Python 验证用户输入时出错
我正在尝试创建一个菜单驱动程序,它将生成5个介于0和9之间的随机整数,并将它们存储在一个列表中。我希望它允许用户输入一个整数,然后搜索列表,如果找到,则报告该整数在列表中的位置,如果没有,则报告-1。然后在屏幕上显示搜索结果并重新显示菜单Python 验证用户输入时出错,python,Python,我正在尝试创建一个菜单驱动程序,它将生成5个介于0和9之间的随机整数,并将它们存储在一个列表中。我希望它允许用户输入一个整数,然后搜索列表,如果找到,则报告该整数在列表中的位置,如果没有,则报告-1。然后在屏幕上显示搜索结果并重新显示菜单 def main(): choice = displayMenu() while choice != '4': if choice == '1': createList() elif ch
def main():
choice = displayMenu()
while choice != '4':
if choice == '1':
createList()
elif choice == '2':
print(createList)
elif choice == '3':
searchList()
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = input("Enter option-->")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print("Invalid option. Please select again.")
return myChoice
import random
def linearSearch(myList):
target = int(input("--->"))
for i in range(len(myList)):
if myList[i] == target:
return i
return -1
#This will generate the five random numbers from 0 to 9
def createList():
newList = []
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
for i in range(5):
newList.append(random.randint(0,9))
return newList
#Option two to display the list
def displayList():
myList = newList
print("Your list is: ", newList)
#Option 3 to search the list
def searchList():
target = int(input("--->"))
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
但是,当它提示用户输入五个数字时,无论您输入什么,它都会说无效。有人能给我举个例子说明如何解决这个问题吗
myChoice = input("Enter option-->")
到
函数输入返回一个整数,与str的比较总是返回False。仔细分析输入。要么将输入保留为字符串并处理字符串,要么最初将其转换为int并继续处理int
myChoice = str(input())
# input 1
if myChoice in ['1', '2', '3', '4']:
print(myChoice)
或
在createList中,输入两次,然后引用未定义的变量a
好的-我在多个地方发现了逻辑和语法错误。我会尽量把它们列出来 已注释掉displayMenu函数中的redundent选项块。 固定的主要功能。您没有捕获由返回的值/列表 功能 将myList定义为需要传递的全局列表 linearSearchmyList,目标有额外的用户输入和调整的逻辑 工作。它只用于在第一个索引中查找数字。理想情况下,您可以使用list.indexvalue方法来获取索引 注释掉createList函数中的额外循环 调整函数以接收全局列表以正常工作。 我尽可能少地修改了你的代码。注释掉的行不是必需的。 我相信它能按预期工作 工作代码: 最后说明,
你可能想从简单的事情开始,比如创建一个菜单,为不同的选择打印不同的句子,看看它是否有效,然后按照你的意愿进行复杂操作。Idk如果这会导致你的问题,但是最好更改你的if statemten if myChoice!='1'和我的选择!='2'和\myChoice!='3'和我的选择!='4':to if myChoice not in[1,2,3,4]:顺便说一句,您可以使用类似if myChoice not in['1','2','3','4']的内容清理那些长if块:。。。嘿,有人抢先接受了我的建议+1@patrick仔细看看,你似乎在比较“字符串”和强制转换与整数。不确定这是否是您的问题,但这样来回转换似乎有点混乱。谢谢你们两位的建议,以清理我的代码!然而,令人遗憾的是,这并不是导致我出现问题的原因。它确实解决了我编辑时的无效选项问题:实际上,将数字更改为整数确实解决了这一问题;好电话@klutt甚至没有看到,当你请求帮助时,请发布一个mcve:对于这个问题,只要显示就足够了。这不是真的a=输入;输入为1的typea`返回str类型。它取决于python版本。在Python3.x中,输入函数返回str。在Python2.x中,输入函数相当于evalraw_inputprompt,因此如果只输入数字,则得到int。啊,没错。我觉得很奇怪typea给我返回了一个字符串,因为我确实记得你说的是真的。我没有意识到他们从Python2.x到3.x.OP的更改显然是在使用Py3,否则程序的任何部分都不会起作用。如果使用Py2,那么最好使用原始输入而不是strinput,因为您不想计算输入。strinput在Py2或Py3中都不是一个好主意:在Py3中它什么都不做。在Py2中,它相当于strevalraw_输入,这将导致意外行为。在Py2中,原始输入是更好的选择。
myChoice = str(input())
# input 1
if myChoice in ['1', '2', '3', '4']:
print(myChoice)
myChoice = int(input())
# input 1
if myChoice in [1, 2, 3, 4]:
print(myChoice)
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
...
if any([num < 0 for num in a]):
Exception
text_input = input("Give me five numbers: ")
numbers = [int(num) for num in text_input.split(' ')]
if any([num < 0 for num in numbers]):
raise ValueError
def linearSearch(myList, target):
if target in myList:
return myList.index(target)
else:
return -1
def main():
myList = []
choice = displayMenu()
while choice != '4':
if choice == '1':
myList =createList()
elif choice == '2':
#print(myList)
displayList(myList)
elif choice == '3':
searchList(myList)
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = str(input("Enter option-->"))
"""
if myChoice != 1 and myChoice != 2 and \
myChoice != 3 and myChoice != 4:
print("Invalid option. Please select again.")
"""
return myChoice
import random
def linearSearch(myList,target):
#target = int(input("--->"))
found = False
for i in range(len(myList)):
if myList[i] == target:
found = True
return i
if found == False:
return -1
#This will generate the five random numbers from 0 to 9
def createList():
print "Creating list..............."
newList = []
"""
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
"""
for i in range(5):
newList.append(random.randint(0,9))
#print newList
return newList
#Option two to display the list
def displayList(myList):
#myList = newList
print("Your list is: ", myList)
#Option 3 to search the list
def searchList(myList):
target = int(input("--->"))
#print("Searching for" , target)
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
>>>
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->1
Creating list...............
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->2
('Your list is: ', [1, 4, 6, 9, 3])
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->4
('Found at', 1)
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->9
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->10
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->10
Not found...
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->4
Thanks for playing!
>>>