我想創建一個代碼,其中Python將生成零和九之間的五個隨機數,然後將它們存儲在列表中。我需要程序來允許用戶輸入一個整數然後搜索列表。搜索整數列表
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 is where I need it to ask the user to give five numbers
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
#This is where the user should be able to search the list
def searchList():
target = int(input("--->"))
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
但是,一旦我讓用戶輸入號碼,它不會搜索列表?
你用什麼版本的Python? ('輸入'在2.6和3.3中的工作方式不同)。 – DyZ
即時通訊使用python 3.6! –
你在哪裏定義了linearSearch? – putonspectacles