Why is this if-else statement not working? - python

So, if the person answers "nutella", it prints "That's correct!" How do I get it to say "You're wrong!" if they answer anything else.
nutella = input
input("What's the best food in the world?")
if nutella:
print("That's correct!")
else:
print("You're wrong!")

Firstly, it seems you should look into if statements since you don't know how to use them yet, but this is how you do it, I'll try to explain as well
choice = input("What's the best food in the world?")
if choice == "Nutella":
print("That's correct!")
else:
print("You're wrong!")
So the first line assigns what the person types to the variable choice and then in the next line it checks if the value of the variable equals/is "nutella", if it is it will print "That's correct!", if it isn't it will print "You're wrong!".

The if statement in Python for a string is true whenever the string isn't empty. What you want is to compare the nutella variable with the expected string. Such as:
nutella = input("What's the best food in the world?")
if nutella == "nutella":
print("That's correct!")
else:
print("You're wrong!")

Related

I cannot use a input check to verify if the person has put in the correct code

This is my code
name=""
name=input("What is your name?")
print ("For clarification, is your name",name,"?")
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
and I was wondering if anyone could help me sort it out. In the lines below.
input("Please enter yes or no")
if input==("yes"):
print ("Thank you")
else:
name=input("What is your name?")
print ("Thank you",name,)
I am trying to ask people if they have put the correct names by asking them directly. If the answer is yes, they can move on, otherwise they will have to input their name again. Unfortunately I am not able to find the way to do it. Can anyone send me a correct code version. (An explanation would be nice but not necessary.)
Try :
while True:
n = input("Please enter yes or no")
if n == "yes":
print ("Thank you")
break
else:
name = input("What is your name?")
print ("Thank you",name)
You need to remember the second input to use it in the if statement.
response = input("Please enter yes or no")
if response == "yes":
print("Thank you")
else:
name = input("What is your name?")
You could use a recursive function.
It will loop until it returns the name.
#!python3
def get_name():
name=input("What is your name?")
print("For clarification, is your name",name,"?")
sure = input("Please enter yes or no")
if sure==("yes"):
print("Thank you")
return name
else:
get_name()
name = get_name()

Python Int object not callable

Please help! I don't understand the error here. Why do I get an error saying: "'int' object is not callable" when I type a number other than 0, 1 or 2? Instead, it's suppose to print "You have entered an incorrect number, please try again" and go back to asking the question.
Second Question: Also how can I change the code in a way that even if I type letter characters, it won't give me the Value Error and continue re-asking the question? Thank you!
def player_action():
player_action = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
if player_action == 0:
print ("Thank You, you chose to stay")
if player_action == 1:
print ("Thank You, you chose to go up")
if player_action == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
player_action()
player_action()
You should change the variable name as #Pedro Lobito suggest, use a while loop as #Craig suggested, and you can also include the try...except statement, but not the way #polarisfox64 done it as he had placed it in the wrong location.
Here's the complete version for your reference:
def player_action():
while True:
try:
user_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
except ValueError:
print('not a number')
continue
if user_input == 0:
print ("Thank You, you chose to stay")
if user_input == 1:
print ("Thank You, you chose to go up")
if user_input == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
continue
break
player_action()
The first answer to your question has been answered by Pedro, but as for the second answer, a try except statement should solve this:
EDIT: Yeah sorry, I messed it up a little... There are better answers but I thought I should take the time to fix this
def player_action():
try:
player_action_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
except ValueError:
print("Non valid value") # or somehting akin
player_action()
if player_action_input == 0:
print ("Thank You, you chose to stay")
elif player_action_input == 1:
print ("Thank You, you chose to go up")
elif player_action_input == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
player_action()
player_action()
Just change the variable name player_action to a diff name of the function, i.e.:
def player_action():
user_input = int(input("Enter 0 to stay, 1 to go Up, or 2 to go Down: "))
if user_input == 0:
print ("Thank You, you chose to stay")
elif user_input == 1:
print ("Thank You, you chose to go up")
elif user_input == 2:
print ("Thank You, you chose to go down")
else:
print ("You have entered an incorrect number, please try again")
player_action()
player_action()

Quiz that I made in python won't work

I have recently made a quiz in my computer science lesson but for some reason it did not work, I am new to programming and I was wondering maybe you could help me, I know that it will be something simple but as I said, I am new to this. I have only copied 4 questions out of the 8 I have made but for some reason it ignores the IF statement and goes straight to the else statement. The code is the following:
score=0
print("Welcome the the general knowledge quiz")
your_name = input("What is your name?: ")
input("Press Enter to Start the Quiz!")
print("1) Who presents Pointless?")
answer = input()
if answer == ["Alexander Armstong", "alexander armstrong", "ALEXANDER
ARMSTRONG"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was Alexander Armstrong")
print("Your score is", score)
print("2) Who presents I'm a celeb, get me out of here?")
answer = input()
if answer == ["Ant and Dec", "ant and dec", "ANT AND DEC", "Ant And Dec"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was Ant and Dec")
print("Your score is", score)
print("3) What is the capital of England?")
answer = input()
if answer == ["London", "london", "LONDON"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was London")
print("Your score is", score)
print("4) Who lives on the White house right now?")
answer = input()
if answer == ["Obama", "obama", "Barack Obama", "barack obama"]:
print("Well done", your_name)
score = score+1
else:
print("Sorry, the answer was Barack Obama")
print("Your score is", score)
answer = input()
if answer == ["Alexander Armstong", "alexander armstrong", "ALEXANDER
ARMSTRONG ):
Missing quotation mark aside, this if statement will always fail. input() always returns a string, but you're checking if it's equal to a list, which can never be true. If you replace == with in, it will do what you expect.
Also, you should consider using .lower() to make the answer into lowercase, then you'd only have one value to check.
There's a hint in the syntax highlighting: you're missing a ":
if answer == ["Alexander Armstong", "alexander armstrong", "ALEXANDER ARMSTRONG ):
print("Well done", your_name)
There's no " after ARMSTRONG.

an if Statement inside an if Statement?

FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
undescribed image
Your code is quite clear. What I understand is you want to ask another question if animal is patted.
FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround=="Yes" or FarmGround=="yes": #this is if
print("You patted the animal")
holy_field = input("Did you clear the field?")
if holy_field.lower() == "yes":
print("Do something else. Don't look at me.")
else:
print("When are you going to do it ?")
elif FarmGround== "No" or FarmGround== "no": #this is elif
print("You didn't patt the animal and it is triggered")
You can indent additional statements, including if statements inside your existing if block, just like you're indented the first print statement. It's not clear from your question what exactly you want to do, so I'll fill in some pseudo-code (which you can replace with whatever you actually want):
FarmGround=input("Do you want to pat the animal? ")
if FarmGround==("Yes") or FarmGround==("yes"):
print("You patted the animal")
some_other_answer = input("Some other question?") # here's more code inside the first if
if some_other_answer == "Foo": # it can include another if statement, if you want it to
print("Foo!")
elif FarmGround==("No") or FarmGround==("no"):
print("You didn't patt the animal and it is triggered")
Indentation matters in python. To nest an if statement in another if statement, just indent it below the first with 4 spaces.
If ( var1 == 1 ):
If ( var2 == 2 ):
print "Both statements are true."

My python code does not run a print statement at the end of a loop

I have this problem when i run the program it all goes good an all, but when a user gets the right answer, the code does not print neither print("Good Job!") or print("Correct"). what is wrong with the code ?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (userAnswer != result) :
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
input("\n\n Press to exit")
The problem is that your while-loop will only run as long as the first answer is wrong. Everything that is indented after while (userAnswer != result) will be ignored by Python if the first answer is right. So logically a first correct answer can never reach print("Correct"), since that would require the answer to be both wrong (to start the while loop) and right (to get to "Correct").
One option is to get rid of the while-loop, and just use if's. You get two chances this way, then you lose.
if (userAnswer == result):
print("Well done!")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
else:
print("Nope all wrong you lose")
Another option is to make an infinite loop using While. (like #csharpcoder said)
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In the last option a wrong answer gets "Wrong answer" and the while-loop starts again, since True is of course still True. So you try again, until you get the right answer, which will bring you to "correct, good job" and then break (which stops the loop).
I struggled with while-loops and kind of getting it in my head that indentation means Python will treat it as 'one thing' and skip it all if I start it with something that's False.
If the answer is correct, then
while (userAnswer != result) :
will cause the loop contents to be skipped.
First of all, you get input outside of your loop and then don't do anything with it. If your answer is correct on the first try, you will get no output because userAnswer != result will be False immediately and your while loop won't run.
Some other points:
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
is redundant because you are guaranteed to fall into one of these, as you will only get here if the answer is wrong (and therefore > or < result). Just print "Wrong" without a condition, as the only reason this would run is if the answer was wrong.
print("Correct")
print("Good Job!")
You can use \n to print on a new line instead of having multiple print statements together. Usually you only use multiple prints together for readability, but print("Correct\nGood job!") isn't that much less readable.
if (userAnswer == result):
#...
break
You don't need break here because the answer is already correct and the loop won't repeat anyway.
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
Here, you append string literals to string literals ("Hello!" + " "). You don't need to do that as you can just write "Hello! ".
result = firstNumber + secondNumber
result = int(result)
The result (pun not intended) is already an integer, so you don't need to convert it.
How about using a infinite while loop something like this :
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In your logic if you enter the wrong answer first time and correct answer afterwards , then it will work as per your requirement , but if you enter the correct answer first time it will simple skip the while loop .
I played around a bit to refactor, in an attempt to make it more clear:
import random
name = input("Hello ! What's your name? ")
print("Hello, {name}!".format(name=name))
print("Ok, {name}, let's start!".format(name=name))
first_number = random.randint(1, 50)
second_number = random.randint(1, 50)
correct_answer = first_number + second_number
print("What is, '{first} + {second}'?".format(first=first_number,
second=second_number))
user_answer = None
while user_answer != correct_answer:
try:
user_answer = int(input("Your answer : ")) # ValueError will be raised if non integer value given
except ValueError:
print("Invalid Input!")
user_answer = None
if user_answer:
if user_answer == correct_answer:
print("Correct")
print("Good Job!")
else:
print('--> Wrong, try again!')
input("\n<< Press any key to exit >>")

Categories