Home > Blockchain >  How can I specify an unknown number in a list as a conditional statement in a for loop?
How can I specify an unknown number in a list as a conditional statement in a for loop?

Time:01-16

def find_num():
    list = [5, 8, 4, 6, 9, 2]
    limit = len(list)
    tries = 0
    for tries in range(limit):
        tries  = 1
        answer = input("Type a guess: ")
        if tries > limit:
            break
        elif answer == int in list:
            print("Correct guess!")
        else:
            print("Wrong!")

find_num()

This script simply asks for a user to type in a guess than check if that number is in the list or not and responds accordingly. The limit and tries variables are so that the user cannot infinitly keep guessing. And its working fine except for the line elif answer == int in list, its not working because I cannot specify an unknown nuumber in the list. I have tried list[int], x in int and in list[i]. It breaks the loop after 6 tries but just prints out 'Wrong' everytime.

CodePudding user response:

Code:

def find_num():
    lst = [5, 8, 4, 6, 9, 2]
    limit = len(lst)
    for tries in range(limit):
        answer = int(input("Type a guess: "))

        if answer in lst:
            print("Correct guess!")
        else:
            print("Wrong!")
  • tries = 0 and tries = 1 is not necessary in for loop.
  • Type casting is done by int(answer) not by answer == int
if tries > limit:
    break
  • The above condition is tested by for loop itself.

CodePudding user response:

I have refactored it to something like.

def find_num():
    numbers_to_guess = [5, 8, 4, 6, 9, 2]
    limit = len(numbers_to_guess)
    tries = 0
    while True:
        tries  = 1
        answer = input("Type a guess: ")
        if tries > limit:
            break
        elif int(answer) in numbers_to_guess:
            print("Correct guess!")
        else:
            print("Wrong!")


find_num()

Notes:

  1. You can use list as a variable name. This is a reserved keyword.
  2. You should have used a while loop instead of a for loop.
  3. You should also remember to check that entered guess is a valid integer before conversion.
  •  Tags:  
  • Related