Python Int object not callable - python

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()

Related

how to make it that it does not repeat?

I know that a "not repeat with random from a list" is probably seen as a info you can find, but as someone who does not have a lot of knowledge of python yet, i cannot seem to understand those answers or they do not work for my problem. So I hope any of you are able to help.
as my first small project I am building a truth or dare program, and now I am at the point that I want to make it that the questions cannot be asked twice, and that if the truth questions are all done it prints that announcement, and I want the same for my dare questions.
here is my program so far, sorry if it is messy:
import random
import time
truth = ["If you could be invisible, what is the first thing you would do?",
"What is a secret you kept from your parents?",
"What is the most embarrassing music you listen to?",
"What is one thing you wish you could change about yourself?",
"Who is your secret crush?"]
dare = ["Do a free-style rap for the next minute",
"Let another person post a status on your behalf.",
"Hand over your phone to another player who can send a single text saying anything they want to anyone they want.",
"Let the other players go through your phone for one minute.",
"Smell another player's armpit."]
print("Hello, and welcome to my truth or dare show, just type truth or type dare to get a question!")
lives = 3
while lives > 0:
choice = input("truth or dare?: ").lower()
time.sleep(0.5)
if choice == "truth":
print(random.choice(truth))
time.sleep(0.5)
while True:
answer_truth = input("want to answer? type yes or no: ").lower()
if answer_truth == "yes":
input("> ").lower()
print("good answer")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif answer_truth == "no":
print("you lost a life!")
time.sleep(1)
lives -= 1
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
elif choice == "dare":
print(random.choice(dare))
time.sleep(0.5)
while True:
do_dare = input(f"did you do the dare? type yes or no: ").lower()
if do_dare == "yes":
print("well done!")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif do_dare == "no":
print("you lost a life!")
lives -= 1
time.sleep(0.5)
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
else:
print("that is not an option")
time.sleep(0.5)
print("GAME OVER!")
This should work:
choice = random.choice(truth)
time.sleep(0.5)
# inside the loop
truth.remove(choice)
if len(truth) == 0:
print("all questions are done")
do the same for dare
You probably want a construct like this:
from random import shuffle
ls = ["a", "b", "c"]
shuffle(ls)
lives = 3
while lives > 0 and ls:
current_question = ls.pop()
... # Rest of your code
So you want to select a random option, but then no longer have it in the set that you select random things from in the future.
If you imagine it physically, you have a jar list that has papers item's in it and you want to take them out at random. Obviously, any that you take out can not be taken out again.
We can accomplish this by removing the item from the list after it's 'picked'
To answer your question about having it let them know there are no more truths or no more dares, we can simply add a conditional to the whole truth segment and one to the whole dare segment as well, then further, if both run out, end the game.
while lives > 0 and (len(truth)>0 or len(dare>0)):
# Rest of the program
if choice == "truth":
if len(truth) > 0:
# Code
else:
print("there are no more truths (existential crisis), maybe try a dare instead")
elif choice == "dare":
if len(dare)>0:
# Code
else:
print("there are no more dares *sigh of releif*, maybe try a truth instead")

Why is this if-else statement not working?

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!")

Heads or Tails in Python

The if and elif conditions aren't working and I am not even getting an error. The code is intended to match the users input to what the computer selects and then make a call, if the user won or lost.
import random
def flip():
return random.choice(["Heads", "Tails"])
Users_Selection = (input("Choose: Heads or Tails?"))
print("Flipping the coin. Please wait!")
print ("It a", flip())
if flip()=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif flip()=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")
All help is genuinely appreciated!
Everytime you call flip, it generates a new random output so you must store the value of flip in a variable.
c = flip()
print("It's a ", c)
if c=="Heads" and "Heads"==Users_Selection:
print("Congratulations, you won!")
elif c=="Tails" and "Tails"==Users_Selection:
print("Sorry, You loose! Please try again")

Why is my program goes straight to else block when it should enter if

I was trying to make a simple survey bot, but I had trouble with the second if statement. it just ignores the if and elif, and goes straight to the else statement. I have tried everything, and even though it's probably going to be an easy solution please help...
import sys
yes = "yes"
no = "no"
experience_good = "yes"
contact = "1"
print("How many times have you bean contacted by us in the past quarter (3 months)")
contact = sys.stdin.readline()
if contact != 0:
print("Was your experience was us good? Type a 1 for yes or 0 for no")
experience_good = sys.stdin.readline()
print("experiencence_good is", experience_good)
# The above line was just to double check the variable was inputted
correctly
if experience_good is 1:
print("Good to hear that.")
elif experience_good is 0:
print("Sorry about that. What could we be doing better?")
doing_better = sys.stdin.readline()
else:
print("Stuff's been messed up")
The output I get is just:
How many times have you bean contacted by us in the past quarter (3
months)
3
Was your experience was us good? Type a 1 for yes or 0 for no
1
exp_good is 1
Stuff's been messed up
because experience_good is never 1! It's starts off as
experience_good = "yes"
Then halfway through it maybe changed as
experience_good = sys.stdin.readline()
At this point if the user typed in 1, what the variable will hold is the string value '1' which is not 1 so you need to
experience_good = int(sys.stdin.readline().strip())
You must use == for int equality test:
if contact != 0:
print("Was your experience was us good? Type a 1 for yes or 0 for no")
experience_good = sys.stdin.readline()
print("experiencence_good is", experience_good)
# The above line was just to double check the variable was inputted correctly
if experience_good == 1:
print("Good to hear that.")
elif experience_good == 0:
print("Sorry about that. What could we be doing better?")
doing_better = sys.stdin.readline()
else:
print("Stuff's been messed up")
Cast the contact and experience_good to int:
contact = int(contact)
experience_good = int(experience_good)
Indentation problem (now edited in question). Bring the last elif and last else block one indent backwards.
if experience_good == 1:
print("Good to hear that.")
elif experience_good == 0:
print("Sorry about that. What could we be doing better?")
doing_better = sys.stdin.readline()
else:
print("Stuff's been messed up")
Use == to evaluate a value. When you use 'is' it will compare the objects. Not it's value.

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