This is my loop:
sure = input('Are you sure that you wish to reset the program?(y/n)')
while sure != 'y' or sure != 'n':
sure = input('Please awnser y or n, Are you sure that you wish to reset the program?(y/n)')
The loop carries on looping even if y or n are entered.
Change the condition to
while sure != 'y' and sure != 'n':
Your condition as written will always be True no matter what they enter. An alternative would be
while sure not in ('y','n'):
You need to do and instead of or . When doing or it will continue to the loop if sure is not y as well n , but sure cannot be both at the same time, hence it loops forever.
Example -
sure = input('Are you sure that you wish to reset the program?(y/n)')
while sure != 'y' and sure != 'n':
sure = input('Please awnser y or n, Are you sure that you wish to reset the program?(y/n)')
The problem is in your logical expression:
sure != 'y' or sure != 'n'
Using De Morgan's Law, this could be rephrased as:
!(sure == 'y' and sure == 'n')
Obviously, sure can never be both 'y' and 'n', so this doesn't work. What you want instead is:
sure != 'y' and sure != 'n'
Related
This question already has answers here:
not equals operator(!=) not working in python string comparison
(2 answers)
Closed 1 year ago.
Trying to add validation to user input.
So the code is:
print ('Does this service require an SFP Module? (y/n): ')
while True:
sfpreq = input()
if sfpreq != 'y' or 'n':
print("You must enter either y or n")
continue
else:
break
So even when the user enters 'n' it returns the "print("You must enter either y or n")" and continues the loop.
I have tried setting the variabl manually to and also tried another convention I found on realpython and also removed the if statement from the while loop:
sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
print("You must enter either y or n")
else:
print("Test")
Again it just returns:
admin#MacBook-Pro Learning Folder % python3 test22.py
You must enter either y or n
Am I just missing something very fundamental here?
Problem with the logic
sfpreq = "n"
if sfpreq != 'y' or sfpreq != 'n':
print("You must enter either y or n")
else:
print("Test")
Here, when you enter the if loop,
sfpreq != 'y' is validated as True and sfpreq != 'n' is validated as False.
Now True OR False statement in boolean algebra equates to True.
So, the if loop gets executed and You must enter either y or n is printed.
See, more about boolean algebra here
A better solution
sfpreq = "n"
if sfpreq not in {"y","n"}:
print("You must enter either y or n")
else:
print("Test")
So, here we are checking if y or n is not there in the set {"y","n"}. As in this case, sfpreq is there in that set so,the else statement gets executed.
I'm new to python and I'm trying to write a program that will guess the users number.
I'm trying to change the range that's in a while loop, depending on the users answer, but i'm not sure how can I do that.
list = range(100)
half = len(list)//2
def the_guess():
guess = "n"
while guess != "y":
guess = input('is it ' + str(len(list)//2) + '? up(+) or down(-) ?\n')
if guess == 'y':
print('I knew it!!')
break #stops loop?
else:
if guess == '+':
print(list[half:])
# use second part of the range
if guess == '-':
print(list[:half])
# use first part of the range
else:
print("ok, let's try again\n")
the_guess()
The loop works, i'm just not sure how to go about changing the value of the range to something other than 100.
for example:
if the user inputs a "+" I want the range to change to 50 - 100, and will continue to dividing it depending on the users input.
I’m just starting to learn functions and I am practicing on implementing some into my code. Just a simple example... how can I code this to loop properly and break out when the user wants?
def profit(i,c):
gain = c - i
print('Your profit is:' + '' + str(gain))
def beginning():
x = float(input("What was your initial investment?"))
y = float(input("What is your investment worth now?"))
profit(x,y)
beginning()
ans = 'y'
while ans == 'y' or ans == 'Y':
ans = str(input('Would you like to calculate another investment? (Y/N)'))
beginning()
if ans != 'y' or ans != 'Y':
break
There are two ways to break out of a while loop. The first way is obviously the break statement, kind of like you have done. For it to work correctly, you need to change the condition:
if ans != 'y' or ans != 'Y':
break
This will always be true, since ans cannot be "y" and "Y" at the same time. You should change it into:
if ans not in ["y", "Y"]:
Or
if ans.upper() != "Y":
In your case however, you don't need it at all. Since in both the if statement and the while condition you are checking ans, you can get rid of the if and just rely on this.
while ans.upper() == "Y":
This will end the loop automatically when ans becomes anything other than "Y" or "y".
The only reason you would use a break here is if you wanted to exit the loop immediately, and not complete the current iteration. For example:
while ans.upper() == "Y":
ans = input("Enter selection: ")
if ans == "I want to stop right now!":
break
print("Do other things, even if ans is not Y")
In this example, "Do other things" will always be printed regardless of ans, unless ans is "I want to stop", in which case it won't get printed.
One thing you can do is ans = ans.capitalize() after you get the user input. Then remove the ans != 'y' since that's causing your loop to break.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I'm having a bit of trouble with my python3 persistent password locker. It stores and retrieves passwords as expected/desired, but I decided to insert a "backout" check so that if information is entered incorrectly you can go back and re-enter it. It seems to be skipping this check for no easily identifiable reason.
elif choice == 2:
conti = False
while conti != True:
print('Enter an account and password to store')
acc = input('Account: ')
apass = input('Password: ')
print('Account: ' + acc + '\n' + 'Password: ' + apass)
print('Correct?')
corr = input(': ')
corr.lower()
if corr == 'yes' or 'ye' or 'y':
print('Making Changes persistent')
# Shelve Stuff
conti = True
break
else:
print('Please make appropriate changes.')
continue
When I run this code it makes changes persistent regardless of what the corr variable happens to be. This is not what I want. I tried explicitly stating in an elif statement the no options and it skipped those as well. Are the multiple 'or' statements throwing it off or is there something else going on that I should be aware of?
This line is not doing what you'd hoped:
if corr == 'yes' or 'y' or 'y':
This translates to "is corr equal to 'yes'? It's not! So, is the value 'y' True? It is! Let's do this!" Note, it's not checking that corr is equal to 'y', just that the string 'y' is Truthy.
The longhand way would be:
if corr == 'yes' or corr == 'y':
but you could also do:
if corr in ['yes', 'y', 'Y', 'YES']:
or something similar to cover more options
I have written a very basic encryption program, and whilst writing the decrypting algorithm for it, I have encountered some problems with a loop I have.
from re import *
cipher = open('cipher.txt')
ciphertext = cipher.read()
keyfile = open('key.txt')
key = keyfile.read()
decoded = []
chardec = ''
inval = 1
print("Decoder for encrypt1.py")
while inval == 1:
useManKey = input("Use a manual key? Y or N\n> ")
if useManKey == 'Y' or 'y':
key = input("Please enter the key you wish to use to decrypt\n> ")
inval = 0
elif useManKey == 'N' or 'n':
inval = 0
print("OK, decrypting")
else:
print("That wasn't a valid option/nPlease re-enter")
When I run this, and declare useManKey as N or n it seems to run the if part of the loop as if I had declared it as Y or y. I am probably being stupid here, but any help would be much appreciated thanks.
useManKey == 'Y' or 'y' does not work how you think it does. What you want is useManKey in ('Y', 'y'). What you have first evaluates useManKey == 'Y', then, if that check fails, tests the string 'y' for truishness. Since non-empty strings are always truish, your if statement always evaluates to True. As is pointed out in the comments, you could also use upper() or lower() to first convert the input to a fixed case if you want.
useManKey == 'Y' or 'y'
Doesn't actually check whether useManKey value being 'Y' or 'y', Use sr2222's answer for what you need to do. ie.
useManKey in ('Y', 'y')
The earlier expression evaluates to
(useManKey == 'Y') or 'y'
Which is always True irrespective of the value of useManKey as 'y' being non-Falsy (non-None) the 'or' of these always evaluates to True,