Getting out of a while loop using input - python

i am preparing a function to user to guess a random number generated by computer.
The output should be the number of guesses, and if the guess is correct, lower or higher than the generated number.
In the end the, the user should be asked if he wants to play again or not.
Everything is working excepts this last part, because i can't break the loop to stop the game.
Here's my code:
#random number guessing game
import random
def generate_random (min,max):
return random.randint (min,max)
#generate_random (1,100)
star_range=1
end_range=100
#targetnumber=generate_random(start_range,end_range)
#print (targetnumber)
def main():
targetnumber=generate_random(star_range,end_range)
number_of_guesses =0 #guarda o numero de tentativas do jogador
print ("Guess a number between 0 e 100.\n")
while True:
number_of_guesses +=1
guess = int(input("Guess #" + str(number_of_guesses) + ": "))
if guess > targetnumber:
print("\t Too High, try again.")
elif guess < targetnumber:
print ("\t Too low, try aain")
else:
print ("\t Correct")
print ("\t Congratulations. you got it in",number_of_guesses,"guesses.")
break
playagain=input("\n whould you like to play again? (y/n): ").lower()
while playagain != "y" or playagain != "n":
print ("Please print y to continue or n to exit")
playagain=input("\n whould you like to play again? (y/n): ").lower()
if playagain == "y":
continue
else:
break
My final output is always this one:
whould you like to play again? (y/n): n
Please print y to continue or n to exit
whould you like to play again? (y/n):
Can you please help me, letting me know what i am doing wrong?
Thank you very much

The condition evaluation is always True, hence you get into the loop again.
while playagain not in ['y', 'n']:
...
would satisfy your input check
Also, your continue/break condition is only evaluated if the while loop condition is met (i.e., the input was not correct)

It looks like you are continuing the second "while" loop and not moving back to your "game" code when you check the equality of the string "y" as the input, thus the question gets asked again. Instead, you should try refactoring the loops so that your game loop is nested inside the retry loop.

Related

Creating a loop of if statments

if explication == "y":
print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
" objective is to guess it, if you type a number lower than the generated number i'll tell you" +
" and the same will happen if you type a bigger number and there's a score if you guess wrong" +
" it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
if explication == "n":
print("Great then we'll go straight to having fun!")
if explication != "n" and explication != "y":
explication = input("please choose y or n: ")
So i started learning python and i wanted to do a simple fun program, and here i wanted to ask the user if he needed explication of the game that was simple to do, but i also wanted to make him choose another time if he miss clicked or he just wanted to type other things so i made the 3rd if statement, i also wanted it to repeat so if he keeps typing things other than y and n the program will always send "please choose y or n" until he he types either y or n is there a way to do this?
explication = None
# keep asking until we get "y" or "n"
while explication not in ["y", "n"]:
# retrieve input
explication = input("please choose y or n: ")
# check whether it's y or n
if explication == "y":
print("The game is very simple...")
elif explication == "n":
print("Great then we'll go straight to having fun!")
# if the input is neither y nor n, the program ends up here
# and loops again
Alternative:
# keep looping unconditionally
while True:
# retrieve input
explication = input("please choose y or n: ")
if explication == "y":
# print and break
print("The game is very simple...")
break # <- this gets us out of the while loop
elif explication == "n":
print("Great then we'll go straight to having fun!")
break
Here is a simple way to write the code
explication = None
while(explication != "n" and explication != "y"):
explication = input("please choose y or n: ")
if explication == "y":
print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
" objective is to guess it, if you type a number lower than the generated number i'll tell you" +
" and the same will happen if you type a bigger number and there's a score if you guess wrong" +
" it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
break
if explication == "n":
print("Great then we'll go straight to having fun!")
break
#Code to start the game after this comment
Explanation
We set explication to None as the explication variable has to be initialized first.
The while loop runs while the input is not y or n. If it is y, we explain the game and then leave the loop using break. If it is n, we skip the explication and break from the loop. After you break from the loop you can put the code for the game!

Guess the number game Python (while loop)

I am trying to create a game that will ask the user to make a guess and if the guess is lower than the randomly generated integer, then it'll print ('Too low! Try again.), if the guess higher than the guess then it will print ('Too high! Try again) and if guess is equal to the random integer then it will ask the user if she wants to play again. This is where I am having trouble with - how can I have the code loop it back to recreate the random integer and start the loop if 'y' is entered?
import random
def main():
again='y'
count=0
while again=='y':
print('I have a number between 1 to 1000.')
print('Can you guess my number?')
print('Please type your first guess')
number=random.randint(1, 1000)
print(number)
guess=int(input(''))
while guess !='':
if guess>number:
print('Too high, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess<number:
print('Too low, try again!')
count+=1
print('count:',count)
guess=int(input(''))
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
else:
print('You entered an invalid value')
main()
You can do this by just adding one line with your code, use break in the inner while loop, in this portion below, it will break the inner loop if user guessed the number accurately with getting new input of again, then if again = 'y' it will start the outer loop again and random will generate again, otherwise the game will end.
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break # added this `break`, it will break the inner loop
Since you are in two loops you have to break the deepest one. Here are two ways for your situation.
Eather update "guess" to: '':
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
guess=''
Or add a break after the again input:
elif guess==number:
print('Excellent!! You guessed the number!!!!')
print('Would you like to try again? (y or n)')
count+=1
print('count:',count)
again=str(input(''))
break

Command "Break" doesnt work for some reason

number=input("enter a whole number")
if number.isdigit():
print("Good one")
else:
print ("haha, really clever")
answer=str(input("Wanna try again? y/n"))
if answer == 'n':
print("Ok loser")
break
elif answer== 'y':
print("ok...good luck")
continue
I tried to make a code that would react if the input is integer or float, and if its float it would restart if the person wants it to; but the command 'break' doesnt want to work for some reason please help... (make it simple please)
You just need to wrap your code with a while loop.
while True:
number=input("enter a whole number")
if number.isdigit():
print("Good one")
else:
print ("haha, really clever")
answer=str(input("Wanna try again? y/n"))
if answer == 'n':
print("Ok loser")
break
elif answer== 'y':
print("ok...good luck")
continue
To use a break, you need it to be in a loop (while, for, ...). A break stop the execution of the loop if it's condition is met. In your casse you only have ifs, so you don't need a break as it will not check the other conditions if the first one is met.
You need to use a while loop.
answer = 'y'
while answer == 'y':
number = input("Please enter a whole number: ")
if number % 1 == 0:
print("Good one!")
else:
print("Haha, really clever.")
answer = input("Wanna try again? (y/n) ")
Set the answer to y so the loop runs at least once.
If the user wants to try again they enter y and the condition will be true meaning the loop wil run again.
Hope this helped!

Im unable to stop the input from taking place & play again loop middle of script

I am making a custom version of hangman for a college assignment using python, but currently I'm having an issue with two parts to my code, its a game of hangman.
I have included the entire code below so that if anyone can answer they have the full information from the code.
The issues I'm having are that this part of the code is not ignoring the input before so it still lets you guess multiple letters.
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
The second issue I have is that once you win the game it doesn't ask if you want to play again properly (I have tried multiple methods to try to fix this including another while loop inside the if statement.
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
print
...
while True:
...
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
# Current Bug: Play again here, cannot use same line as end.
print
guess = input("guess a letter: ").lower()
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
guesses += guess
...
play_again = input("If you'd like to play again, please type 'yes' or 'y': ").lower()
if play_again == "yes" or play_again == "y":
continue
else:
play_again != "yes" or play_again != "y"
break
This should solve your problem of taking multiple letters as input
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
else:
guesses += guess
This will only add the input to guesses if its length is less than 1.
And if you want to ask the game to play again, after winning put your code in a while loop. Something like this:
play_again = 'y'
while(play_again == 'y' or play_again='yes'):
win = False
while(!win):
<your code for game, set win = True after winning>
play_again = input("Want to play again y or n: ").lower()
Edit: You can add failed along with win in the while loop as well.

How can I make my program return to the beginning in Python?

I'm a really new programmer, just programing for fun. I usually write my programs with a series of while loops to get to different sections of the program at different times. It's probably not the best way, but it's all I know how to do.
For example, I'm working on a little program that runs in a shell meant to solve an equation. Here's part of the program that's supposed to bring you back to the beginning.
while loop==4:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == "Y":
#Get values again
loop=2
elif goagain == "N":
print "Bye!"
#End program
loop=0
else:
print"Sorry, that wasn't Y or N. Try again."
I have it set so that while loop==2, it gets the values to put into the equation and while loop==0, nothing happens.
The problem I have, though, is that when my loop changes back to 2, the program just ends there. It doesn't want to back in the code to where I told it what to do while loop==2.
So what I need to know is how to get my program to go back to that section. Should I use a different method than the while loops? Or is there a way to get my program to go back to that section?
Thanks!
A better approach would be to do sometihng like this:
while True:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == "Y":
#Get values again
pass #or do whatever
elif goagain == "N":
print "Bye!"
#End program
break
else:
print"Sorry, that wasn't Y or N. Try again."
You will only iterate when loop is equal to 4. So for the example you have given loop=2 and loop=0 will have the same affect.
First of all, the loop condition states:-
while loop == 4:
This means the loop will be executed as long as the value of the variable 'loop' remains 4. But since you assign 2 to loop, the condition is not satisfied, and control goes out of the loop. One solution would be to change condition as:-
while loop == 2:
Or, another solution would be to remove the statement assigning 2 to loop altogether.
But, since you are getting the value Y/N in goagain, a better way would be:-
done = False
while not done:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == 'Y':
#Get values
elif goagain == "N":
print "Bye!"
#End program
done = True
else:
print"Sorry, that wasn't Y or N. Try again."
Why are you changing Loop to 2, when the user enters Y? If the user inputs yes, collect the values then execute your equation solver, then loop back.
while loop==4:
goagain = raw_input("Would you like to do the equation again? (Y/N)")
if goagain == "Y":
#Get values again
#Solve your equation here
elif goagain == "N":
print "Bye!"
#End program
loop=0
else:
print"Sorry, that wasn't Y or N. Try again."
You can do it as.. this program will check for a number is it prime and find factorial...
while input('Enter yes to start no to exit...: ') == 'yes':
print('Enter your choice [1] to find prime no. and [2] to calc. factorial.')
choice = int(input('Enter your choice: '))
num = int(input('Enter number: '))
def prime(number):
if number == (1 or 2 or 3 or 5 or 7):
print('%d is a prime number..:)' %number)
else:
for x in range(2,number):
if number%x == 0:
print('%d is not a prime number..' %number)
break
else:
print('%d is a prime number..' %number)
break
def fact(number):
fact = 1
for x in range(1,number+1):
fact = fact*x
print('Factorial of %d is %d' %(number,fact))
switch = { 1:prime , 2:fact}
try:
result = switch[choice]
result(num)
except KeyError:
print("I didn't get that...")
print('Bye...:)')

Categories

Resources