Why is my conditional returning "none?" [duplicate] - python

This question already has answers here:
String comparison in Python: is vs. == [duplicate]
(4 answers)
Closed 8 years ago.
Whenever I run this I get the third option when it should be returning the first, since s = 'yes'. What is going wrong here?
def shut_down(s):
if s is 'yes':
return 'Shutting down...'
elif s is 'no':
return 'Shutdown aborted!'
else:
return "Sorry, I didn't understand you"
ans = 'Yes'
s = ans.lower()
shut_down(s)

Change
if s is 'yes':
to
if s == 'yes':
and
elif s is 'no':
to
elif s == 'no':
While is is a valid operator, it is not the one to use here (it compares object identity instead of comparing the character sequences).

is tests for identity, not equality. To test if a string is equal to yes use s=='yes'

Related

Create a conversation that has a Y/N answer [duplicate]

This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed 6 days ago.
I am trying to create a small bit of code in Python that runs a conversation, then asks a Y/N question i.e "Do you believe the sky is blue?"
When I run the code, it works well until I reach the question. It ignores my parameters for Y/N answers to print specific responses. It gives me the print response attached to my "else" statement.
I am confused if I am writing my If/elif/else statements wrong?
My code is written as follows:
x = input('do you believe the sky is blue')
if x == "yes":
print("I believe you are correct")
elif x == "no":
print('I think you have a unique perspective.')
else:
print('Please answer Yes or No.)
You use .lower() to obtain a lower case version of a string, and you are missing a ' in the last print():
x = input('do you believe the sky is blue ').lower()
if x == "yes":
print("I believe you are correct")
elif x == "no":
print('I think you have a unique perspective.')
else:
print('Please answer Yes or No.')

Python If statement and logical operator issue [duplicate]

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.

Python: Elif and Else not working [duplicate]

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 constructing an interactive timetable for terminal with Python, but at the end of my code where i have if, elif and else statements no matter what user input i give it keeps passing the if statement. Any Solutions would be greatly appreciated and Thank You for your time :)
while True:
TimeTable()
print "\nDo you wish to go again? "
answer = raw_input()
if answer == "Yes" or "yes":
print " "
continue
elif answer == "No" or "no":
print "Ok then"
break
else:
print "Ok then"
break
answer == "Yes" or "yes"
# is the same as
(answer == "Yes") or "yes"
and is always True. You can solve your problem this way:
answer in ["Yes", "yes"]

If/Then statement not working inside of while loop [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
The if/else statement inside of this loop will not work. If I enter "no" it still continues the loop. I don't understand why, any help would be appreciated.
while keepPlaying == True:
play = input(str('Would you like to play rock, paper, scissors? Yes or no?\n'))
if play == str('yes') or str('Yes'):
playerChoice = input(str('Ok! what\'s your choice?\n'))
else:
keepPlaying = False
print ('Thanks for playing.')
I've put the code through a visualizer and even if the variable play != yes or Yes it still chooses the == to path.
The problem is this:
if play == str('yes') or str('Yes'):
It is equivalent to:
if (play == str('yes')) or str('Yes'):
Note that str('Yes') is always truthy (and with an or means you'll never get the false part).
You want:
if play in ('yes', 'Yes'):
Or maybe (just a tip):
if play.lower() == 'yes':
Change the if condition to play in ('Yes', 'yes', 'y', 'Y')
The issue is, the second part of the or clause (str('Yes')) always evaluates to true.

How come my program does not quit? [duplicate]

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.

Categories

Resources