How can I exit if a certain condition is met? The input in the loop is still popping up after I wrote the correct answer.
I've tried using exit(), break, system.exit, system.quit
x = int(input("write a number : "))
y = int(input("write another number : "))
result = x * y
guess = int(input(str(x) + " is multiplied to "+ str(y) + " is equals to? \n " ))
if guess == result:
print("congrats")
### if this condition is met i want to end here
guess1 = 0
while guess1 != result:
guess1 = int(input("write another answer : "))
if guess1 == result:
print("this time you got it")
I want to get rid of the other input if the other condition is met.
Just add an else statement after the if block. It will either stop the code if the condition is met or it will continue to the else part of the code.
if guess == result:
print("congrats")
### if this condition is met it will print congrats and stop
else:
guess1 = 0
while guess1 != result:
guess1 = int(input("write another answer : "))
if guess1 == result:
print("this time you got it")
The easiest way is to set result to 0 if the condition is met.
x = int(input("write a number : "))
y = int(input("write another number : "))
result = x * y
guess = int(input(str(x) + " is multiplied to "+ str(y) + " is equals to? \n " ))
if guess == result:
print("congrats")
result = 0 # if the condition is met, the while loop would never run if the result is the same as guess1
guess1 = 0
while guess1 != result:
guess1 = int(input("write another answer : "))
if guess1 == result:
print("this time you got it")
###I want to get rid of the other input if the other condition is met
You could use else to skip part of code
if guess == result:
print("congrats")
else:
guess1 = 0
while guess1 != result:
guess1 = int(input("write another answer : "))
if guess1 == result:
print("this time you got it")
# this line will be executed
Or exit() to exit script
if guess == result:
print("congrats")
### if this condition is met i want to end here
exit()
guess1 = 0
while guess1 != result:
guess1 = int(input("write another answer : "))
if guess1 == result:
print("this time you got it")
Two solutions:
Put that code inside of a function and use return when you want to terminate the whole thing.
Use sys.exit(0) at the point where you want to terminate. You'd need to import the sys module (import sys) for that.
On another note, you could just refactor your code and make it much cleaner by:
Setting the guess to None initially and then entering the loop. Your code will be:
x = int(input("write a number : "))
y = int(input("write another number : "))
result = x * y
guess = None
while guess != result:
guess = int(input("write another answer : "))
if guess == result:
print("congrats")
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm trying to create a number guessing game but when I run this it keeps running the while loop and doesnt break out. (very new to python by the way) thanks!
from random import randint
name1 = input("What is Player One's first name? ")
name2 = input("What is Player Two's first name? ")
cnumber = randint(1,25)
guess1 = ""
guess2 = ""
times_guessed1 = 0
times_guessed2 = 0
while guess1 != cnumber and guess2 != cnumber:
guess1 = input(name1 + " guess a number between 1 and 25: ")
times_guessed1 += 1
guess2 = input(name2 + " guess a number between 1 and 25: ")
times_guessed2 += 1
if guess1 == cnumber:
print (name1, "wins!")
print ("You guessed,", times_guessed1, "times.")
elif guess2 == cnumber:
print (name2, "wins!")
print ("You guessed,", times_guessed2, "times.")
input() returns a str.
randint(1,25) returns an int.
When it compares, '2' with 2, it will be false in python.
Solution: convert the input to int like below.
guess1 = int(input(name1 + " guess a number between 1 and 25: "))
guess2 = int(input(name2 + " guess a number between 1 and 25: "))
input will return a string use int(input()) to covert to int to be able to match with randint
cnumber is an int, but guess1 and guess2 are strings, so they are never equal, because their types are different. The easiest would be to convert cnumber to a string: cnumber = str(randint(1,25)).
I'm making a guess the number game in Python but it just wont work.
I want it to just say guess and then you guess it until its true. Sorry if the solution is so simple because I'm a beginner(I have been learning python for 3 days).
import random
while True:
print("Choose number gap(0-10,0-100)")
gap = input()
if gap == "0-10":
number = random.randint(0,10)
print("Guess")
guess = int(input())
if guess == number:
print("True the number was: ", number)
while guess != number:
print("False")
guess = int(input())
if gap == "0-100":
number = random.randint(0,100)
print(number)
guess = int(input())
if guess == number:
print("True the number was: ", number)
while guess != number:
print("False")
guess = int(input())
To do what you want, you'll need to use a loop. In this case, a while loop will be used. We'll check to see if the inputted number is equal to the random number. When it's not, the loop will repeat until it is correct, and then repeat the program again.
import random
while True:
print("Choose number gap(0-10,0-100)")
gap = input()
if gap == "0-10":
number = random.randint(0,10)
print("Guess")
guess = int(input())
while guess != number:
print("False. Guess again")
guess = int(input())
print("True the number was: ", number)
if gap == "0-100":
number = random.randint(0,100)
print("Guess")
guess = int(input())
while guess != number:
print("False. Guess again")
guess = int(input())
print("True the number was: ", number)
You can run while first, until true. And you don't have to call input alone first.
import random
while True:
print("Choose number gap(0-10,0-100)")
gap = input()
guess = -1
if gap == "0-10":
number = random.randint(0,10)
print("Guess")
while guess != number:
guess = int(input())
print("False")
print("True the number was: ", number)
elif gap == "0-100":
number = random.randint(0,100)
print("Guess")
while guess != number:
guess = int(input())
print("False")
print("True the number was: ", number)
I'm working on a simple python script that when run allows for an input of a number, then asks if another number input is wanted, if yes, the input entry is displayed, this is repeated until the answer is no when asked if another number input is needed.
Once "no" is entered, I need to sum all the numbers that were input and output it.
This part I have working, however, the issue I am facing is when the question is asked if another input is needed, if there is anything other than "Y"/"YES"/"N"/"NO" an error is displayed, in the summed output the error count is also being included and I can't quite figure out how to exclude the errors.
Here's the script:
total = 0
num = 1
while num > 0:
if num > 0:
total = total + num
cont = input("Would you like to enter another number: ").upper()
if cont == "Y" or cont == "YES":
float(input("Please enter number: \n"))
continue
if cont == "N" or cont == "NO":
print("The total of the numbers is", total)
break
if cont != "N" and cont != "NO" and cont != "Y" and cont != "YES":
print("Invalid response. Please enter Y or N")
continue
There's a lot going on here, but I've tried to refactor your code a bit to help you understand:
# Set up total:
total = 0
# Keep asking for numbers until we answer 'NO':
while True:
# Ask user if they want to continue
cont = input("Would you like to enter another number: ").upper()
# If yes, get a number and add it to the total
if cont == "Y" or cont == "YES":
num = float(input("Please enter number: \n"))
total += num
# If no, print the total and break out of the while loop
elif cont == "N" or cont == "NO":
print("The total of the numbers is", total)
break
# Otherwise, try again.
else:
print("Invalid response. Please enter Y or N")
I can get the print statements to display to terminal if I enter a number that is not equivalent to 15. I want to display a message when the input is not 15, but it won't. Only when I enter 15, I get only "Right Guess". Why does this not work?
x=15
y=10
while x != y:
y = int(input("Please Try to guess the random number: "))
if y < x:
print("Low guess")
elif y > x:
print("High Guess")
else :
print ("Right Guess!")
Your if, elif, and else is not in the while loop. This means it won't run until after the while loop is finished (when x == y)
You should also use descriptive variable names (not x and y)
I'm on my phone, so I can't test code, but I think working code would be:
number = 15
# why did you initialize your `y` to 10?
guess = 0
while guess != number:
guess = int(input("Guess a number:"))
if guess == number:
print("Yay! You guessed the number")
elif guess > number:
print("You guessed too high")
else:
print("You guessed too low")
You should indent your code properly.
Initialize your values, these have to be separated from the while loop, otherwise you will get an infinite loop.
x = 15
y = 10
Then you can run your script below with properly identation.
while x != y:
y = int(input("Please Try to guess the random number: "))
if y < x:
print("Low guess")
elif y > x:
print("High Guess")
else:
print ("Right Guess!")
Identation
Identation for python means tell us when a function start and when finish:
if x != y:
# start indent
print("I'm in if")
# finish indent
print("I'm out of if")
There, indent tell us when if starts and when finishes. So the first print will be affected by if and the other print not.
I think that you need to indent your if block so that it is contained within the while loop.
So I am very new to python as I spend most of my time using HTML and CSS. I am creating a small project to help me practice which is a number guessing game:
guess_number = (800)
guess = int(input('Please enter the correct number in order to win: '))
if guess != guess_number:
print('Incorrect number, you have 2 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print('Incorrect number, you have 1 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print()
print('Sorry you reached the maximum number of tries, please try again...')
else:
print('That is correct...')
elif guess == guess_number:
print('That is correct...')
So my code currently works, when run, but I would prefer it if it looped instead of me having to put multiple if and else statements which makes the coding big chunky. I know there are about a million other questions and examples that are similar but I need a solution that follows my coding below.
Thanks.
Have a counter that holds the number of additionally allowed answers:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no') + ' more attempts..')
If you don't know how many times you need to loop beforehand, use a while loop.
correct_guess = False
while not correct_guess:
# get user input, set correct_guess as appropriate
If you do know how many times (or have an upper bound), use a for loop.
n_guesses = 3
correct_guess = False
for guess_num in range(n_guesses):
# set correct_guess as appropriate
if correct_guess:
# terminate the loop
print("You win!")
break
else:
# if the for loop does not break, the else block will run
print("Out of guesses!")
You will get an error, TypeError: Can't convert 'int' object to str implicitly if you go with the answer you have selected. Add str() to convert the tries left to a string. See below:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + (str(tries_left) if tries_left > 0 else 'no') + ' more attempts..')