'repeat a process in Python
I want to repeat asking number process while guess is not equal with TrueNum but when I put it in while loop it just repeats the print of its "if" what should I do?
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
Guess = int(input("Input your number: "))
# Checking Guess:3
while Guess != TrueNum:
if Guess > TrueNum:
print("You Are Getting Far...")
elif Guess < TrueNum:
print("It`s bigger than you think :)")
break
if Guess == TrueNum:
print("yeah that`s it")
Solution 1:[1]
You need to put the input inside the while, and is good also to take out some unnecessary conditions:
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
Guess = int(input("Input your number: "))
# Checking Guess:3
while Guess != TrueNum:
if Guess > TrueNum:
print("You Are Getting Far...")
else:
print("It`s bigger than you think :)")
Guess = int(input("Input your number: "))
print("yeah that`s it")
Solution 2:[2]
Using Try/Except allows you to address an invalid choice while also keeping readability.
import random
# Defining True Num:
DataRange = list(range(0, 11))
TrueNum = int(random.choice(DataRange))
print("it`s in range from o to 10")
# Getting Guesses From User:
while True:
try:
Guess = int(input("Input your number: "))
if Guess > TrueNum:
print("You Are Getting Far...")
elif Guess < TrueNum:
print("It`s bigger than you think :)")
elif Guess == TrueNum:
print("yeah that`s it")
break
except ValueError:
print("Invalid Choice")
Solution 3:[3]
The variable Guess is defined outside the loop, you should put the input and check the value inside the loop.
import random
datarange = list(range(0, 11))
trueNum = int(random.choice(datarange))
print("Guess the number! It`s in range from o to 10")
while True:
Guess = int(input("Input your number: "))
if Guess == trueNum:
print("Yeah that`s it")
break
elif Guess > trueNum:
print("You Are Getting Far...")
else:
print("It`s bigger than you think :)")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ziur Olpa |
| Solution 2 | |
| Solution 3 | I-am-developer-9 |
