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!
Related
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.
This question already has answers here:
Priority of the logical operators (order of operations) for NOT, AND, OR in Python
(8 answers)
Closed 4 months ago.
The code is supposed to return false if the user's input is not "Y" or "N". When the user types "Y", it ends the loop, but when the type "N" it still continues the loop. How can this be corrected?
# Ask if they want to continue
while True:
noOrYes = input(f"Do you want to continue? (Y/N)")
if not noOrYes == "Y" or noOrYes == "N":
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#firstName & lastName was successfully parsed!
#we're ready to exit the loop.
print(f"break")
break
Much like mathematical operations and PEMDAS, boolean operators (and, or, ==) have an "order of operations." Right now you are asking two questions:
Is noOrYes not equal to Y?
Is noOrYes equal to N?
Fix the order of operations by using parentheses.
if not (noOrYes == "Y" or noOrYes == "N")
you can do this instead:
while True:
noOrYes = input(f"Do you want to continue? (Y/N)")
if noOrYes == "Y":
break
else :
print("Sorry, I didn't understand that.")
Instead of asking "if not"s. The following code takes care of every input that's not some variation of "yes" or "no"(Ex. "yeah", "nope", etc.).
# Ask if they want to continue
while True:
noOrYes = input(f"Do you want to continue? (Y/N)")
if noOrYes.lower().startswith('y'):
#User gave a proper response
#we're ready to exit the loop.
break
elif noOrYes.lower().startswith('n'):
#User gave a proper response,
#we're ready to exit the loop.
break
else:
print("Sorry, I didn't understand that.")
#Better try again... returning to the start of the loop
continue
Started learning python a few days ago and was doing a task with simple yes/no inputs and doing different things with the while loop depending no whether the user wants to continue using the program or not.
The whole program is fairly small so hope it's alright to post the entirety of its code here. This is what worked for me:
import random
print("=====================================")
print("I Add Numbers and Tell You the Sum v2")
print("=====================================")
while True:
rand1 = random.randint(1, 100)
rand2 = random.randint(1, 100)
result = rand1 + rand2
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
print()
again_input = input("Would you like to try again? (Y/N) ")
again = again_input.lower().strip()
validyes = ["yes", "y"]
validno = ["no", "n"]
if again in validyes:
print("Sure thing!")
print()
elif again in validno:
print("Okay. See you!")
break
else:
print("That's not a valid response. The program will now exit.")
break
While the relevant code that didn't work as expected was this, to do with checking the user input against the valid list:
valid = ["yes", "y", "no", "n"]
if valid == "yes" or "y":
print("Sure thing")
elif valid == "no" or "n":
print("Okay bye")
break
else:
print("That's not a valid response. The program will now exit")
break
The former would run just fine, while the latter will print "Sure thing" regardless of what the user inputs. Why is that the case?
On that front, I'm happy to hear any other tips you guys might have with regards to making the rest of the code better. Eager to hear from and take part in this community!
You have to show what all the string what they are comparing to
if again == "yes" or again == "y":
print("Sure thing")
elif again == "no" or again == "n":
print("Okay bye")
break
else:
print("That's not a valid response. The program will now exit")
break
Also a tip is to use "\n" for a new line. The \n will not be shown
Old:
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
print()
New:
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}\n")
Last is that for the lower and strip function u can use it in the same line were u get your input
Old:
again_input = input("Would you like to try again? (Y/N) ")
again = again_input.lower().strip()
New:
again = input("Would you like to try again? (Y/N) ").lower().strip()
In the second case you're using the OR operand wrong and that's why it is always printing Sure thing. Here you can take a look and understand it better.
To make the code better, i would suggest keeping the valid list with all valid inputs, and checking for yes or no using the if again in valid method, but playing with what is and isn't valid inputs.
This is how or works
operation: x or y result: if x is false, then y, else x
Explanation:
valid == "yes" will be false for obvious reason because you are comparing a list to a string. When the first condition is false operator or goes to evaluate next condition which is just "y" and will always be true(you can confirm it using bool("y")) so that's why it's always printing "Sure thing".
You use this:
if valid == "yes" or "y":
print("Sure thing")
elif valid == "no" or "n":
print("Okay bye")
break
So in the first condition you check if (valid == "yes") or ("y"), but not if valid == ("yes" or "y"). Non-empty string is always True, when you use it as bool, so the first condition is always True. If you want to do somwthing like this, you can use tuples (it's like lists, but you cant edit it): if valid in ("yes", "y")
valid is a list, so valid will never equal to "yes", so it just goes to "y", which will always equal true. You need to check if "yes" or "y" is in valid:
if "yes" in valid or "y" in valid:
print("Sure thing")
elif "no" in valid or "n" in valid:
print("Okay bye")
break
Of course, with this code it will always print "Sure thing" because valid includes all the options.
I am new to programming and so i'm practicing a bid. At this point i'm practicing with functions. In the code below break and continue are outside the loop i can not see why. I've tryed out different ways but the only thing i get to work is the last block of code. Why are break and continue outside the loop here?
import random
again = 'y'
while again == "y" :
def main():
print "gues a number between 0 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print 'Your the man'
found = True
else:
print 'to bad dude try again'
main()
again = raw_input('would you like to play again press y to play again press n yo exit')
if again == 'n':
break #here it says it is outside the loop
elif again != 'y':
print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
continue #this is outside loop as well
#main()
Because you are new to programming, I will get a few basic tips in my answer too.
INFINITE LOOP
You are trying to start an infinite loop by first settingagain = 'y' and afterwards you are using this variable to evaluate a while loop. Because you are not changing the value of y, it is better to not use a variable to create this infinite loop. Instead, try this:
while True:
(some code)
DEFINE FUNCTION IN LOOP
You're defining the function main() inside of the while loop. As far as I can tell, there is no use for that. Just leave out the first while loop. If you define a function, it is permanent (much like a variable), so no need to redefine it everytime. Using your code, you won't even get to call the function, because you never end the first loop.
CONTINUE/BREAK NOT IN LOOP
The error is quite self-explanaitory, but here we go. If you would ever end the first loop (which in this case, you won't), the next thing you do is call your function main(). This will generate a number and make the user guess it until he got it right. When that happens, you get out of that function (and loop).
Next, you ask if the user would like to play again. This is just an input statement. You store the answer in the variable 'again'. You check, with an if statement (note that this is not a loop!) what the answer is. You want the user to play again if he typed 'y', so instead of using again != 'y', you could use the following:
if again == 'y':
main() # you call the function to play again
If 'n' was typed in, you want to exit the script, which you do not by typing break, because you are not in a loop, just in an if-statement. You can either type nothing, which will just go out of the if-statement. Because there is nothing after the if, you will exit the script. You could also useexit(), which will immediately exit the script.
Lastly, you want to repeat the question if neither of these two things were answered. You can put the if-statement inside of a loop. You can (if you want) use your break and continue when doing this, but you mostly want to avoid those two. Here is an example:
while True:
again = raw_imput('y for again or n to stop')
if again == 'y':
main()
exit() # use this if you don't want to ask to play again after the 2nd game
elif again == 'n':
print('bye!')
exit()
# no need for an 'else' this way
# every exit() can be replaced by a 'break' if you really want to
BASIC BREAK/CONTINUE USAGE
Finally, here is some basic usage of break and continue. People generally tend to avoid them, but it's nice to know what they do.
Using break will exit the most inner loop you are currently in, but you can only use it inside of a loop, obviously (for-loops or while-loops).
Using continue will immediately restart the most inner loop you are currently in, regardless of what code comes next. Also, only usable inside of a loop.
EVERYTHING TOGETHER
import random
again = 'y'
def main():
print ("gues a number between 0 - 10.")
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print ('Your the man')
found = True
else:
print ('to bad dude try again')
main()
while True:
again = input('would you like to play again press y to play again press n yo exit')
if again == 'n':
print ('bye!')
exit() # you could use break here too
elif again == 'y':
main()
exit() # you can remove this if you want to keep asking after every game
else:
print ('oeps i don\'t know what you mean plz enter y to play again or n to exit')
I hope I helped you!
You loops and def are all muddled, you want something more like:
import random
again = 'y'
while again == "y" :
print "gues a number between 0 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print 'Your the man'
found = True
else:
print 'to bad dude try again'
while True:
again = raw_input('would you like to play again press y to play again press n to exit')
if again == 'n':
break
elif again != 'y':
print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
break
You may want to refer to instructional material because you seem to misunderstand the general purpose of functions and the order of your logic.
Your function should be at the outer scope, e.g.:
def main():
again = 'y'
while again == "y" :
Your question for again needs to be indented into the while loop:
while again == "y":
[snip]
again = raw_input('would you like to play again press y to play again press n to exit')
if again == 'n':
break #here it says it is outside the loop
elif again != 'y':
print 'oops i don\'t know what you mean plz enter y to play again or n to exit'
else:
continue #this is outside loop as well
The else: continue is unnecessary because you are at the end of the loop.
However, this only asks the question once, and you probably want this in a while loop. You also don't need to check the again == "y" in the outer while loop, because you are controlling the flow here:
while True:
[snip]
again = raw_input("would you like to play again press y to play again press n to exit")
while again not in ('y', 'n'):
again = raw_input("oops i don't know what you mean plz enter y to play again or n to exit")
if again == 'n':
break
I would recommend against using a bare input() because any code could be executed, receiving a string and casting to an int would be safe (and you probably do some error checking):
usergues = int(raw_input("your guess?"))
Putting it all together it looks like:
def main():
while True:
print "guess a number between 1 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = int(raw_input("your guess?"))
if usergues == nummer:
print 'You're the man'
found = True
else:
print 'Too bad dude try again'
again = raw_input('would you like to play again press y to play again press n to exit')
while again not in ('y', 'n'):
again = raw_input('oops i don\'t know what you mean plz enter y to play again or n to exit')
if again == 'n':
break
main()
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...:)')