有不少同学反映我之前发的Python代码太高级看不懂,让写点简单的代码实例集供他们学习。
下面就来分享50多个实例吧,特别适合初学者
实例1:
print('hello world')
实例2:
x = 55 / 11
print(x)
实例3:
x = 50 * 2 + (60 - 20) / 4
print(x)
实例4:
# This is a comment
answer = 42 # the answer
# Now back to the puzzle
text = "# Is this a comment?"
print(text)
实例5:
x = 'silent'
print(x[2] + x[1] + x[0]
+ x[5] + x[3] + x[4])
实例6:
squares = [1, 4, 9, 16, 25]
print(squares[0])
实例7:
word = "galaxy"
print(len(word[1:]))
实例8:
x = 50 // 11
print(x)
实例9:
print(3 * 'un' + 'ium')
实例10:
x = 'py' 'thon'
print(x)
实例11:
print(sum(range(0, 7)))
实例12:
cubes = [1, 8, 27]
cubes.append(4 ** 3)
print(cubes)
实例13:
word = "galaxy"
print(word[4:50])
实例14:
x = 51 % 3
print(x)
实例15:
def if_confusion(x, y):
if x > y:
if x - 5 > 0:
x = y
return "A" if y == y + y else "B"
elif x + y > 0:
while x > y: x -= 1
while y > x: y -= 1
if x == y:
return "E"
else:
if x - 2 > y - 4:
x_old = x
x = y * y
y = 2 * x_old
if (x - 4) ** 2 > (y - 7) ** 2:
return "C"
return "D"
return "H"
print(if_confusion(3, 7))
实例16:
x = 'cool'
print(x[-1] + x[-2]
+ x[-4] + x[-3])
实例17:
words = ['cat', 'mouse']
for word in words:
print(len(word))
实例18:
def func(x):
return x + 1
f = func
print(f(2) + func(2))
实例19:
word = "galaxy"
print(word[:-2] + word[-2:])
实例20:
def func(a, *args):
print(a)
for arg in args:
print(arg)
func("A", "B", "C")
实例21:
def ping(i):
if i > 0:
return pong(i - 1)
return "0"
def pong(i):
if i > 0:
return ping(i - 1)
return "1"
print(ping(29))
实例22:
word = "bender"
print(word[1:4])
实例23:
customers = ['Marie', 'Anne', 'Donald']
customers[2:4] = ['Barack', 'Olivia', 'Sophia']
print(customers)
实例24:
def ask(prompt, retries=4, output='Error'):
for _ in range(retries):
response = input(prompt).lower()
if response in ['y', 'yes']:
return True
if response in ['n', 'no']:
return False
print(output)
print(ask('Want to know the answer?', 5))
实例25:
letters = ['a', 'b', 'c', 'd']
print(len(letters[1:-1]))
实例26:
a = ['a', 'b']
n = [1, 2]
x = [a, n]
print(x[1])
实例27:
letters = ['a', 'b', 'c',
'd', 'e', 'f', 'g']
letters[1:] = []
print(letters)
实例28:
# Fibonacci series:
a, b = 0, 1
while b < 5:
print(b)
a, b = b, a + b
实例29:
for num in range(2, 8):
if not num % 2:
continue
print(num)
实例30:
print(range(5, 10)[-1])
print(range(0, 10, 3)[2])
print(range(-10, -100, -30)[1])
实例31:
def matrix_find(matrix, value):
if not matrix or not matrix[0]:
return False
j = len(matrix) - 1
for row in matrix:
while row[j] > value:
j = j - 1
if j == -1:
return False
if row[j] == value:
return True
return False
matrix = [[3, 4, 4, 6],
[6, 8, 11, 12],
[6, 8, 11, 15],
[9, 11, 12, 17]]
print(matrix_find(matrix=matrix, value=11))
实例32:
def maximum_profit(prices):
'''Maximum profit of a single buying low and selling high'''
profit = 0
for i, buy_price in enumerate(prices):
sell_price = max(prices[i:])
profit = max(profit, sell_price - buy_price)
return profit
# Ethereum daily prices in Dec 2017 ($)
eth_prices = [455, 460, 465, 451, 414, 415, 441]
print(maximum_profit(prices=eth_prices))
实例33:
def bubble_sort(lst):
'''Implementation of bubble sort algorithm'''
for border in range(len(lst)-1, 0, -1):
for i in range(border):
if lst[i] > lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
return lst
list_to_sort = [27, 0, 71, 70, 27, 63, 90]
print(bubble_sort(lst=list_to_sort))
实例34:
def concatenation(*args, sep="/"):
return sep.join(args)
print(concatenation("A", "B", "C", sep=","))
实例35:
x = 5 * 3.8 - 1
print(x)
实例36:
def bsearch(l, value):
lo, hi = 0, len(l)-1
while lo <= hi:
mid = (lo + hi) // 2
if l[mid] < value:
lo = mid + 1
elif value < l[mid]:
hi = mid - 1
else:
return mid
return -1
l = [0, 1, 2, 3, 4, 5, 6]
x = 6
print(bsearch(l,x))
实例37:
words = ['cat', 'mouse', 'dog']
for word in words[:]:
if len(word) > 3:
words.insert(0, word)
print(words[0])
实例38:
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
print(f(0))
print(f(1))
实例39:
print("""
A
B
C
""" == "\nA\nB\nC\n")
实例40:
print('P"yt\'h"on')
实例41:
def fibo(n):
"""Return list containing
Fibonacci series up to n.
"""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a + b
return result
fib100 = fibo(100)
print(fib100[-1] ==
fib100[-2] + fib100[-3])
实例42:
def qsort1(L):
if L:
return qsort1([x for x in L[1:] if x < L[0]]) + L[:1] \
+ qsort1([x for x in L[1:] if x >= L[0]])
return []
def qsort2(L):
if L:
return L[:1] + qsort2([x for x in L[1:] if x < L[0]]) \
+ qsort2([x for x in L[1:] if x >= L[0]])
return []
print(qsort1([0, 33, 22]))
print(qsort2([0, 33, 22]))
实例43:
def func(val1=3, val2=4, val3=6):
return val1 + val2 + val3
values = {
"val1":9, "val3":-1}
print(func(**values))
实例44:
print("Answer")
while True:
pass
print("42")
实例45:
def has_path(graph, v_start, v_end, path_len=0):
'''Graph has path from v_start to v_end'''
# Traverse each vertex only once
if path_len >= len(graph):
return False
# Direct path from v_start to v_end?
if graph[v_start][v_end]:
return True
# Indirect path via neighbor v_nbor?
for v_nbor, edge in enumerate(graph[v_start]):
if edge: # between v_start and v_nbor
if has_path(graph, v_nbor, v_end, path_len + 1):
return True
return False
# The graph represented as adjancy matrix
G = [[1, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[1, 0, 0, 1, 1]]
print(has_path(graph=G, v_start=3, v_end=0))
实例46:
pairs = [(1, 'one'),
(2, 'two'),
(3, 'three'),
(4, 'four')]
# lexicographical sorting (ascending)
pairs.sort(key=lambda pair: pair[1])
print(pairs[0][1])
实例47:
# popular instagram accounts
# (millions followers)
inst = {
"@instagram":232,
"@selenagomez":133,
"@victoriassecret":59,
"@cristiano":120,
"@beyonce":111,
"@nike":76}
# popular twitter accounts
# (millions followers)
twit = {
"@cristiano":69,
"@barackobama":100,
"@ladygaga":77,
"@selenagomez":56,
"@realdonaldtrump":48}
inst_names = set(filter(lambda key: inst[key]>60, inst.keys()))
twit_names = set(filter(lambda key: twit[key]>60, twit.keys()))
superstars = inst_names.intersection(twit_names)
print(list(superstars)[0])
实例48:
words_list = ["bitcoin",
"cryptocurrency",
"wallet"]
crawled_text = '''
Research produced by the University of
Cambridge estimates that in 2017,
there are 2.9 to 5.8 million unique
users using a cryptocurrency wallet,
most of them using bitcoin.
'''
split_text = crawled_text.split()
res1 = True in map(lambda word: word in split_text, words_list)
res2 = any(word in words_list for word in split_text)
print(res1 == res2)
实例49:
def encrypt(text):
encrypted = map(lambda c: chr(ord(c) + 2), text)
return ''.join(encrypted)
def decrypt(text):
decrypted = map(lambda c: chr(ord(c) - 2), text)
return ''.join(decrypted)
s = "xtherussiansarecomingx"
print(decrypt(encrypt(encrypt(s))) == encrypt(s))
实例50:
import random
def guess(a, b):
return random.randint(a, b)
def check(x, y):
return y ** 2 == x
x = 100
left, right = 0, x
y = guess(left, right)
while not check(x, y):
y = guess(left, right)
print(y)
实例51:
print('andunderst'[3:6] + 'andunderst'[6:10] + 'andunderst'[0:3])
上面50个实例代码,大家有兴趣的可以进行下,然后把运行结果发评论区。