7.1.1 编写清晰的程序
例:
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
函数input接受一个参数:即向用户显示的提示或说明。上述代码的运行结果如下:
Tell me something, and I will repeat it back to you: Hello everyone!
同理,有例子:
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\nHello, " + name + "!")
7.1.2 使用int()来获取数值输入
height = input("How tall are you, in inches?")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
在该程序中,我们在输入height后,Python将这个数字解读为一个字符串。但随后int()将这个字符串转换为了数值表示。将数值输入用于计算和比较前,务必将其转换为数值表示。
7.1.3 求模运算符
例:
number = input("Enter a number, and I’ll tell you if it’s even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")