I'm very new to python (~1 wk). I got this error when trying to run this code, intended to be a simple game where you guess heads or tails and it keeps track of your score. Is there any way I can avoid this error? I get the error for the "attempts" variable when I run attempts += 1, but I assume I'd get it for "score" too when I do the same.
import random
coin = ['heads', 'tails']
score = 0
attempts = 0
def coin_flip():
print("Heads or tails?")
guess = input()
result = random.choice(coin)
print("Your guess: " + guess)
print("Result: " + result)
attempts += 1
if result == guess:
print('You guessed correctly!')
score += 1
else:
print('Your guess was incorrect.')
percentCorrect = str((score / attempts) * 100) + '%'
print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.')
print("Accuracy: " + percentCorrect)
print('Do you want to play again?')
if input() == 'y' or 'yes':
return coin_flip()
else:
quit()
coin_flip()
import random
coin = ['heads', 'tails']
score = 0
attempts = 0
def coin_flip():
global attempts
global score
print("Heads or tails?")
guess = input()
result = random.choice(coin)
print("Your guess: " + guess)
print("Result: " + result)
attempts += 1
if result == guess:
print('You guessed correctly!')
score += 1
else:
print('Your guess was incorrect.')
percentCorrect = str((score / attempts) * 100) + '%'
print("You have " + str(score) + " correct guesses in " + str(attempts) + ' attempts.')
print("Accuracy: " + percentCorrect)
print('Do you want to play again?')
if input() == 'y' or 'yes':
return coin_flip()
else:
quit()
coin_flip()
What was missing:
global attempts
global score
This is an issue with scoping. Either put the word global in front of attemps and score, or create a class (which would not be ideal for what I assume you're doing).
Related
I'm very new to programming and am starting off with python. I was tasked to create a random number guessing game. The idea is to have the computer guesses the user's input number. Though I'm having a bit of trouble getting the program to recognize that it has found the number. Here's my code and if you can help that'd be great! The program right now is only printing random numbers and won't stop even if the right number is printed that is the problem
import random
tries = 1
guessNum = random.randint(1, 100)
realNum = int(input("Input a number from 1 to 100 for the computer to guess: "))
print("Is the number " + str(guessNum) + "?")
answer = input("Type yes, or no: ")
answerLower = answer.lower()
if answerLower == 'yes':
if guessNum == realNum:
print("Seems like I got it in " + str(tries) + " try!")
else:
print("Wait I got it wrong though, I guessed " + str(guessNum) + " and your number was " + str(realNum) + ", so that means I'm acutally wrong." )
else:
print("Is the number higher or lower than " + str(guessNum))
lowOr = input("Type in lower or higher: ")
lowOrlower = lowOr.lower()
import random
guessNum2 = random.randint(guessNum, 100)
import random
guessNum3 = random.randint(1, guessNum)
while realNum != guessNum2 or guessNum3:
if lowOr == 'higher':
tries += 1
import random
guessNum2 = random.randint(guessNum, 100)
print(str(guessNum2))
input()
else:
tries += 1
import random
guessNum3 = random.randint(1, guessNum)
print(str(guessNum3))
input()
print("I got it!")
input()
How about something along the lines of:
import random
realnum = int(input('PICK PROMPT\n'))
narrowguess = random.randint(1,100)
if narrowguess == realnum:
print('CORRECT')
exit(1)
print(narrowguess)
highorlow = input('Higher or Lower Prompt\n')
if highorlow == 'higher':
while True:
try:
guess = random.randint(narrowguess,100)
print(guess)
while realnum != guess:
guess = random.randint(narrowguess,100)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
elif highorlow == 'lower':
while True:
try:
guess = random.randint(1,narrowguess)
print(guess)
while realnum != guess:
guess = random.randint(1,narrowguess)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
This code is just a skeleton, add all of your details to it however you like.
This is my current HiLo game, I want to integrate a menu with 4 options, 1. read csv file 2. play game 3. show results and 4. exit, any help is appreciated.
Because I don't know where to start.
import\
random
n = random.randint(1,20)
print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")`enter code here`
You could place your game loop inside a menu loop, and all the code for csv file, etc. inside these loops...
However, it is surely preferable to learn a little bit about functions, in order to organize your code a little bit:
Here, I placed your game loop inside a function, and also created functions for the other options; right now, they only print what they should be doing, but as you add features, you will fill this with code.
import random
def read_csv():
print('reading csv')
def show_results():
print('showing results')
def play_game():
n = random.randint(1,20)
# print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")
while True:
choice = int(input("1. read csv file 2. play game 3. show results and 4. exit"))
if choice == 4:
break
elif choice == 2:
play_game()
elif choice == 3:
show_results()
elif choice == 1:
read_csv()
import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
return
play()
From the information available for now, I would say that this is because you did not assign any value for
questions
variable
To solve this, simply add
questions = 10 # or other value you may want
at the very start of the play() function
You need to initialize questions variable to 0 before while loop and also initialize counters variable to 0 and return statement should be outside while loop.
Below is the corrected code
import random
import time
print ("Welcome to the Game")
print ("You must complete the next 10 Multiplication Questions to be truly ready for the challenges of life")
print ("")
choice = input("Are you ready? Y / N: ")
print("")
def play():
#initialization
questions,counter =0,0
while questions != 10:
num1 = random.randrange(9,17)
num2 = random.randrange(6,17)
print("What does " + str(num1) + " x " + str(num2) + " = ")
guess1 = input("Your guess?: ")
answer1 = (num1*num2)
if int(guess1) == answer1:
print("Correct")
time.sleep(1)
counter = counter + 1
questions = questions + 1
print("")
else:
print("Your answer was Wrong")
time.sleep(1)
print("The real answer was")
time.sleep(1)
print (str(answer1))
questions = questions + 1
print("")
if questions == 10:
print ("You got " + str(counter) + " out of 10")
# return outside while loop
return
play()
An example for you:
#!/usr/bin/env python3.6
import time
from random import randrange
def play():
counter = 0
for i in range(10):
num1 = randrange(9, 17)
num2 = randrange(6, 17)
print(f"What does {num1} x {num2} = ")
guess = input("Your guess?: ")
answer = str(num1 * num2)
if guess == answer:
print("Correct\n")
counter += 1
else:
print("Your answer was Wrong")
print(f"The real answer was {answer}\n")
time.sleep(0.5)
print("You got " + str(counter) + " out of 10")
def main():
print(
"Welcome to the Game\n"
"You must complete the next 10 Multiplication Questions "
"to be truly ready for the challenges of life\n"
)
choice = input("Are you ready? Y / N: ")
if choice.upper() == "N":
return
print()
play()
if __name__ == "__main__":
main()
I am new and a beginner. I need help condensing play_game() below. I need to get it to 18 lines. I would like to call the if and else function from within this code to shorten it by that many lines.
def play_game(): # def the plag game function which is the main control of the game
level = get_level()
quiz = game_data[level]['quiz']
print quiz
answers_list = game_data[level]['answers']
blanks_index = 0
answers_index = 0
guesses = 3
while blanks_index < len(blanks):
user_answer = raw_input("So what's your answer to question " + blanks[blanks_index] + "? : ") #while, if and else to increment the blanks, answers, and guesses
if check_answer(user_answer,answers_list,answers_index) == "right_answer":
print "\n Lucky Guess!\n"
quiz = quiz.replace(blanks[blanks_index], user_answer.upper()) #prints appropriate responses
blanks_index += 1
answers_index += 1
guesses = 3
print quiz
if blanks_index == len(blanks):
return you_win()
else:
guesses -= 1
if guesses == 0:
return you_lost()
break
print "Incorrect. Try again only " + str (guesses) + " guesses left!"
play_game()
Here's the play_game() subroutine reduced to 18 lines of code:
def play_game():
data = game_data[get_level()]
quiz, answers = data['quiz'], data['answers']
index, guesses = 0, 3
print quiz
while index < len(blanks):
user_answer = raw_input("So what's your answer to question " + blanks[index] + "? : ")
if check_answer(user_answer, answers, index) == "right_answer":
quiz = quiz.replace(blanks[index], user_answer.upper())
print "\nLucky Guess!\n\n" + quiz
guesses = 3
index += 1
else:
guesses -= 1
if guesses == 0:
return you_lost()
print "Incorrect. Try again only " + str(guesses) + " guesses left!"
return you_win()
Tricky to do without being able to actually run the code. Mostly just code cleanup.
Probably obvious, but for some reason, this code:
import random
import time
def tables():
global tablesUsed
tablesUsed = [int(x) for x in input("Please choose which multiplication tables you wish\nto practice, then type them like this: 2 5 10.\n").split()]
return tablesUsed
def timer():
timer = input("Do you wish to play with the timer? (yes or no)\n")
if timer == "yes":
withTimer()
else:
withoutTimer()
def withTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
start = time.time()
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
elapsed = round((time.time() - start), 1)
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
if elapsed < 2:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nThat is a very good time!\nScore: " + score)
else:
print("Congratulations, you got it correct in " + str(elapsed) + " seconds!\nNow work on your time.\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def withoutTimer():
playAgain = "yes"
total = 0
correct = 0
while playAgain == "yes":
total = total + 1
random1 = random.choice(tablesUsed)
random2 = random.randint(1, 12)
realAnswer = random1 * random2
humanAnswer = int(input("What is the answer to this multiplication sum?\n" + str(random1) + " * " + str(random2) + "\n"))
if realAnswer == humanAnswer:
correct = correct + 1
score = str(int(correct / total * 100)) + "%"
print("Congratulations, you got it correct!\nScore: " + score)
else:
score = str(int(correct / total * 100)) + "%"
print("Unforunately, you got this one incorrect, the actual answer was " + str(realAnswer) + ".\nScore: " + score)
playAgain()
def playAgain():
playAgain = input("Do you wish to play again? (yes or no)\n")
if playAgain == "yes":
settings()
else:
print("Thank you for practising your multiplication tables with me. Your final score was " + score + " and your average time was " + averageTime)
def settings():
settings = input("Do you wish to edit settings? (yes or no)\n")
if settings == "yes":
tables()
timer()
tables()
timer()
returns an error saying:
TypeError: 'str' object is not callable, line 66, line 10, line 35
Please could someone help and tell me what I'm doing wrong?
I gather that it's probably to do with defining functions incorrectly, but I can't find anything on that solves my problem.
You defined playAgain both as a function and a local variable in the withTimer function:
def withTimer():
playAgain = "yes"
# ...
while playAgain == "yes":
# ....
playAgain() # this is now a string, not the function
Don't do that, use meaningful names that don't shadow your function names.