[英]what is wrong in my python code?
#!usr/bin/python
listofnames = []
names = input("Pls enter how many of names:")
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print listofnames
错误
inname = input("Enter the name " + str(x))
文件“”,第1行,在NameError中:未定义名称“ Jhon”
请改用raw_input
。 请参阅http://docs.python.org/library/functions.html#raw_input 。 input
将执行与eval(raw_input(prompt))
,因此在Jhon
输入将尝试在文件中查找符号Jhon
(不存在)。 因此,对于您现有的脚本,您必须在提示中输入'Jhon'
(注意引号),以便eval将值转换为字符串。
这是input
文档中的摘录警告。
警告
此功能对用户错误不安全! 它期望一个有效的Python表达式作为输入; 如果输入在语法上无效,则将引发SyntaxError。 如果评估期间出现错误,可能会引发其他例外情况。 (另一方面,有时候这正是编写供专家使用的快速脚本时需要的。)
下面是更正的版本:
#!usr/bin/python
# The list is implied with the variable name, see my comment below.
names = []
try:
# We need to convert the names input to an int using raw input.
# If a valid number is not entered a `ValueError` is raised, and
# we throw an exception. You may also want to consider renaming
# names to num_names. To be "names" sounds implies a list of
# names, not a number of names.
num_names = int(raw_input("Pls enter how many of names:"))
except ValueError:
raise Exception('Please enter a valid number.')
# You don't need x=1. If you want to start your name at 1
# change the range to start at 1, and add 1 to the number of names.
for x in range(1, num_names+1)):
inname = raw_input("Enter the name " + str(x))
names.append(inname)
print names
注意:这适用于Python2.x。 Python3.x已解决输入与raw_input混淆的问题,如其他答案所述。
input
从用户那里获取文本,然后将其解释为Python代码(因此,它试图评估您输入的内容Jhon
)。 您都需要raw_input
,并且需要将输入的数字(因为它是字符串)转换为您range
的整数。
#!usr/bin/python
listofnames = []
names = 0
try:
names = int(raw_input("Pls enter how many of names:"))
except:
print "Problem with input"
for x in range(0, names):
inname = raw_input("Enter the name %d: "%(x))
listofnames.append(inname)
print listofnames
在python3中, input()
现在就像raw_input()
。 但是,要使您的代码与Python3配合使用,仍需要进行一些更改
#!usr/bin/python3
listofnames = []
names = int(input("Pls enter how many of names:"))
x = 1
for x in range(0, names):
inname = input("Enter the name " + str(x))
listofnames.append(inname)
print(listofnames)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.