I am trying to figure out why any input starting with 'y' keeps this game going....looking at the code it appears only 'y' or 'yes' should keep it going but I could enter 'yensdg', 'yyyy' etc and it still loops.
Any ideas? Thanks
from random import randint
repeat = True
while repeat:
print('You rolled', randint(1,6))
print('Do you want to roll again?')
repeat = ('y' or 'yes') in input().lower()
'y' in input().lower(), this statement will return true if 'y' is present anywhere in the input string. Like if the input is 'thisisarandominputwithy' it will return true, because it has 'y' in the end
Change the last line to:
repeat = input().lower() in ['y', 'yes']
Related
I want to use a list of string values in an if statement and convert any input given by the user to lowercase- the only way I can do this now is by making a list that includes all lowercase and uppercase values and then use the "in" and "not in" operators in the if statement. Here's my code:
yes = [
"Y", "y", "yes", "YES"]
no = [
"N", "n", "no", "NO"]
start = input("Hello there! Press 'y' to start, or 'n' to stop. ")
if start in yes:
main()
elif start in no:
print("Hope you can play some other time!")
There are other longer lists in the same program and this makes it very inconvenient to type different variations of the same word. Is there any way I can convert all values to lower/upper case either in the list itself, or in the if statement?
You can use the builtin function lower:
start = input("Hello there! Press 'y' to start, or 'n' to stop. ").lower()
if start in ['y', 'yes']:
main()
elif start in ['n', 'no']:
print("Hope you can play some other time!")
And if you want without the list at all, you can check only the first letter:
start = input("Hello there! Press 'y' to start, or 'n' to stop. ").lower()
if start[0] == 'y':
main()
elif start[0] == 'n':
print("Hope you can play some other time!")
inp = input('Enter: ').upper()
print(inp)
This will print the input in uppercase. user lower() to convert in lowercase.
You might like to use strtobool. This will obviate the need to upper()|lower() and will convert truthy values into True|False for you.
from distutils.util import strtobool
start = input("Hello there! Press 'y' to start, or 'n' to stop. ")
if strtobool(start):
main()
else:
print("Hope you can play some other time!")
True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
I would do it like this:
start = input("Hello there! Press 'y' to start, or 'n' to stop. ").upper()[0]
if start == "Y":
print("put main program here")
else:
print("Hope you can play some other time!")
I have just started learning Python and I have some issues with the while loop.
instruction_yes_no = ""
while instruction_yes_no.lower() != "y" or "n":
instruction_yes_no = input("Do you want to see the instruction? Please write 'Y' or 'N'\n")
if instruction_yes_no.lower() == "y":
print("You are gonna lose even if you read the instructions...")
print("\n")
time.sleep(1)
instruction()
elif instruction_yes_no.lower() == "n":
print("Do you think you are better than me? I will beat you faster since you have not read the instructions")
time.sleep(1)
else:
print("You mortal...you have not chosen a valid input. Type or 'Y' or 'N'")
time.sleep(1)
break
Basically I would like to obtain the following:
1) If the user inputs 'y', the instruction() function is called (THIS WORKS)
2) If the user inputs 'n', it prints ""Do you think you are better than me?..." (THIS WORKS)
3) If the user does not type either 'y' or 'n', I would like to keep looping until the user insert or 'y' or 'n'.
HOWEVER this is not working.
I am not understanding why. This is how I think it should work:
At the beginning the variable instruction_yes_no is set to ""
It enter the loop because instruction_yes_no != than 'y' or 'n'
Now, instruction_yes_no assumes the value that the user inputs
If the user does not input either 'y' or 'n' it should keep looping, but is does not.
If the user does not input either 'y' or 'n' it should keep looping, but is does not
Because you have the break after the if-elif-else. So it will break in any case.
Move that break inside the if block (when instruction_yes_no.lower() == "y").
Oh, this is a classic common error:
while instruction_yes_no.lower() != "y" or "n":
It's the same as
while (instruction_yes_no.lower() != "y") or True:
You want this instead:
while instruction_yes_no.lower() != "y" and instruction_yes_no.lower() != "n":
Or maybe this, it's shorter :)
while instruction_yes_no.lower() not in ["y", "n"]:
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()
In Codeacademy, I ran this simple python program:
choice = raw_input('Enjoying the course? (y/n)')
while choice != 'y' or choice != 'Y' or choice != 'N' or choice != 'n': # Fill in the condition (before the colon)
choice = raw_input("Sorry, I didn't catch that. Enter again: ")
I entered y at the console but the loop never exited
So I did it in a different way
choice = raw_input('Enjoying the course? (y/n)')
while True: # Fill in the condition (before the colon)
if choice == 'y' or choice == 'Y' or choice == 'N' or choice == 'n':
break
choice = raw_input("Sorry, I didn't catch that. Enter again: ")
and this seems to work. No clue as to why
You have your logic inverted. Use and instead:
while choice != 'y' and choice != 'Y' and choice != 'N' and choice != 'n':
By using or, typing in Y means choice != 'y' is true, so the other or options no longer matter. or means one of the options must be true, and for any given value of choice, there is always at least one of your != tests that is going to be true.
You could save yourself some typing work by using choice.lower() and test only against y and n, and then use membership testing:
while choice.lower() not in {'n', 'y'}:
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 9 years ago.
Alright, so I've tried this for a while now and I can't seem to find a way to close the program once it is running.
What I want it to do is to end the program if the user chooses 'no':
elif y == 'n' or 'no':
sys.exit(0)
However whatever I choose returns the program to the partOne function. I've tried different things to try and solve this, such as moving
partOne()
from the end of the program to in between the two functions but that does not work because then the PartTwo function has yet to be defined.
Thanks for your response.
import hashlib
import sys
def partOne():
x = input("\nEnter something to hash: ")
hash_object = hashlib.sha256(x.encode())
hex_dig = hash_object.hexdigest()
print("\nPlain text: ")
print(x)
print("\nHashed text: ")
print(hex_dig)
print("\nYour password: ")
print(hex_dig[::9])
partTwo()
def partTwo():
y = input("\nDo you want to make another password? (y/n): ")
if y == 'y' or 'yes':
partOne()
elif y == 'n' or 'no':
sys.exit(0)
else:
print("\nYou need to type either 'y' or 'n'.")
partOne()
partOne()
Try y == 'n' or y =='no'
instead of y == 'n' or 'no'
>>> y = 'anything'
>>>
>>> bool(y == 'n' or 'no')
True
your statement always returns True. Instead of checking y == 'no' it just checks 'no', anything converted to bool in python is True if its not None, False, or 0.
In case of strings and other iterables it returns True if its not empty, e.g. '', [], {}, () will always return False.
Or as Foo Bar User says, if y.lower() in ('n', 'no') will also do. lower() will make sure that the matching is case insensitive.