How to make a loop in python three that stops when you input the correct word/number

General Tech Bugs & Fixes 2 years ago

0 3 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (3)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I am making a text based adventure game in python 3 and I was wondering what the simplest loop is. Using the code I have, it continues to print "whats the number" even when you put the correct number, also giving 9 as input doesnt work. It also doesn't work when I give ("8","9"). Here is my code :

print("whats the number?")
required_number = ("8" or "9")

while True:
    number = input()
    if number == required_number:
        print ("GOT IT")
    else: print ("Wrong number try again")
profilepic.png
manpreet 2 years ago

Try this :

print("whats the number?")
required_number = [8,9]
while True:
    number = int(input())
    if number in required_number :
        print('GOT IT')
        break
    else:
        print('Wrong number try again')

Sample output in shell :

whats the number?
5
Wrong number try again
2
Wrong number try again
4
Wrong number try again
8
GOT IT

0 views   0 shares

profilepic.png
manpreet 2 years ago

If your required_number or the input will accommodate a string, then you can use this:

required_number = [8,9]
required_number = str(required_number)
number = None

while True:
    number = input("Write a number: ")
    if number in required_number:
        print ("GOT IT")
    else: 
        print ("Wrong number try again")

Output:

Write a number: 3
Wrong number try again
Write a number: 8
GOT IT
Write a number: Hi
Wrong number try again

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.