This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 years ago.
EDIT - Apparently this is a duplicate. And while I've no doubt the core problems are answered elsewhere I think that the level is pretty blatant and thus the ability to comprehend other solutions and transpose them into my own problem is diminished. I searched before asking.
I'm just having a mess about and was trying to write a little thing with user input.
However, I'm not sure how to go about this without knowing how many iterations are needed, or having two questions?
I tried to modify it to take an if condition, which I don't really want anyway but that didn't work either :
for i in range(50):
userIn = raw_input()
urlList.append(userIn)
print 'Continue? Y/N'
ynAns = raw_input()
if ynAns == 'n' or 'N':
break
Basically I'm just trying to take user input to fill up a list and then print it out.
I also tried
import sys
listOne = []
num = int(raw_input('How many'))
for x in range(num):
listOne.append(raw_input(('Entry #' + x+1 + ' '))
print listOne
pretty basic
You need to compare ynAns with both 'n' and 'N':
if ynAns == 'n' or ynAns == 'N':
An alternative syntax:
if ynAns in ('n', 'N'):
The reason why your if statement doesn't work is that ynAns == 'n' and 'N' are two separate expressions. 'N' is always evaluated to True, so the if condition is always true.
It's basically jh314's answer, but shorter:
if ynAns.lower() == 'n':
What it does is converts ynAns to lowercase, making your code more concise.
Dont use a for loop for this, you´re restricting your app to run within a limit of 50 iterations, instead use while:
userInput = None
userInput = raw_input("Enter input (N or n to stop): ")
while(userInput not in ['N', 'n']):
urlList.append(userIn)
userIn = raw_input("Enter input (N or n to stop): ")
Related
# Dice Rolling Random Number and Guessing Game
import random
user_choice = 'y'
while user_choice != 'N' or user_choice != 'n':
print(random.randint(1,6))
user_choice = input("Do you want to continue: ")
print("You are exited")
The logic of the while condition is wrong.
Your loop runs forever, because the character will ALWAYS be different from one of the suggested characters. So the while condition is always true as at least one of the two parts is always true.
You want something like
while user_choice != 'N' and user_choice != 'n':
...
If you want to go for a more 'pythonic' way, query a set in the while condition:
while user_choice not in {'n', 'N'}:
....
There are many similar ways with tuples, lists, ... to express the condition other than querying every character individually in a chain of 'and' conditions.
As far as coding is concerned, the question is answered already, but I'd like to offer a more deep explanation of why the answer was the and operation instead of or.
The question "Did the user enter neither 'n' or 'N'?" can be expressed using Boole Algebra as
Answer = Not('n' or 'N'), and using the DeMorgan theorem this can be rewritten as
Answer = Not('n') and Not('N')
In your code, the first of the two ways to write this would look like
while !(user_choice == 'N' or user_choice == 'n'):
I hope this clears up the logic behind your question.
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 am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
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 7 years ago.
I managed to get this code to work before, but I've changed something accidentally and can't figure out what.
The code that will not work is:
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
When I run the code and put in one of the answers, the program will not run the next part and gives no error message.
In case it is necessary, I have put the code for the entire program below:
import random
import sys
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
try:
value = int(code)
except:
print ("Invalid code")
continue
if 1 <= value <= 100:
print (code)
print ("Valid code")
print ("I will now try to guess your number")
number = random.randint(1, 100)
while number > int(code) or number < int(code):
print ("Failed attempt. Number guessed is")
number = random.randint(1, 100)
print (number)
else:
if number == int(code):
print ("Your code is")
print (code)
else:
print ("Invalid code")
EDIT: Thank you so much, the yes option is working now, but the program will still not exit when selecting any of the no options, as it did before. The edited code is:
if answer in ('no', 'n', 'No', 'N'):
sys.exit()
elif answer in ('yes', 'y', 'Yes', 'Y'):
I checked by printing the answer value, and i believe it is registering the no input but not executing the command that follows for some reason.
EDIT: I'm still a bit fuzzy on the logic, but changing it to exit() fixed the problem. It asks for confirmation when closing now, when it didn't before, but otherwise sorted.
Problem causing silent exit:
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
That test is testing answer == 'no' as one test, then 'n' as a separate test, and so on. or chains return when any test returns a "truthy" value (or the last evaluated value if none are truthy), so the test always ends up evaluating as "truthy" because a non-empty string like 'n' is truthy. If you're trying to test for any one of those values, you'd do an "is contained in" test to see if answer is one of a recognized group of values, e.g.:
if answer in ('no', 'n', 'No', 'N'):
The reason is due to this expression:
if answer == 'no' or 'n' or 'No' or 'N':
In python, the above is exactly the same as this:
if (answer == 'no') or ('n' != '') or ('No' != '') or ('N' != ''):
Since all but the first expression evaluates to true, the whole expression is true.
The simplest solution is to convert your input to lowercase and trim off any extra space, then check if the answer is in a list of allowable answers so that you can easily compare for "n", "N", "no", "NO", "No", "nO".
if answer.strip().lower() in ("n", "no"):
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I am trying to write a number guessing program as follows:
def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
if n == 'True':
guess = guess + int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'False':
guess = guess - int(guess/5)
print
print 'What about',guess, '?'
break
elif n == 'Correct':
print 'Success!, your number is approximately equal to:', guess
oracle()
What I am trying to do now is get this sequence of if/ elif/ else commands to loop until the user enters 'Correct', i.e. when the number stated by the program is approximately equal to the users number, however if I do not know the users number I cannot think how I could implement and if statement, and my attempts to use 'while' also do not work.
As an alternative to #Mark Byers' approach, you can use while True:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Your code won't work because you haven't assigned anything to n before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.
Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.