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!")
Related
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 cannot figure out why this won't work, I have gone as far as to apply integer variables, I would prefer to keep it purely to strings. I'm new, what am I doing wrong?
x = int(2)
y = int(1)
while userinput != (1,2):
userinput = input("Do you wish to continue, to start from scratch?")
if input == 1:
print("y")
if input == 2:
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
I presume you want to check directly on the "y" and "n" characters, note that, among the other things, in your code you are checking the wrong input, you should check the variable userinput that you assign in the loop with the user input.
Here is a working example, note that i convert to lowercase in order to accept both "y\n" and "Y\N" with a single if statement.
userinput = ""
while (userinput !="y" and userinput !="n"):
userinput = input("Do you wish to continue, to start from scratch?").lower()
if userinput == "y":
print("y")
elif userinput == "n":
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
EDIT: if statement fixed as suggested by #Kumar
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 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']
while True:
game = input("Would you like to play: Guess the integer(i) or true/false(t). **Case Senestive** ")
if not name.isalpha():
print (name, "Enter the correct values")
continue
if not game == "i" or game == "t" or game=="integer" or game=="true/false":
print ("Enter i, integer or true/false, t")
continue
else:
break
I want to make it if they don't type 'i' or 'integer' it goes to the part saying not game == "i" or game=="integer". Whenever I enter i it works, but not when I enter integer.
You'll need to put parentheses around your or conditions:
if not (game == "i" or game == "t" or game=="integer" or game=="true/false"):
otherwise Python sees this as (not game == "i") or ....
You'd be better off using not in on a set:
if game not in {"i", "t", "integer", "true/false"}:
Not only is this shorter, it is also faster; only one check constant-time check is made rather than separate == tests for each string.