函数input()的工作原理
- 函数input()让程序暂停运行,等待用户输入一些文本,获取用户输入后,python将其变量存储在一个变量中,以方便实用。
- input()接收一个参数,即向用户显示的提示或说明。
message = input("Tell me something,and I will repaeat it back to you : ")
print(message)
Tell me something,and I will repaeat it back to you : hello
hello
编写清晰的程序
- 使用input()函数时,都应指向清晰而易于明白的提示。
- 可将提示存储在一个变量中,再将变量传递给函数input()
name = input("Please enter your name: ")
print("Hello, " + name + "!")
Please enter your name: yegeli
Hello, yegeli!
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 + "!")
If you tell us who you are, we can personalize the message you see.
What is your first name? yegeli
Hello, yegeli!
使用int()来获取数值输入
- 用户输入的数值为字符串表示
- 函数int()将数字的字符串表示转换为数值表示
- 将数值输入用于计算和比较前,务必将其转换为数值表示
age = input("How old are you? ")
age
How old are you? 21
'21'
age = input("How old are you ? ")
age = int(age)
age >=18
How old are you ? 21
True
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 order.")
How tall are you ,in inches? 30
You'll be able to ride when you're a little order.
求模运算符
- % 它将两个数想出并返回余数:
- 一个数可被另一个数整除,余数就为 0 ,因此求模运算符将返回 0 。你可利用这一点来判断一个数是奇数还是偶数
number = input("Enter a number, and I'll tell you if it's enven or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even")
else:
print("\nThe number " + str(number) + " is odd")
Enter a number, and I'll tell you if it's enven or odd: 22
The number 22 is even
练习
prompt = "brother,DO you want to rent a car? "
message = input(prompt)
print("Let me see if I can fin you a " + message.title() + " !")
brother,DO you want to rent a car? subaru
Let me see if I can fin you a Subaru !
order_food = input("How many people order meals? ")
order_food = int(order_food)
if order_food >= 8:
print("Sorry there are no vacant tables.")
else:
print("\nGreat,there are still tables available.")
How many people order meals? 4
Great,there are still tables available.
multiple = input("Please enter a number! ")
multiple = int(multiple)
if multiple % 10 == 0:
print(str(multiple) + " is 10 multiple.")
else:
print(str(multiple) + " is not 10 multiple.")
Please enter a number! 110
110 is 10 multiple.