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.
Related
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")
New to this so please bear with me. I'm trying to run a loop that asks the user to input a number between 1 and 100. I want to make it to where if they enter a number outside of 100 it asks again. I was able to do so but I can't figure out if I'm using the correct loop. Also whenever I do get inbetween 1 and 100 the loop continues.
code below:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
else:
while user_input > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
I think the clearest way to do this is to start with a loop that you break out of when you finally get the right answer. Be sure to handle a bad input like "fubar" that isn't an integer
while True:
try:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
break
print("Not between 1 and 100, try again")
except ValueError:
print("Not a number, try again")
In python 3 you can use range to do bounds checking. If you do
if user_input in range(1, 101)
range will calculate the result without actually generating all of the numbers.
When your code is run, it will continue to ask for an input, even if the input given is less than 100. One way to fix this would be to do this:
try_again = 1000
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
elif user_input > 100:
while try_again > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
This code first tests if the user's input is more than 100, then runs a while statement in which the base value is more than 100. When the user inputs another value, if it is over 100, it continues, otherwise it does not.
Below is an example of a program that gets you the output that you are seeking:
attempts = 0
while True:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input > 100 or user_input < 1:
print('Please try again')
attempts += 1
continue
elif attempts >= 1 and user_input <= 100 and user_input >= 1:
print('There you go!')
break
else:
print('Nice!')
break
Start by putting your prompt for the user within the loop so that the user can be asked the same prompt if the fail to enter a number between 1 and 100 the first time. If the user input is greater than 100 or less than 1, we will tell the user to try again, we will add 1 to attempts and we will add a continue statement which starts the code again at the top of the while loop. Next we add an elif statement. If they've already attempted the prompt and failed (attempts >= 1) and if the new input is less than or equal to 100 AND the user input is also greater than or equal to 1, then the user will get the 'There you go' message that you assigned to them. Then we will break out of the loop with a break statement in order to avoid an infinite loop. Lastly we add an else statement. If the user satisfies the prior conditions on the first attempt, we will print 'Nice' and simply break out of the loop.
I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.
So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:
x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
What would you do?
There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:
import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
continue jumps to the next iteration of the loop, and break terminates the loop altogether.
(Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)
Python does not support goto or anything equivalent.
You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the control flow page for more information.
x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
In many other cases, you'll want to use a function to handle the logic you want to use a goto statement for.
You can use infinite loop, and also explicit break if necessary.
x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break
I'm currently in the process of creating a game where it loops over and over again until you guess the right number.
The problem I'm having is getting the looping command right. I want to go for a while loop but I can get it to work, for certain parts of the script. If I use a "while true" loop, the if statement's print command is repeated over and over again but if I use any symbols (<, >, <=, >= etc.) I can't seem to get it to work on the elif statements. The code can be found below:
#GAME NUMBER 1: GUESS THE NUMBER
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
attempt = 1
while
if num == x:
print("Good job! it took you ",attempt," tries!")
num + 1
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
attempt = attempt + 1
else:
print("ERROR MESSAGE!")
Any and all help is appreciated.
You can use a boolean in the while :
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
attempt = 1
not_found = True
while not_found:
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
not_found = False
elif num > x: #Don't need the equals
print("Too high!")
elif num < x: #Don't need the equals
print("Too low!")
else:
print("ERROR MESSAGE!")
attempt = attempt + 1
You should put your question in the loop, because you want to repeat asking after each failure to get it right. Then also break the loop when user found it:
attempt = 0
while True:
attempt = attempt + 1
num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
if num == x:
print("Good job! it took you ",attempt," tries!")
break
elif num >= x:
print("Too high!")
attempt = attempt + 1
elif num <= x:
print("Too low!")
else:
print("ERROR MESSAGE!")
Your while needs a colon, and a condition
while True:
and if you use a while True: you have to end the loop, you can use a variable for this.
while foo:
#Your Code
if num == x:
foo = False
Also, you could use string format instead of breaking your string. For example,
print("Good job! it took you %s tries!" % attempt)
or
print("Good job! it took you {0} tries!".format(attempt))
def guess(n):
import random
x = random.randint(1,1000000)
while n != x:
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
if n == x :
print("Congrats")
again = print(input(str("Play Again Y/N?: ")))
if again == Y:
n = print(input(str("Input Number 'n': ")))
print(guess(n))
elif again == N:
print("Goodbye")
How do i make the while loops stop looping if the condition is matched and move onto the next condition that i have stated. Thank you!
Use the break statement (it terminates the nearest enclosing loop), e.g.
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
break
You can exit a loop early using break. I am not sure what you mean by "the next condition", but after a normal "break" excution will just start immediately after the loop. Python also has a nice construct where you can put an "else" clause after the loop which run only if the Loop exits normally.
You need to call a new input to change n. In your while statement, n is never redefined.
Try:
def guess(n):
import random
x = random.randint(1,1000000)
while n != x:
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
n = print(input(str("Input Number 'n': ")))
and if you want to stop the loop... Use break
if my_condition:
break
will stop your loop. It also works with for loops.
But asking for a new value of n will result, when x ==n, to end your while statement.
I'd write something like this:
import random
def guess():
x = random.randint(1,1000000)
n = x + 1 # make sure we get into the loop
while n != x:
n = input(str("Input Number 'n': "))
if n < x:
print("Too Low, Try Again")
elif n > x:
print("Too High, Try Again")
else:
print("Congrats")
break
if __name__ == '__main__':
while True:
guess()
again = input(str("Play Again Y/N?: ") == 'N'
if not again:
break
As previously stated,your indentation is incorrect for the statement "while..." and also for the "if x==n" .Move it to two tabs to the right,as you want to run the loop till the player wants to play the game.In your given code, the loop is running where there is no increment in x .Now regarding the break condition you can try something like this.
else:
print("Goodbye")
break