Why is the 'else' statement getting printed even if a correct choice is picked?
ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
print"Chocolate"
if ch=='3':
print"Strawberry"
if ch=='4':
print"Kiwi"
if ch=='5':
print"orange"
if ch=='6':
print"mango"
if ch=='7':
print"pineapple"
if ch=='8':
print"grapes"
print"You are done picking up a flavor, pay now"
if ans=='n':
print"Good, you can go!"
else:
print"wrong choice"
Output is printing "wrong choice" even if a valid choice is selected.
Because the if-statement checking "y" and the second if-statement checking "n" are two different. The else is only connected to the second if-statement with the "n"-check. You want to have the outermost statements like
if "y":
....
elif "n":
....
else:
....
It appears that you're conflating your series of ifs with a series of if-elifs.
Note that this:
if cond0:
...
if cond1:
...
else:
bar()
is not the same as:
if cond0:
...
elif cond1:
...
else:
bar()
If cond0 is True, then the former will call bar(), while the latter will not. In the former, it is just an if followed by a completely separate if-else.
It might help to write the former like this:
if cond0:
...
# Note spacing here, emphasizing that the above construct is separate from the one below.
if cond1:
...
else:
bar()
ans isn't 'n' so the else clause fires. You probably want an elif:
if ans == 'y':
...
elif ans == 'n':
...
else:
...
The else in this chunk of code is only referring to the if ans=='n'.
It's not taking into account your first if statement. You're going to want to change it to this
elif ans=='n':
print"Good, you can go!"
else:
print"wrong choice"
You have two conditions not one.
The first condition checks ans against 'y'.
If ans is 'y' the user gets to input an integer 1-8 and the appropriate string will be printed to the console. Processing then moves to the second condition (#2).
If ans is not 'y' then the user dose not give any input and processing moves to the second condition (#2).
The second condition checks ans against 'n'.
If ans is 'n' then "Good, you can go!" is printed to the console and processing continues skipping the else block.
If ans is not 'n' (which would be the case that user entered 'y') then the else block is executed printing "wrong choice" to the console.
What is happening is you have your logic setup that any input other than 'n' will print "wrong choice" eventually. You want a single decision from the users initial input. Currently your logic makes two.
Use the if elif else construct.
Related
while Guessp1 != Player1_secretword:
Guessp1 = input("player 1, guess your secret word: ")
nogp1 += 1
if Guessp1 != Player1_secretword:
hint1 = input("would you like a hint? (Y/N): ")
if hint1 in ["yes", "y", "Y"]:
hintcharecter = Player1_secretword[0]
print("hint: " + hintcharecter)
noghp1 += 1
else:
print("ok continue")
I want to clear the variable hint1 however when i try the "local variable "hint1" referenced outside the assesment" error, how do i fix this?.
I think we need to restructure some things here.
Add x = True statement before the loop. (Or whichever variable you prefer.)
Change the "while" condition to be "while x == True".
Move the "if" condition for hint1 to be a subset of the first if condition, instead of just following it. (In other words, the hint if condition should only appear if the user got the guess wrong in the first place.)
Add an else statement to the Guessp1 if condition. "else: x = False"
This should break the while loop only if the correct word has been guessed. There may be some additional issues to contend with, depending on the rest of your code, but I think this should get you started.
Good luck!
The question I have is about the flag I have here for the while loop. This works but not like I think it should. I assume I'm not understanding something so if someone is able to explain, that would be great.
From my understanding this should break out of the loop as soon as one of my conditionals is met. So if I input 'q' it should break out and stop the loop. But what happens is it keeps going through the loop and then it breaks out. so it goes through the last prompt and prints the exception.
(Python version is 3.8.5)
# Statement that tells the user what we need.
print("Enter two numbers and I will tell you the sum of the numbers.")
# Lets the user know they can press 'q' to exit the program.
print("Press 'q' at anytime to exit.")
keep_going = True
# Loop to make the program keep going until its told to stop.
while keep_going:
# Prompt for user to input first number and store it in a variable.
first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
keep_going = False
# Prompt for user to input second number and store it in a variable.
second_number = input("Second number: ")
# Create a break when entering the second number.
if second_number == 'q':
keep_going = False
# Exception for non integers being input "ValueError"
try:
# Convert input to integers and add them.
# storing the answer in a variable.
answer = int(first_number) + int(second_number)
except ValueError:
# Tell the user what they did wrong.
print("Please enter a number!")
else:
# Print the sum of the numbers
print(f"\nThe answer is: {answer}")
Using this code it breaks out right away like I expect it to.
while True:
first_number = input("First number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
I just would like to understand what the difference is and if thats how it should work. I feel like I'm missing something or misunderstanding something.
The condition of the while loop is only checked between iterations of the loop body, so if you change the condition in the middle of the loop, the current iteration will finish before the loop terminates. If you want to break a loop immediately, you need to either break (which automatically breaks the loop regardless of the condition) or continue (which jumps to the next iteration, and will therefore terminate the loop if the condition is no longer true).
Using while True: with a break when you want to stop the loop is generally much more straightforward than trying to control the loop by setting and unsetting a flag.
FWIW, rather than copying and pasting the code to input the two numbers, and have two different ways to break out of the loop, I might put that all into a function and break the loop with an Exception, like this:
print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")
def input_number(prompt: str) -> int:
"""Ask the user to input a number, re-prompting on invalid input.
Exception: raise EOFError if the user enters 'q'."""
while True:
try:
number = input(f"{prompt} number: ")
if number == 'q':
raise EOFError
return int(number)
except ValueError:
print("Please enter a number!")
while True:
try:
numbers = (input_number(n) for n in ("First", "Second"))
print(f"The answer is: {sum(numbers)}")
except EOFError:
break
This makes it easier to extend the program to handle more than two inputs; try adding a "Third" after where it says "First" and "Second"! :)
Once you run the program and type "q", Yes indeed keep_going will be set to False but it DOES NOT MEAN it will break the loop already, it will just make the keep_going be equal to False thus on the NEXT ITERATION will stop the loop. Why is that? because it would be like this while keep_going: -> while False: so since it is not True thus not executing the program anymore.
Now based on your goal as you mentioned. You can do it this way where you can add the break.
if first_number == 'q':
keep_going = False
break
# Prompt for user to input second number and store it in a variable.
second_number = input("Second number: ")
# Create a break when entering the second number.
if second_number == 'q':
keep_going = False
break
I'd also like to suggest have it this way, it's just more specific in terms of what is to happen on the code, but of course it is up to you.
first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
keep_going = False
break
# Prompt for user to input second number and store it in a variable.
# Create a break when entering the second number.
else:
second_number = input("Second number: ")
if second_number =='q':
keep_going = False
break
While loops execute until their given condition is false. A loop will only check its condition when required (program execution is moved to the top of the loop). In almost every case, this occurs when the full body of the loop has run. See here:
keep_going = True
while keep_going:
keep_going = False
# keep_going is False, but this will still print once
# because the loop has not checked its condition again.
print("Will execute once")
"Will execute once" prints a single time even after keep_going is set to False. This happens because the while loop does not re-check its condition until its entire body has run.
However, break statements are different. A break statement will cause a loop to exit immediately no matter what.
keep_going = True
while keep_going:
break # Exits the while loop immediately. The condition is not checked.
print("Will never print")
Here, nothing is printed even though keep_going is True the whole time. break made the loop exit regardless of the condition.
A continue statement will move program execution back to the start of the loop, and cause your condition to be checked again.
In this example, continue sends program execution back to the start of the loop. Since keep_going was set to False, nothing will print because the while loop will exit after realizing its condition evaluates to false.
keep_going = True
while keep_going:
keep_going = False
continue
print("Will never print")
First off, hope you have a great time learning Python!
Both ways will work and stop the loop, but there is a difference:
In the first method, you are changing the keep_going variable to false, therefore, the loop will stop when the the while loops finds out that keep_going had become False. However, the checking only happens at the end of the loop (In your case, it is after you have done your except or else part), the loop will not stop right away even when you entered q for your variable first_number.
In the second solution, you are using the break keyword in Python, to break away from the loop right away after you entered q for first_number.
Technically speaking, you will want to break if you want to break off from the loop right away when q is detected, otherwise, setting keep_going to False if you want the whole loop to be completed, but not run again for the next round.
In scenario 1 the result, even when you entered q,
Please enter a number!
Will always show, but not for scenario 2.
this is a little different approach to your script:
def main():
print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")
val = []
while True:
check_value = lambda x: 'quit' if x.lower() == 'q' or x.lower() == 'quit' else int(x)
if not val:
value = input("First number: ")
elif len(val) == 2:
answer = sum(val)
print(f"\nThe answer is: {answer}")
print('==='*15 + ' < ' + f'PROGRAM RESTARTING' + ' > ' + '==='*15)
val[:] = []
continue
else:
value = input("Second number: ")
try:
check_ = check_value(value)
val.append(check_)
except ValueError:
print("Please enter a number!")
continue
finally:
if check_ == 'quit':
print('Program is stopping....')
break
else:
pass
if __name__ == '__main__':
main()
It check at anytime the user's input, whether is a 'q' 'Q' or ('quit' or 'QUIT') or any combination or capital letter because run the check x.lower()
I suggest you to have a look at realpython.com especially the paragraph "he Python break and continue Statements."
Long story short:
Use Break to terminate the loop at any given time.
Use continue to roll back where you left and repeat the loop again (I used it in my code if the value is not a Int)
User pass to keep the loop running with no stop.
I've tried to make a program that randomizes meals and outputs a random dish. The only problem is, when it first asks you if you want a dish it returns a dish no matter what the response it. Any help appreciated.
print('Random Dinner Dish?')
response = input()
while True:
if response == 'Yes' or 'yes' or 'Y' or 'y':
print(dinner[random.randint(0,len(dinner) - 1)])
break
else:
print('Goodbye')
break
I'm expecting it to print Goodbye and stop the program if some form of yes isn't used.
The result of response == 'Yes' or 'yes' or 'Y' or 'y' is always truthy, so the else-block is unreachable.
You probably meant
if response in {'Yes', 'yes', 'Y', 'y'}:
or will return its left side if it is truthy, otherwise it returns its right.
So False or 'yes' returns 'yes'.
I am using break statement inside while loop to exit from while loop. But it gives wrong output. I don't know why this occurs. Here is the code I have used:
def func():
print "You have entered yes"
t='yes' or 'Y' or 'y' or 'Yes' or 'YES'
while True:
r=raw_input("Enter any number:")
if t=='r':
func()
else:
break
print "Program End"
Update:
When I put Yes it should give :
You have entered yes , but control goes to break statement. Why?
You should not use t = 'y' or 'Y' ... in your code because when you use or it checks the validity. Try this code and I am pretty sure it will work.
def func():
print "You have entered yes"
t=('yes', 'Y', 'y', 'Yes', 'YES')
while True:
r=raw_input("Enter any number:")
if r in t:
func()
else:
break
print "Program End"
Change
if t=='r':
to
if t==r:
Is that what you want?
First, you're checking if t is equal to the string literal 'r' and not the variable r, so in theory what you want is if t==r
However, this won't work. What you're looking for is a list, like the following:
def func():
print "You have entered yes"
t= ['yes','Y','y','Yes','YES']
while True:
r=raw_input("Enter any number:")
if r in t:
func()
else:
break
print "Program End"
When executing
t=='r'
you are comparing variable to a string r (this exact one character only), not to r variable.
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()