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.
Related
Been looking online for some answers, however it's still unclear to me why the 'health' var is not updated when calling the getDamage() func
I'm on my first few miles learning python
health = 200.0
maxHealth = 200
healthDashes = 20
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
gameOver = False
def updateGame():
print(chr(27) + "[2J")
print (30 * '-')
print("")
print(" |" + healthDisplay + remainingDisplay + "|")
print(" health " + percent)
print ("")
print (30 * '-')
print("")
def getDamage():
global health
health = 10
while gameOver == False:
answer = raw_input("> ").lower()
if answer == "help":
print("")
print(" you can use the following commands: h, i, q, d")
print("")
elif answer == "q":
print("\n")
print("Game Over")
print("")
break
elif answer == "h":
updateGame()
elif answer == "d":
getDamage()
else:
print(""" not a valid command, see "help" """)
Is there anything I can do to properly update the "health" var and disply a reduced health the next time I call the getDamage() func?
Basically what I'm trying to achieve is a text-based game to run in a while loop and have different functions to update a primary function (updateGame) that display relevant info about the player's state like health, inventory items.
The logic I'm trying to implement is:
have getDamage() reduce the health var and then display the newly change variable with updateGame()
Many thanks
health will change to 10 when you call getDamage() but healthDisplay, remainingDisplay and percent are set at the first of script and won't change everytime that healt global variable is changed. so you must change them in updateGame() function everytime it's called. Also i guess health = 10 must change to health -= 10!
health = 200.0
maxHealth = 200
healthDashes = 20
gameOver = False
def updateGame():
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
print(chr(27) + "[2J")
print (30 * '-')
print("")
print(" |" + healthDisplay + remainingDisplay + "|")
print(" health " + percent)
print ("")
print (30 * '-')
print("")
def getDamage():
global health
health -= 10
while gameOver == False:
answer = input("> ").lower()
if answer == "help":
print("")
print(" you can use the following commands: h, i, q, d")
print("")
elif answer == "q":
print("\n")
print("Game Over")
print("")
break
elif answer == "h":
updateGame()
elif answer == "d":
getDamage()
else:
print(""" not a valid command, see "help" """)
Inside the updateGame function, you never make reference to the global variable health. If you want health to change inside the function, you will need to access it.
This means you should have something like:
def updateGame():
global health
health = updatedHEALTH
...
Then it should change each time you call the function
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).
I'm making a simple program (I am a beginner at python) where I fight a monster with random assigned values. I used 2 lists with 4 variables each depicting hp atk def and spd. They get assigned a random number of 10 to 15 and get multiplied by 2. I don't really know what I am doing wrong here.
import random
monsters = ["slime","goblin","troll","dryad","bard","clown"]
hp,atk,dfn,spd = 0,0,0,0
mhp,matk,mdfn,mspd = 0,0,0,0
stats = [hp,atk,dfn,spd]
mstats = [hp,atk,dfn,spd]
damage = 0
defend = 0
action = "none"
name = input()
print("Your name is " + name + ", time to battle!")
for x in stats:
stats[x] = random.randint(10,15) * 2
print("Your stats(hp/a/d/s): " + str(stats[x]))
for y in mstats:
mstats[y] = random.randint(10,15) * 2
print("Monster stats(hp/a/d/s): " + str(mstats[y]))
while stats[hp] > 0 or mstats[hp] > 0:
print("What will you do? 1 for attack, 2 for defend, others to give up")
action = input()
if action == "1":
damage = stats[atk] / 2 + random.randint(1,5)
mstats[hp] = mstats[hp] - damage
print("You slash the monster for " + str(damage) + " damage!" )
print("Monster HP: " + str(mstats[hp]))
damage = mstats[atk] / 2
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action == "2":
damage = mstats[atk] / 2 - random.randint(3,5)
if damage > 0:
stats[hp] = stats[hp] - damage
print("The monster slashes you for " + str(damage) + " damage!")
print("Your HP: " + str(stats[hp]))
if action != "1" and action != "2":
stats[hp] = 0
if stats[hp] < 0 or stats[hp] == 0:
print("You lose!")
if mstats[hp] < 0:
print("You win!")
Hopefully this code isn't a mess, I thank you all in advance if extra corrections can be given.
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'm creating program which will teach my little brother math. But for example, when program is saying 2 + 2, and I enter 4 it's saying "Incorrect!". What am I doing wrong?
import random
import math
def addition():
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")#this is the line with problem
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()
result is an integer (e.g., 4), and the inputed guess is a string (e.g., '4'). You need to convert them to the same type in order to compare them. E.g.:
result = str(num1 + num2)
Wrap the answer to int
guess = int(input(str(num1) + " + " + str(num2) + " = "))
typecast the input to int:
import random
import math
def addition():
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")
guess = int(guess) #input is string and it must be typecast to int
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()