python随笔6(用户输入input())

6.1函数input()

函数input()让程序暂停运行,等待用户一些文本输入。获取用户输入后,python将其存储在一个变量中。例如:

message = input("Tell me something:")
print(message)

函数input()接受一个参数。程序等待用户输入,并在用户按回车键后继续运行。输入存储在变量message中,接下来的print(message)将输入呈现给用户。

Tell me something:hello everyone!
hello everyone!

编写清晰的程序

每当你使用函数input()时,都应指定清晰而明白的提示,准确地指出你希望用户提供什么样的信息,如下:

name = input("please enter your name:")
print("Hello," + name + "!")
please enter your name:AAAz
Hello,AAAz!

有时候,提示可能超过一行。在这种情况下,可将提示存储在一个变量中,再将该变量传递给函数input()。

prompt = "If you tell us who you are,we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print("\nHello," + name + "!")

这种示例演示了一种创建多行字符串的方式。第1行将消息的前半部分存储在变量prompt中;在第2行中,运算符 += 在存储在prompt中的字符串末尾附加一个字符串。

使用int()来获取数值输入

使用input()函数时,python将用户输入解读为字符串。请看下面让让用户输入其年龄的解释器会话:

>>> age = input("How old are you? ")
How old are you? 21
>>>age
'21'

用户输入的是数字21,但我们请求python提供变量age的值时,它返回的是’21’——用户输入的数值字符串表示。

>>> age = input("How old are you? ")
How old are you? 21

>>> age >= 18
Traceback (most recent call last):
  File "<stdin>",line 1, in <module>
TypeError: unorderable types: str() >= int()

你试图将输入用于数值比较时,python会发生错误,因为它无法将数字与字符串比较。

为解决这个问题,可以使用函数int(),它让python将输入是为数值。函数int()将数字的字符串表示转换为数值表示:

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True

在实际程序中使用函数int()。下面程序判断一个人的身高够不够坐过山车。

height = input("How tall are you,in inches? ")
height = int(height)

if height >= 160:
    print("\nYou are tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")

求模运算符

处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:

扫描二维码关注公众号,回复: 2509352 查看本文章
>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0

你可以利用求模运算来判断一个数是奇数还是偶数。

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.")

猜你喜欢

转载自www.cnblogs.com/wf1017/p/9403719.html
今日推荐