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.
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
Background:
I'm experimenting with while loops and I just made a simple program nested in a while loop.
Code:
while True:
userinput = input("Is nem jeff? ")
if userinput == "y" or "yes" or "Y" or "Yes":
print ("YAY!")
elif userinput == "n" or "no" or "N" or "No":
print ("das sad :(")
else:
print ("wrong input")
break
Problem:
My program should be looping until the user types in an invalid input, but instead, it always returns the value nested in the if statement, no matter what I type in. What am I doing wrong?
Your conditionals aren't doing what you think they are.
In Python, a non-zero-length string evaluates to True in a boolean
context. The or operator performs a boolean or operation between
the lefthand operand and the righthand operand.
So when you write this:
if userinput == "y" or "yes" or "Y" or "Yes":
What you are saying is this:
if (userinput == "y") or True or True or True:
Which will always evaluate to True. You want to write instead:
if userinput == "y" or userinput == "yes" or userinput == "Y" or userinput == "Yes":
Or more simply:
if userinput.lower() in ['y', 'yes']:
The reason false down to truthsy or falsy in if conditions.
based on your initial code block
print('y'=='yes'or'y')
[output] y
print('n'=='yes'or'y')
[output] y
based on the above you can see that regardless of you input, your first if statement would be evaluated as True.
rather than doing that, try doing this instead.
while True:
userinput = input("Is nem jeff? ").lower()
if userinput in ['yes','y']:
print ("YAY!")
elif userinput in ['no','n']:
print ("das sad :(")
else:
print ("wrong input")
break
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 2 years ago.
I got to write a script which replaces certain things in a .txt file with a specific variables from input() and then it should create a new .txt with exact same content except the things replaced.
I have a few conditions:
Which compares line content from original .txt with a specific strings and if it's equal, it then replaces the string with replaced one and writes this new string to a new .txt file.
Basically, I must copy\paste original file with a few touches. But when it comes to the test stage, the whole config would be rewritten with only first condition stated in the build_config() function. And If you run my script, you would see that the LACP condition is not working at all, it writes the content in whichever way, when it should only write it if the LACP variable equals to "y".
What's going on? Here is my code:
def build_config():
base_config = open("MES2428B.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
line.replace("location", "location"+location)
complete_config.close()
base_config.close()
if lacp == "y" or "Y" or "Н" or "н" :
base_config = open("MES2428B_lacp.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
base_config.close()
complete_config.close()
print("LOCATION:")
location = input()
print("VLAN:")
vlan = input()
print("Adress:")
ip = input()
print("LACP NEEDED? y/n")
lacp = input()
print("COM SPEED:")
COMspeed = input()
print("LOCATION: " + location + "\nVLAN: " + vlan + "\nIP: " + ip)
print("IS EVERYTHING RIGHT? y/n")
while True:
check = input()
if check == "y" or "Y" or "Н" or "н":
build_config()
print("Done, check it!")
input()
break
elif check == "n" or "N" or "т" or "Т":
print("What would you like to change? /n 1 - Локация /n 2 - VLAN /n 3 - IP /n 4 - COM Скорость /n 5 - nothing")
check = input()
if check == 1:
location = input()
elif check == 2:
vlan = input()
elif check == 3:
ip = input()
elif check == 4:
COMspeed = input()
elif check == 5:
print('Then why you press it!?')
build_config()
print("Done! Check it!")
input()
break
elif True:
print("Your input is garbage, try again")
'''
Welcome to SO.
Where you have if check == "y" or "Y" or "Н" or "н":, you want if check.lower() in ('y', 'h'):
The or operator takes two boolean values and returns a boolean value.
This expression:
lacp == 'y' or 'Y'
would be evaluated as follows:
Evaluate lacp == 'y'.
If it is true, the whole expression returns true.
Otherwise, evaluate 'Y' as a boolean value and return that. Any non-zero, non-empty value is coerced to true. So your expression returns true.
The proper general way to incorporate multiple comparisons would be:
(lacp == 'y') or (lacp == 'Y')
The parentheses should not be necessary here, but I think it is a good habit to use them to make the order of evaluation clear.
For specific cases such as yours, there might be other reasonable ways to do your test, as shown in another answer.
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']
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
I'm trying to create a small python program to emulate rolling a single die. My problem arises in that I want the program to accept both upper and lower-case 'Y' to trigger a re-roll. My program works when I accept either upper or lower case y but when I try to change the line
if usr == 'Y'
to
if usr == 'Y' or 'y'
creates a problem where it never enters the else statement, making the program never terminate.
import random
def DiceRoll():
number = random.randrange(1, 7, 1)
print("Dice Roll: ", number)
AskUser()
return
def AskUser():
usr = input("Roll Again? (Y/N) \n")
if usr == 'Y':
DiceRoll()
else :
print("Thank you for playing!")
return
DiceRoll()
You must do
if usr == 'Y' or usr == 'y'.
It is currently evaluating the statement 'y' as its own condition, and in this case 'y' always evaluates to true.
This question already has answers here:
Python And Or statements acting ..weird
(5 answers)
Closed 6 years ago.
How can I make sure the user input only 'y' or 'n' in and make the program only accept 'y' or'n' as an answer?
while True:
try:
cont = input("Do you want to continue? If so enter 'y'.")
if cont != "n" or cont !="y":
print("Please enter 'y' or 'n'")
else:
break
except ValueError:
print("Please enter 'y' or 'n'")
else:
break
A condition of the type if cont != "n" or cont !="y": will always be true as cont can not be n and y at the same time.
You should use and operator instead of or operator. To avoid such confusion, you can try and write such conditions in close to english way, like this
cont="a"
if cont not in ("n", "y"):
print "Welcome"
This can be read as "if cont is not one of...". The advantage of this method is that, you can check for n number of elements in a single condition. For example,
if cont not in ("n", "y", "N", "Y"):
this will be True only when cont is case-insensitively n or y
Edit: As suggested by Eric in the comments, for single character checking we can do something like this
if cont not in "nyNY":
Because it should be if cont != "n" and cont !="y":. Every word is either not n or not y.