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()
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.
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).
So I'm new to programming, and made a little game, with help from google. The first code of the game works, but I want to ask how I would add a function that asks if I want to play again, and if I say "Yes" for example, then it plays the game again, and returns to "I am thinking of a number....." or if I say "No" then it exits...
The second code is the code that doesn't work, where I tried adding a function for the game to play again, and suggested I add another while loop, but not too sure where to put it. Currently with the second code, when I guess the correct number, it just closes and doesn't ask for input.
I apologise for the dumb question, but I can't figure it out.
import random
guessesTaken = 0
print("Hello, I am your computer. What is your name?")
myName = input()
number = random.randint(1, 20)
print("\nHello " + myName + ", and welcome to the game! Do you want to play?")
playGame = input()
while playGame == "Yes":
print("I am thinking of a number between 1 and 20, can you guess my number?\n")
while guessesTaken < 6:
print("Take a guess. ")
guess = input()
guess = int(guess)
guessesTaken += 1
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Well done " + myName + "! You guessed my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Sorry " + myName + ", but you couldn't figure it out, my number was " + number)
break
while playGame == "No":
print("Then you opened this for nothing, goodbye")
break
input()
import random
guessesTaken = 0
print("Hello, I am your computer. What is your name?")
myName = input()
number = random.randint(1, 20)
print("\nHello " + myName + ", and welcome to the game! Do you want to play?")
playGame = input()
while playGame == "Yes" or playAgain == "Yes":
print("I am thinking of a number between 1 and 20, can you guess my number?\n")
while guessesTaken < 6:
print("Take a guess. ")
guess = input()
guess = int(guess)
guessesTaken += 1
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Well done " + myName + "! You guessed my number in " + guessesTaken + " guesses! \nWould you like to play again?")
playAgain = input()
if guess != number:
number = str(number)
print("Sorry " + myName + ", but you couldn't figure it out, my number was " + number + "\nWould you like to play again?")
playAgain = input()
break
while playAgain == "No":
print("Thank you for playing, goodbye")
break
while playGame == "No":
print("Then you opened this for nothing, goodbye")
break
input()
You can add the playing features as a function and call that in a while loop.
import random
def PlayGame():
guessesTaken = 0
print("Hello, I am your computer. What is your name?")
myName = input()
number = random.randint(1, 20)
print("\nHello " + myName + ", and welcome to the game!")
print("I am thinking of a number between 1 and 20, can you guess my number?\n")
while guessesTaken < 6:
print("Take a guess. ")
guess = input()
guess = int(guess)
guessesTaken += 1
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Well done " + myName + "! You guessed my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Sorry " + myName + ", but you couldn't figure it out, my number was " + number)
print("Would you like to play again? Enter 1 for Yes and 2 for No")
playAgain = input()
if playAgain == 1:
return True
else:
return False
playing = True
while playing == True:
playing = PlayGame()
can't repeat the loop after the "else statement" (googled it and did'nt find a solid resault)
example:
I'm trying to make a dice game
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
user_input = input("Roll the Dice? [Y/N] ")
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while user_input:
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
else:
print('Invalid')
continue
user_input = input("Roll again? [Y/N] ")
print(user_input)
Your while loop needs a condition. While x == 1: or while 1:
If you use x = 1. When the value of x is other than 1, the while loop will stop or when a break is used.
If you use while 1, it will continue to loop until you use break.
Another point, you want to have the user_input within the while loop so that it can ask the user if they would like to roll again.
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
x = 1
while x == 1:
user_input = input("Roll the Dice? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
Answer: As noted by Klaus, removing the continue in the while user_input will fix the loop, to only re-roll when the user responds 'y'
Changing print(dice_roll()) to just dice_roll() (function call without printing it's return value) will keep this program from printing 'None' after dice rolls.
If you want it to print the return, you can change the
print(" The sum is", dices_sum) to
return(" The sum is", dices_sum)
try this
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while 1:
user_input = input("Roll? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input == 'y':
dice_roll()
elif user_input == 'N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
There are two problems that you need to fix.
Since your function dice_roll ends without return syntax, python interpreter will add return None at the end of the function. I change 'print(dice_roll())' to 'dice_roll()'.
In your while loop, if elif else syntax has covered all situations, the code will never go to
user_input = input("Roll again? [Y/N] ")
print(user_input)
So, I just put these two lines in front of 'if elif else'. and remove ' again'.
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.