我的python学习笔记.用户输入.函数input()的工作原理

来源:互联网 发布:剑三冷艳花姐捏脸数据 编辑:程序博客网 时间:2024/06/10 10:25

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

#helloword.py
message=input("Tell me something,and I will repeat it back to you: ")
print(message)

输出为:

D:\www>python helloword.py
Tell me something,and I will repeat it back to you: haha
haha

实例之编写清晰的程序:

#helloword.py
prompt="If you tell us who you are,we can personalize the massages you see."
prompt+="\nwhat is your first name? "
message=input(prompt)
print("\nHello, "+message+"!")

输出为:

D:\www>python helloword.py
If you tell us who you are,we can personalize the massages you see.
what is your first name? jin

Hello, jin!

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

使用函数input()时,python将用户输入解读为字符串,可使用函数int(),它让python将输入视为数值。

>>> 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: '>=' not supported between instances of 'str' and 'int'
>>> age=int(age)
>>> age>=18
True

将数值输入用于计算和比较前,务必将其转换为数值表示。

实例:

#helloword.py
height=input("How tall are you?")
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.")

输出为:

D:\www>python helloword.py
How tall are you?162

You're tall enough to ride!

3、求模运算符

#helloword.py
number=input("Enter a number,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.")

输出为:

D:\www>python helloword.py
Enter a number,I'll tell you if it's even or odd:3

The number 3 is odd.











原创粉丝点击