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.
Related
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.
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()
This is kind of an extension to my last question, but I was wondering if it is possible to make the script go back to a specific line, if an event happens.
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
else:
print "not working"
On the last line, if 'else' happens, can you make it so it restarts from line 2 again?
Any help will be very greatly appreciated, thanks a lot!
You could put your code in an endless loop that only exits if the right word is typed in:
print "Type in 'Hello'"
while True:
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
break
else:
print "not working"
You can let the program lie in a loop till the correct input is given
while True:
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
break
there is 2 ways to do it , one with while loop , and one with recursion
the two answer before mine solved your problem with while loop , so i'd solve yours with recursion
def Inp():
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
else:
print "not working"
Inp()
Inp()
at the end just call the function Inp and it will continue asking for entering the value you want
I am starting to learn python. I have gone through several tutorials and now I am trying to write my first script. It is a simple console menu. I am running Python 2.6.5 under cygwin.
Here is my script:
import sys
print "********************************************************************"
print "** 1) This is menu choice #1 **"
print "** **"
print "** **"
print "** **"
print "** **"
print "** **"
print "********************************************************************"
print
print "Choice ?"
choice = sys.stdin.readline()
print "You entered: " + choice
if choice == 1:
choice1 = sys.stdin.readline()
print "You entered:" + choice1
else:
quit()
print "Exiting"
When I run the script, I get to the Choice? prompt. I enter 1 and I get the "You entered:" message and then the script exits without displaying the "Exiting" message.
Seems like it should be so easy. Thanks in advance for any help.
You're comparing a string to an integer. Try converting the string into an integer:
if int(choice.strip()) == 1:
Use raw_input() instead of sys.stdin.readline()
Change choice == 1 to choice == '1'
The problem is that readline returns a string, but your if statement expects an int. To convert the string to an int, you could use int(choice.strip()) (be prepared for it to raise an exception if what you enter isn't a valid number).
In [8]: choice
Out[8]: '1\n'
In [9]: int(choice.strip())
Out[9]: 1
Not sure, but I think the user is entering a string, not a number. The number 1 and the string 1 are two completely different things.
Try choice == "1"
The readline function retains the newline at the end of the input. Your first if should be:
if choice == "1\n":
assuming you want the newline.
It's exiting by calling quit() since it takes the else branch. That's because '1' (a string) does not equal 1, an integer.
I want to assign something a value and then try and get someone to guess that value. I have tried something along the lines of this but I can't seem to get it to work...:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You guessed it!')
if foo != guessfoo:
print('haha, fail.')
Why doesn't this work? And how should I be doing it? I am a beginner at this, please help!
With python version 3 :
input() returns a 'str' (string) object. A string compares to an integer returns False :
1 == '1'
False
You must cast your input like that :
guessfoo = int(input('Guess my number: '))
Don't forget to try...except if the result of the input cannot be casted into an int.
Full example code :
try:
foo = 1
guessfoo = int(input('Guess my number: '))
if foo == guessfoo:
print('Well done, You guessed it!')
else:
print('haha, fail.')
except ValueError:
# cannot cast your input
pass
EDIT:
With python version 2 :
Thanks for this comment :
In previous versions, input would eval the string, so if the user typed in 1, input returned an int.
Ouput or your original code:
$ python2 test.py
Guess my number: 1
Well done, You guessed it!
Currently you have no condition to stop the loop. You're just printing stuff. Put a break after you guessed the number, or set loop to a different value than 1.
Because integers (foo) aren't strings (result of input()).
If you think that Python behaves like PHP or Perl then you are wrong
1 is something completely different than '1'.
You have to either convert the string using int(..) to an int or check against 'foo'
as a string.
It looks like the first problem will be an infinite loop, since the condition you're checking each iteration will always be true with the above code. When you loop, you need to make sure you change something that will bring loop closer to that condition. As a start, your code should look like this:
loop = 1
while loop == 1:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You guessed it!')
loop = 0
if foo != guessfoo:
print('Oh no, try again')
This will cause the loop to finish executing if the number is actually guessed.
The next problem is that input returns a String, so the check to see if the entered number is equal to the expected number will always fail. In python, use the int() function to convert a string to a number, so that line looks like:
guessfoo = int(input('Guess my number: '))
At this point, you should have a decently-working loop. However, there are a few things you could do to make your code simpler. Here are some suggestions, starting with the simplest tweaks and moving to cleaner code.
The first step could be to use if...else to make sure only one condition is executed, and you only have to check the value of foo once. If the condition is true, the first branch is executed; if it fails, execution proceeds to the else block.
loop = 1
while loop == 1:
foo = 1
guessfoo = int(input('Guess my number: '))
if foo == guessfoo:
print('Well done, You guessed it!')
loop = 0
else:
print('Oh no, try again')
This works, but we can also move the check for a correct result in the condition of the loop. This way, the program only loops until the number is displayed:
foo = 1
guessfoo = 0
while foo != guessfoo:
guessfoo = int( input( 'Guess my number: ' )
if guessfoo != foo:
print( 'Oh no, try again' )
print( 'Well done, You guessed it!' )
Now the success message will only be displayed when foo == guessfoo. This loop is a bit clearer and simpler.
As a beginner, you've chosen a great place to ask for help! Welcome to StackOverflow!
Also, should you be using two different if's?
shouldn't it be something more like
if foo == guessfoo:
print('Well done, you guessed it!')
else:
print('haha, fail.')
import random
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
foo = random.randint(1,10)
while True:
guess = int(inp('Guess my number: '))
if guess < foo:
print('Too low!')
elif guess > foo:
print('Too high!')
else:
print('You got it!')
break