2017-02-21 83 views
-1

我想创建一个代码,其中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) 

但是,一旦我让用户输入号码,它不会搜索列表?

+0

你用什么版本的Python? ('输入'在2.6和3.3中的工作方式不同)。 – DyZ

+0

即时通讯使用python 3.6! –

+0

你在哪里定义了linearSearch? – putonspectacles

回答

-1

有一些问题与您的代码

  1. 在你要求用户输入您不使用任何地方五个号码createList功能。
  2. 在主函数中,您正在调用createList(),但您并未将其存储在任何变量中。余吨应该是这样的:

    list=createList()

  3. 在可供选择的主要功能= 2要打印功能本身,而不是你应该做以下:

    print(list)

记住在主函数的开始处声明列表。因为如果用户选择选项2而没有选择1,那么将会出现错误。

  • 你应该在searchList功能通过列表如下:

    def searchList(list): target = int(input("--->")) try: result=list.index(target) print("Found at", result) except: print("Not found")

  • +0

    这非常有帮助!谢谢! –

    -1

    首先linearSearch没有在任何地方定义。假设您已将其定义在某处,则必须将myList转换为searchList函数。

    1

    createlist()被创建列表但searchList()不具有基准到它。 您的searchList()未采用任何参数,所以linearSearch()不知道要搜索哪个列表的编号。

    linearSearch(),可以以更好的方式来定义:

    def linearSearch(myList,target): 
        for i,j in enumerate(myList): 
         if target == j: 
          return i 
         else: 
          return -1