Python学习入门之用户输入
用户输入函数 input()
函数input让程序暂停运行,等待用户输入一些文本,获取用户输入后,将其存储到在一个变量中
使用input函数,python将用户输入解读为字符串
input函数接受一个参数:即要向用户显示的提示或说明
简单示例
message = input("Tell me something ,and I will repeat it back to you :")
print(message)
使用int函数将数字的字符串表示转换为数值表示
age = input("Please input your age:")
age = int(age)
if age >= 18 :
print("you are old enough to vote.")
else:
print("sorry,you are too young to vote.")
求模运算符(%)
它将两个数相除并返回余数
num = int(input("Enter a number,and I'll tell you if it's even or odd:"))
if num % 2 ==0:
print("\n the number " + str(num) + " is even.")
else:
print("\n the number " + str(num) + " is odd.")
在python 2.7中获取输入
如果使用的是python 2.7,应使用raw_input()来提示用户输入。这个函数与python 3中的input()一样,也将输入解读为字符串。
python 2.7中也包含input(),但它将用户输入解读为为python 代码,并将尝试运行它们。因此,最好的结果是出现错误,指出python不明白输入的代码;最糟糕的结果是,将运行原本无意运行的代码。因此,如果使用的是 python 2.7 ,请使用raw_input()而不是input()来获取输入