Very simple code, not working - python

I am trying to elicit two responses depending on user input, and can't get it to work. It just keeps printing "Correct, seems you're smarter than I thought...". Any help would be much appreciated, thank you
print ("Welcome to UTOPIA")
river= ""
while not river:
river = input ("\n\n\n\nYou come across a raging river, what do you do? ")
if river == "swim" or "swim through it":
print ("Correct, seems you're smarter than I thought...")
elif river == "walk through it" or "walk through":
print ("You cant walk through such a big river... silly!")
else:
print ("Well, sensible suggestions now...")

The issue has to do with your if statements. An or will not automatically look at the last variable used so it must be specified again. If "some string" will always evaluate to true as long as the string isn't empty.
print ("Welcome to UTOPIA")
river= ""
while not river:
river = input ("\n\n\n\nYou come across a raging river, what do you do? ")
if river == "swim" or river == "swim through it": #Notice the change
print ("Correct, seems you're smarter than I thought...")
elif river == "walk through it" or river == "walk through": #Notice the change
print ("You cant walk through such a big river... silly!")
else:
print ("Well, sensible suggestions now...")

Because you're doing
if river == "swim" or "swim through it":
# ...
which is not correct code.
Essentially you're saying "If river is swim or string "swim through it" " which doesn't make sense.
You're looking for
if river == "swim" or river == "swim through it"

All non-empty strings are (unfortunately) True in Python.
That means that this will always be True:
if something or "string":
Because or "string" will always be True.

Related

Chatbot in python generates random answers if the userinput contains more than one word

My problem is, that my program randomly generates a random answer if the userinput contains more than one word, even though i don't want to. I mean i understand why the programm generates a random answer, but how can i overcome this?
Here is my code:
import random
print("Welcome to Chatbot! Have fun.")
print("")
randomanswer = ['Thats not good', 'me too', 'how about you?']
reactionanswer = {'hello': 'hello, whats up?',
'sad': 'speak to me',
'entertainment': 'how can i entertain you?'}
userinput = ''
while True:
userinput = input("Question/Answer: ")
userinput = userinput.lower()
if userinput == 'bye':
print("See you soon!")
break
else:
usersplit = userinput.split()
for i in usersplit:
if i in reactionanswer:
print(reactionanswer[i])
else:
print(random.choice(randomanswer))
Works fine for me, I ran exactly your code and get this:
Question/Answer: hello guy
hello, whats up?
Thats not good
Question/Answer: nothing in the list
me too
me too
me too
Thats not good
work also for several words. it depend on what works meaning - you wrote that for each word that not in your known list it would generate random answer. and for any known word it will answer as you want to. and that exactly what happen - in the first case the first word generated the first known answer and the second generated random answer. clarify what exactly not work as you expect.
The problem is that even though you found your answer the for loop continues to run. Add add "break" statement if the word has been found in answers. Like this:
else:
usersplit = userinput.split()
for i in usersplit:
if i in reactionanswer:
print(reactionanswer[i])
break < --- add this
else:
print(random.choice(randomanswer))

else statement not executing

The part of my code where I ask the user if they want some cake has me confused.
import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or 'ya' or 'Ya':
print("Cool!")
else:
print('Aww..')
Sample Input:
ya
yes
no
something other
Expected Output:
Cool!
Cool!
Aww..
Aww..
Actual Output
Cool!
Cool!
Cool!
Cool!
Why is the line print('Aww..') not executing?
An if statement is built on conditions. If you plan to use a statement with multiple different 'triggers' you must state the new conditions for each.
As such, your statement requires cake == for every potential true or false outcome.
import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'yes' or cake == 'ya' or cake == 'Ya':
print("Cool!")
else:
print('Aww..')
To help with your confusion, I believe the or 'ya' or 'Ya' resulted in true due to both the user input and 'ya'/'Ya' being of the string type.
Do not quote me on that last part. My assumption may be incorrect.
Edit: Your comment "
Isaac It probably works but the or should hook them up. It was working earlier. It will work with one word but if not it will all ways say Cool!" suggests that my assumption regarding the type match resulting in true is in fact correct. That could be why earlier testing could have made the or seem like it was hooking the different possibilities.
The following code if cake in ('yes', 'Ya','ya'): would be the correct method of 'hooking' the different possibilities into a single condition.
Fixed Answer for OP:
import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake in ('yes', 'Ya','ya', 'fine', 'sure'):
print("Cool!")
else:
print('Aww..')
I haven't written a single line of python before, but my intuition says you need to replace
if cake == 'yes' or 'ya' or 'Ya':
with
if cake == 'yes' or cake == 'ya' or cake == 'Ya':
You could try Word in array of words (again, untested, just a guess)
if cake in ['yes','ya','Ya']:
Non-empty strings are always evaluated as True in Python. Your code
if cake == 'yes' or 'ya' or 'Ya':
, using boolean logic, will always execute the tasks under it no matter you enter there. So it always prints "Cool!".
To prevent this from happening you should modify your conditional if statement in such a way that you will only catch the words 'yes', 'ya' and 'Ya'. Thus, if cake == 'yes' or 'ya' or 'Ya': should be replaced with
if cake == 'yes' or cake == 'ya' or cake == 'Ya':
or if you are already familiar with Python lists
if cake in ['yes', 'ya', 'Ya']: # Evaluates to True if cake is
# equivalent to one of the strings in the list
Read this thread for more details on the truth value of a Python string.

Python 3 - if statement not matching exact string

I'm following the "Learn Python The Hard Way" book. In the partial example below the input string is compared against some values.
When I execute the code, if you enter any input that contains the word + any other character, it is still evaluated to True,
e.g. > fleeee, headsss, headhead
def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"
choice = raw_input("> ")
if "flee" in choice:
start()
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room()
How can I modify it so it matches 'head' exactly?
Use == instead of in.
By using in you search if it's inside.
Using == checks for the exact string.

Conditional statements with multiple if statements (Involves raw_input)

I'm experimenting with raw_input and it works fine except for my 1st if statement and my else statement. Whenever I run the code and answer the 2nd question with a raw_input listed after 'League' in the 1st if statement, it returns both the 1st if's print and the else's print when it should only print the 1st if. Any idea what's wrong?
name = raw_input('What is your name?\n')
game = raw_input('\nWhat MOBA do you play/have played? \n(The answer ' \
'must be case sensitive i.e. LoL for League and DoTA for y\'know the whole darn thing '\
'is too '\
'darn long to say even though I typed a lot more than the name)\n')
if game in ('League' , 'League of Legends' , 'LoL'):
print '\nYou go girl! '
if game in ('DoTA' , 'DoTA 2' , 'DoTA2'):
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
you can always use if for the first conditional, elif for any number of other conditionals (if the input is in the second list in your instance) and else if the input is not in any of those lists, your indentation is also a little messed up,nesting if statements inside each other will only run the nested conditional if the first statement is true, I'd also recommend you use the string.lower() method on your users input so you don't have to instruct the user to type case-sensitive input and use variables to store those lists so you can reuse them elsewhere in your code..something like this:
name = raw_input('What is your name?\n')
game = (raw_input('\nWhat MOBA do you play/have played?')).lower()
awesomeGames=['league' , 'league of legends' , 'lol']
coolGames=['dota' , 'dota 2' , 'dota2']
if game in awesomeGames:
print '\nYou go girl! '
elif game in coolGames:
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
The indent level is incorrect.
Spend one more space for the second if statement.
or 1 less space and elif instead of the second if.
Replace the second if condition by elif. elif can be used as many times as you want until the condition matches but its better practice to have the last condition as else (which is like default statement when other conditions have failed)

Making multiple list items apply in python

What I’d like to is make my code so that if I enter "You are a " plus a complement word (in the list) and or another word like "You are a nice robot" It will print out: "Thank You!"
Here is my code:
complements = ["nice","happy","good","smart","wonderful"]
def chat():
input = raw_input("You: ")
if input in "You are a ":
if input in complements:
print "TIM: Thank you"
else:
print "I don't understand"
chat();
No matter what I do, it automatically goes to the else statement
You have two main problems:
if input in "You are a ": tests whether the whole input is in "You are a ", not whether that phrase is at the start of the input; and
if input in complements tests whether the whole input is in your list, not whether one item from your list is in the input.
Try something like:
def chat(compliments=["nice", "happy", "good", "smart", "wonderful"]):
input = raw_input("YOU: ")
if input.startswith("You are a "):
if any(input[10:].startswith(c) for c in compliments):
print "TIM: Thank you"
This gives me:
>>> chat()
YOU: You are a nice robot
TIM: Thank you

Categories