pythonraw_input()
函数用于读取从标准输入(如键盘)的字符串。
这样,程序员都能够将用户插入数据插入程序中。
示例:询问用户名。
print "What is your name?" name = raw_input() print "Hello %s!" % name
执行:
$python input.py What is your name? Monty Python Hello Monty Python!
上面的示例也可以缩写为单行,而包括其他新行字符\ n
print "Hello %s!" % raw_input("What is your name?\n")
重要的是要指出,Python函数raw_input()
将生成字符串,因此其输出不能被视为整数。
要获取整数,需要先将所获得的输入字符串转换为整数。
例子:
print "What integer you wish to multiply by 2?" number = int(raw_input()) print "The answer is: %s" % (number * 2) # Alternative shortened version print "The answer is: %s" % (int(raw_input("What integer you wish to multiply by 3?\n")) * 3)
输出:
$python input.py What integer you wish to multiply by 2? 33 The answer is: 66 What integer you wish to multiply by 3? 33 The answer is: 99
日期:2020-07-07 20:54:28 来源:oir作者:oir