簡體   English   中英

我的python代碼有什么問題?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM