input()函数
函数input()让程序暂停一会,等待用户输入一些文本。获取用户输入后,python将用户输入的内容存储在变量中,以方便你使用
message = input("what would you like to say to yourself now: ")
print(message)
#当运行这个程序时,屏幕上会打印出提示what would you like to say to yourself now: ,然后等待用户输入,当用户输入“I love you”后按enter键,屏幕上就会打印出你输入的信息,I love you,这个运行结果如下所示:
what would you like to say to yourself now: **I love you**
I love you
当给用户的提示可能超过一行时,在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input(),如下所示:
message = "It is very important to keep positive every day." #将消息的前半部分存储在变量message中
message += "\nWhat would you like to say to yourself now: " #运输符+=在存储在message中的字符串末尾附件一个字符串,为了清晰考虑,用了一个换行符\n
content = input(message)
print(content)
#整个运行结果如下:
It is very important to keep positive every day.
What would you like to say to yourself now: **you are the best**
you are the best
使用int()来获取数值输入
age = input("How old are you? ")
if int(age) >= 18: #从input函数输入的数值是用字符串表示,不能直接和数字18相比较,为了将数字的字符串转换为数值表示,用int()函数。
print("Congratulations, you are adult now.")
else:
print("Sorry, you are still too young.")
#整个运行结果为:
How old are you? 10
Sorry, you are still too young.
求模运算符
处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数,如下
>>> 4 % 2
0
>>> 5 % 3
2
>>> 4 % 3
1
如果一个数可被另一个数整除,余数就为0,求模运算也会返回0,可利用这点来判断一个数为奇数还是偶数
number = input("please enter a number, and I will tell you if it is even or odd: ")
if int(number) % 2 == 0:
print("It is an even.")
else:
print("It is an odd.")
# 整个运行结果为:
please enter a number, and I will tell you if it is even or odd: **4**
It is an even.