while
浮点数不用作判定条件
for
range: an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
for i in range(initvalue,endvalue):
print(i)
for var in sequence:
print(val)
# in function :range(a) 等于 rang(0,a)
# in function :range(a,b,k) 以步长k从a走到b
最大公约数(GCD)
- 常规的方法,i是不是n1的约数,是不是n2的约数,依次遍历到n1和n2 的较小的值
import math
x1, x2 = eval(input("enter x1,x2:"))
gcd = 0
if x1 > x2:
x1, x2 = x2, x1
for i in range(1, x1+1):
if x1 % i ==0 & x2 % i == 0:
gcd = i
print(gcd, end="\t")
print(math.gcd(x1, x2))
- 辗转相除法:
import math
x1, x2 = eval(input("enter x1,x2:"))
gcd = 0
if x1 > x2:
x1, x2 = x2, x1
# 大的除以小的,再将余数进行除
div = 0
# x2 is bigger than x1
while x1 != 0:
temp = x2 % x1
x2 = x1
x1 = temp
print(x2)
print(math.gcd(x2, x1))
预测未来学费
import math
tuition = eval(input("please enter tuition:"))
target = 2 * tuition
i=0
while tuition < target:
tuition *= 1.07
i+=1
print("total tuition is ", format(tuition, ".2f"), "passed ", format(i, ".2f"), "years")
蒙特卡罗模拟
import random
NUMBER_OF_TRIALS = 1000000
numberOfHits = 0
for i in range(NUMBER_OF_TRIALS):
x = random.random()*2 - 1
y = random.random()*2 - 1
if x**2 + y**2 <= 1:
numberOfHits += 1
print("pi = ", 4 * numberOfHits / NUMBER_OF_TRIALS)
break continue
- and和not 和c不同
- break 跳出整个循环,continue 语句只是退出当前循环