Calling a function in an if statement? - python

I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")

This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.

If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.

Related

How do I stop this from repeating?

I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?

Elif Command Not Working Even When It's Response Is Typed

So, I'm quite new to python and I've been trying make a game. It goes as follows.
-Asks for name (Done)
-Returns a username made of the first two letters of each name (Done)
-Asks user to play (Issue is here)
What happens is that it rolls the dice if you pick yes but is meant to give you a simple goodbye when you say no, however when you say no it still rolls the dice and then returns the result and tell you if you've won or not.
Everything else seems to work fine, it's just where even if you type the response to the elif, the if still takes place. If anybody could take a look at this for me I'd be thankful.
from random import randint
print ("Hello, whats is your first name?")
first_name = input()
print ("What is your second name?")
second_name = input()
username = first_name[0] + first_name[1] + second_name[0] + second_name[1]
print (username + ", I want to play a game. Do you accept?")
game = input()
if game.lower() == "yes":
print ("Great, let's play. I'm going to roll a dice, if it lands on a 6, you win. If not, you lose.")
dice_roll = (randint(1,6))
print (dice_roll)
if dice_roll == 6:
print ("Congrats, you win.")
elif dice_roll != 6:
print ("Sorry. You lose.")
elif game.lower() == "no":
print ("Fine, leave then.")
I think you have an indentation issue with your code. That is why the dice is rolled even if the user typed in something different from "yes"
from random import randint
print("Hello, whats is your first name?")
first_name = input()
print("What is your second name?")
second_name = input()
username = first_name[0] + first_name[1] + second_name[0] + second_name[1]
print (username + ", I want to play a game. Do you accept?")
game = input()
if game.lower() == "yes":
print ("Great, let's play. I'm going to roll a dice, if it lands on a 6, you win. If not, you lose.")
dice_roll = (randint(1,6))
print (dice_roll)
if dice_roll == 6:
print ("Congrats, you win.")
elif dice_roll != 6:
print ("Sorry. You lose.")
elif game.lower() == "no":
print ("Fine, leave then.")
You can wrap the logic of rolling the dice inside an if statement if the user inputs yes. Otherwise, you can branch to an else statement and print goodbye.
if game.lower() == "yes":
# Roll dice here
else:
# Print out goodbye

Python script works when I run from IDLE but not in command line?

I'm working on a school project, and we have to make a script.
Basically, whenever I'm in IDLE and I press F5 to run the script everything works fine, but when I double click the python file itself and go into command line, I only get to input one thing (R or L) and then the window closes. Why is this ? I think one of the requirements for the assignment is that it need to be executed in Command Line, so this is why I'm asking.
Here is my script (it's not finished yet)
import os
import csv
import sys
def main():
menu()
def menu():
print ("******MAIN MENU******")
print()
veryFirstChoice = input("Would you like to register an account, or log in? Type R to register and L to log in ").upper()
if veryFirstChoice == "R":
register()
elif veryFirstChoice == "L":
login()
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return quiz()
print("Incorrect credentials,please try again. ")
return login()
def register():
username = input("Please input the first 3 letters of your first name and your age ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
menu()
def quiz():
choice1 = input ("""Would you like to take the Chemistry Quiz,or the Computer Science quiz ? Type in CH for Chemistry or CS for Computer Science """).upper()
score = 0
if choice1 == "CH":
choice2 = input ("Would you like to do the easy, medium or hard questions ?").lower()
if choice2 == "easy":
load_profile = open("chemistryquiz.txt","r")
lines = load_profile.read().splitlines()
question1 = lines[4]
question2 = lines[5]
question3 = lines[6]
question4 = lines[7]
question5 = lines[8]
print (question1)
answer1 = input("Please enter your answer ").upper()
if answer1 != "A":
print ("You got the wrong answer, your score is", score)
else:
score1 = (score+1)
print ("Your score is", score1)
print (question2)
answer2 = input("Please enter your answer ").upper()
if answer2 != "A":
score1 = score1
print ("You got the wrong answer, your score is", score1)
else:
score2 = (score1+1)
print ("Your score is", score2)
print (question3)
answer3 = input("Please enter your answer ").upper()
score2 = score1
if answer3 != "A":
score3 = score2
print ("You got the wrong answer, your score is", score3)
else:
score3 = (score2+1)
print ("Your score is", score3)
print (question4)
answer4 = input("Please enter your answer ").upper()
if answer4 != "A":
score4 = score3
print ("Wrong answer, your score is ", score4)
else:
score4 = (score3+1)
print ("Your score is", score4)
print (question5)
answer5 = input("Please enter your answer ").upper()
if answer5 != "A":
score5 = score4
print ("You got the wrong answer, your score is ", score5)
else:
score5 = (score4+1)
print ("Well done, your score is ", score5)
if choice2 == "medium":
load_profile = open("chemistryquiz.txt","r")
lines = load_profile.read().splitlines()
question1 = lines[13]
question2 = lines[14]
print (question1)
answer1 = input("Please enter answer ").upper()
if answer1 != "A":
score1 = score
print ("Wrong answer ", score1)
else:
score1 = (score+1)
print ("Noice, score is ", score1)
main()
I'm assuming you're on Windows?
This is the way window's console is working; it closes as soon as the program running in it exits. I'm guessing your program ends with an error or just ends normally, in either case, windows immediately closes the console window (yay).
One way to avoid this is adding a input("press enter to exit.") at the end of your program. This doesn't help if the program crashes though, in which case the comment above by Vinny is the way to go: open a command window manually, and manually launch your program by typing python and then the path to your .py file. IN case of an error in your program it will then get printed and you'll drop back into the cmd shell prompt.
You can run it by double clicking if the file extension is associated to the python interpreter, the problem is with the terminal/cmd window closing immediately after the script finish execution. to fix this you have 2 options:
Add a blocking statement to your script at the end, for example a input('Press enter to exit.'), after your main() execution. This way the script will not terminate immediately but after you press a key.
Run the your script from a terminal/cmd instance that will remain after the script execution

Bug with a program for a guessing game

I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a correct guess, you tell the user they are out of tries and tell them they lost. When the program finishes after a correct or 3 wrong tries and the game is over, you ask if the user wants to play again. If they say "yes", you star the game again and if they say "no", you end the game.
This is the code I have come up with:
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"
Now when you guess the correct number before 3 tries, the program seems to be working fine, but even when the number of wrong tries exceeds 3, the program keeps asking for more guesses but I want it to stop the program right there. The second thing I don't get is how do I start the whole game again when the user wants to play again?
How can I modify my code to fix these errors?
The simplest way to stop a loop when some condition becomes true is to use break. So when the player guesses correctly, the code would look like
if inp == x:
guess = True
print "Correct! You won"
break
Additionally, you should break the loop when you run out of guesses, otherwise it will keep running
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
break
To let the player play again, you can have a variable playing and use it in a while loop that wraps the whole game, and when they say they don't want to play anymore, make it False so that the outer loop ends.
playing = True
while playing:
x = round(random.random()*5)
guess = False
tries = 0
while guess != True:
...
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
playing = False
elif again =="yes":
print "Great!"
As you noted in comments on another answer, when the player gets their third guess wrong, the game tells them they have 0 guesses left and to try again, and then tells them they are out of tries and that the game is over. Since you want it to only tell them they are out of tries and that the game is over, you can change the main block of code to:
while guess != True:
inp = input("Guess the number: ")
if inp == x:
guess = True
print "Correct! You won"
else:
tries = tries + 1
if tries == 3:
print "Wrong guess! You are out of tries"
print "Game Over!"
break
else:
print "Wrong guess! Try again."
print "Your remaining tries are",(3-tries)
I guess this is it. Tested this out. Working Perfect (Y)
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
guess = True
print "Okay thanks for playing!"
elif again =="yes":
tries = 0
print "Great!"
Hope this helps.
Here's more compact code you can try. Also it is solving your "Wrong Guess. Try Again." issue on last guess.
import random
x =round(random.random()*5)
guess = False
tries = 0
print x
while guess != True:
while tries<3:
inp = input("Guess the number: ")
if inp == x:
guess = True
print "Correct! You won"
break
else:
tries = tries + 1
if tries == 3:
break
print "Wrong guess! Try again."
print "Your remaining tries are", (3 - tries)
if not guess:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
guess = True
print "Okay thanks for playing!"
elif again == "yes":
tries = 0
if guess:
guess = False
x = round(random.random() * 5)
print "Great!"
this is a slightly different version to your problem:
import random
def play():
x = round(random.random()*5)
guess = False
tries = 0
while guess is False and tries < 3:
inp = raw_input("Guess the number: ")
if int(inp) == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries == 3:
print("Game Over!")
play()
again = "maybe"
while again != "no":
again = raw_input("Do you want to play again? yes OR no? \n")
if again == "yes":
print "Great!"
play()
print "Okay thanks for playing!"
You need to move where you set guess = True
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
guess = True
if inp == x:
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"
Before you were only ending on the condition where the last guess was correct. You should be ending whether the guess was correct or not.
You need to make guess equal to True in your second else or else it will never satisfy stop condition for while loop. Do you understand?
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
elif tries+1 != 3:
print "Wrong guess! Try again."
print "Your remaining tries are",(3-(tries+1))
tries = tries + 1
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
guess= True
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"
guess = False
tries = 0
EDIT: I think this does the trick using your code.
You need to update tries. Additionally you need to break out of your loop even if guess != True
import random
x =round(random.random()*5)
guess = False
tries = 0
while guess != True:
if tries<=3:
inp = input("Guess the number: ")
if tries<3:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! Try again."
tries = tries + 1
print "Your remaining tries are",(3-tries)
if tries>2:
if inp == x:
guess = True
print "Correct! You won"
else:
print "Wrong guess! You are out of tries"
print "Game Over!"
break
tries += 1
again = raw_input("Do you want to play again? ")
if again == "no":
print "Okay thanks for playing!"
elif again =="yes":
print "Great!"

Can't fix "TypeError: 'str' object is not callable" in Python

I need help fixing the error. Here is my code:
import random
def game():
capitals={"England":"London","France":"Paris","Belgiom":"Brussels",\
"Canada":"Ottawa","China":"Beijing","Cyprus":"Nicosia",\
"Cuba":"Havana","Egypt":"Cairo","Greece":"Athens",\
"Ireland":"Dublin","Italy":"Rome","a":"A","B":"B"}
wrong=[]
right=[]
incorrect_answers = False
while len(capitals)>0:
pick = random.choice(list(capitals.keys()))
correct_answer = capitals.get(pick)
print ("What is the capital city of" + pick + "?")
answer = input("Your answer: ")
if answer.lower() == correct_answer.lower():
print ("That's Correct!\n")
del capitals[pick]
right.append(pick)
else:
print ("That's Incorrect.\n")
print ("The correct answer is" + correct_answer + "\n")
wrong.append(pick)
incorrect_answers = True
del capitals[pick]
print ("You got ",len(right), "/", len(wrong))
top = len(right)
bottom = len(wrong)
perc = float((top / bottom) * 100)
print(perc)
if incorrect_answers:
print ("Here are the ones that you may want to brush up on:\n")
for each in wrong:
print (each)
else:
print ("Perfect!")
def help():
print("do you neeeded efhdufghaf dfgjn")
while True:
input = input("what do you want to do? help or play?")
if input == "help":
help()
break
if input == "play":
print("you want to play")
game()
break
You shouldn't do this
input = input("what do you want to do? help or play?")
You are shadowing the function input with your variable. Change the name of your variable to something else.

Categories