for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n // x) break else: # loop fell through without finding a factor print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
4.5 pass 语句
pass 语句什么也不做。当语法上需要一个语句,当程序需要什么动作也不做时,可以使用它。
1 2
# while True: # pass # Busy-wait for keyboard interrupt (Ctrl+C)
1 2 3
# 通常用于创建最小的类 classMyEmptyClass: pass
1 2 3
# 编写函数时作为占位符,允许你保持在更抽象的层次上进行思考 definitlog(*args): pass# Remember to implement this!
4.6 定义函数
1 2 3 4 5 6 7
deffib(n):# write Fibonacci series up to n """Print a Fibonacci series up to n.""" a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print()
1 2
# Now call the function we just defined: fib(2000)
defcheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) for kw in keywords: print(kw, ":", keywords[kw])
1 2 3 4 5
cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch