False def if raise None del import return True elif in try and else is while as except lambda with assert finally nonlocal yield break for not class from or continue global pass
#!/usr/bin/env python3 number = int(input("Enter an integer: ")) if number < 100: print("Your number is smaller than 100") else: print("Your number is greater than 100")
如果 number 小于 100,输出“Your number is smaller than 100”,如果大于 100,输出“Your number is greater than 100”。
$ ./testhundred.py Enter an integer: 13 Your number is smaller than 100 $ ./testhundred.py Enter an integer: 123 Your number is greater than 100
下一个程序我们来计算投资:
1 2 3 4 5 6 7 8 9 10 11
#!/usr/bin/env python3 amount = float(input("Enter amount: ")) # 输入数额 inrate = float(input("Enter Interest rate: ")) # 输入利率 period = int(input("Enter period: ")) # 输入期限 value = 0 year = 1 while year <= period: value = amount + (inrate * amount) print("Year {} Rs. {:.2f}".format(year, value)) amount = value year = year + 1
运行程序:
1 2 3 4 5 6 7 8 9
$ ./investment.py Enter amount: 10000 Enter Interest rate: 0.14 Enter period: 5 Year 1 Rs. 11400.00 Year 2 Rs. 12996.00 Year 3 Rs. 14815.44 Year 4 Rs. 16889.60 Year 5 Rs. 19254.15
while year <= period: 的意思是,当 year 的值小于等于 period 的值时,下面的语句将会一直循环执行下去,直到 year 大于 period 时停止循环。
Year {} Rs. {:.2f}".format(year, value) 称为字符串格式化,大括号和其中的字符会被替换成传入 str.format() 的参数,也即 year 和 value。其中 {:.2f} 的意思是替换为 2 位精度的浮点数。
一些例子
一些关于变量和数据类型的例子。
求 N 个数字的平均值
下面的程序用来求 N 个数字的平均值。
1 2 3 4 5 6 7 8 9 10 11
#!/usr/bin/env python3 N = 10 sum = 0 count = 0 while count < N: number = float(input()) sum = sum + number count = count + 1 average = sum / N print("N = {}, Sum = {}".format(N, sum)) print("Average = {:.2f}".format(average))
运行程序:
1 2 3 4 5 6 7 8 9 10 11 12 13
$ ./averagen.py 1.2 3.4 3.5 33.2 2 4 6 2.4 4 5.5 N = 10, Sum = 65.2 Average = 6.52