我试图创建一个菜单驱动的程序,它将生成0到9之间的5个随机整数,并将它们存储在List中。我想让它然后允许用户输入一个整数,然后搜索List,报告List中整数的位置(如果找到),否则返回-1。然后将搜索结果显示在屏幕上并重新显示菜单。
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()
然而,当它提示用户输入五个数字时,无论你输入什么内容,它都会显示无效。有人可以举个例子说明我如何解决这个问题吗?
答案 0 :(得分:1)
小心输入解析。将输入保留为字符串并处理字符串,或者最初将其转换为int并继续处理整数。
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)
答案 1 :(得分:1)
在createList
中,您将input
两次,然后引用未定义的变量a
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
你的程序有许多其他的奇怪之处,但也许你还在研究这些:
createList
中输入的数字执行任何操作,而是返回随机数列表。您的描述还建议您想要一个随机数列表,那么为什么要输入数字?myList
和newList
,但除非您将其声明为global
或明确将其作为参数传递,否则您的函数将无法访问这些变量linearSearch
可以使用list.index
更简单地编写:
def linearSearch(myList, target):
if target in myList:
return myList.index(target)
else:
return -1
答案 2 :(得分:0)
好的 - 我在多个地方发现了逻辑和语法错误。我会尽量列出它们。
displayMenu()
函数中注释掉了redundent选项块。myList
定义为需要传递的全局列表linearSearch(myList,target)
有额外的用户输入和调整逻辑
上班。它只适用于在第一个索引处查找数字。理想情况下,您可以使用list.index(value)
方法获取索引#createList()
函数我尽可能少地调整了你的代码。注释掉不需要的行。 我相信它按预期工作。
工作代码:
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!
>>>
最后的笔记, 您可能希望从简单的事情开始,例如创建一个菜单,为不同的选择打印不同的句子,看它是否有效,然后根据您的意愿复杂化。
答案 3 :(得分:-1)
更改
myChoice = input("Enter option-->")
到
myChoice = str(input("Enter option-->"))
函数输入返回一个整数,与str的比较总是返回False。