Python random maths equation does not work - python

It doesn't tell you if the question is correct or not (when it should) and it doesn't do what it is supposed to when all of the questions have been asked. It should say this at the end: "You scored " + str(correctQuestions) + "/10 questions."
Here is the code:
import random
name = input("What is your name: ")
finish = False
questionNumber = 0
correctQuestions = 0
while finish == False:
op = ['+','-','*']
choice = random.choice(op)
if questionNumber < 10 and questionNumber >= 0:
number1 = random.randrange(1,10)
number2 = random.randrange(1,10)
print((number1),(choice),(number2))
answer=int(input("What is the answer?"))
questionNumber = questionNumber + 1
if choice==("+"):
realAnswer = number1+number2
elif answer==realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
if choice==("*"):
realAnswer = number1*number2
elif answer==realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
if choice==("-"):
realAnswer = number1-number2
elif answer==realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
if finish == True:
print("You scored " + str(correctQuestions) + "/10 questions.")

As this looks like a homework exercise i will not solve it for you take some time and think about it. However here are some hints:
The variable finish is always False, it never gets updated, so its no wonder the game is never finished. Do something about that.
Second at line if choice==("+"): it can be possible that the variable choice does not exist (nor number1 and number2). Think about what you put under the while loop and what you don't.
Also there is a variable realAnswer in an elif statement while you did not declared it before. As the variable does not even exist, it will give you a NameError if it gets evaluated.

Let's say choice is *. Python gets to if choice==("+"):. The result: False, so it checks the elif: elif answer==realAnswer: At this point realAnswer has not yet been defined. You define realAnswer in the if block, but the if block did not execute. You need to take out the elif and else blocks from each choice, and instead put them at the end:
if answer == realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
Also, you never define finish as anything but False. You use if questionNumber < 10 and questionNumber >= 0:, but you don't say what to do if questionNumber is not between 0 and 10. You need an else block that will break out of the loop.

Related

Global variable not updated in while loop - Python

I'm new to Python but I can't seem to figure out why the declared "attempt" variable is not decremented if an incorrect attempt is submitted.
My thoughts are once a guess is submitted if it's not equal to the correctAnswer then the variable attempts should be decremeted by 1 so the print statement would say "You have 2 attempts left.
# You have 3 attempts to guess the correct word. If you don't you lose!
attempts = 3
correctAnswer = 32
while attempts != 0:
guess = input("How old is Dad?")
if guess != correctAnswer:
attempts = attempts - 1 #This should decrement if the attempt is incorrect
print("You have " + str(attempts) + " left")
else:
print("You lose!")
print("You are right!")
The variable is being updated but you have a problem with the input comparison and your print logic is kinda backwards, making the output look strange. The input function returns strings, and strings are never equal to integers. You need to convert the string to an integer. That will fail if you are given bad input so you can either check the value before you attempt a conversion or use a try/except block to catch errors.
You could pull the final success/failure condition out of the loop:
attempts = 3
correctAnswer = 32
while attempts != 0:
guess_str = input("How old is Dad?")
if not guess_str.isdigit():
attempts = attempts - 1
print("Please enter a number, yYou have " + str(attempts) + " left")
continue
guess = int(guess_str)
if guess != correctAnswer:
attempts = attempts - 1 #This should decrement if the attempt is incorrect
print("You have " + str(attempts) + " left")
else:
break
if attempts:
print("You are right!")
else:
print("You lose!")
But python while loops have an else clause that only runs if the while is not terminated with a break. Add a break to the success path and it will catch the fail path.
attempts = 3
correctAnswer = 32
while attempts != 0:
guess_str = input("How old is Dad?")
if not guess_str.isdigit():
attempts = attempts - 1
print("Please enter a number, yYou have " + str(attempts) + " left")
continue
guess = int(guess_str)
if guess != correctAnswer:
attempts = attempts - 1
print("You have " + str(attempts) + " left")
else:
print("You are right!")
break
else:
print("You lose!")

Python guessing game code keeps crashing after 1 guess. How would i fix this?

My code keeps crashing after I put in the 1st guess I make. I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it. When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end? Any help would be appreciated.
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input != target on the first iteration of the loop, time_uin is referenced before assignment. Hence the error:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input == target.
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.

Game of Chance in Python 3.x?

I have this problem in my python code which is a coinflip game, the problem is that when It asks, "Heads or Tails?" and I just say 1 or Heads(same for 2 and Tails) without quotation marks and with quotation marks, it does not give me an answer that I am looking for.
I've Tried using quotation marks in my answer which didn't seem to work either.
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails?")
coinnum = random.randint(1, 2)
if coinnum == 1:
return 1
elif coinnum == 2:
return 2
win = bet*2
if choice == "Heads" or "1":
return 1
elif choice == "Tails" or "2":
return 2
if choice == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
elif choice != coinnum:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
The expected output was either "Well done! You have won 200 Dollars!" or "Sorry, you lost 100 Dollars!"
The first thing to note here is that your usage of return seems to be wrong. Please look up tutorials about how to write a function and how to use return.
I think this is what you were trying to do:
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails? ")
coinnum = random.randint(1, 2)
win = bet*2
if choice == "Heads" or choice == "1":
choicenum = 1
elif choice == "Tails" or choice == "2":
choicenum = 2
else:
raise ValueError("Invalid choice: " + choice)
if choicenum == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
else:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
Now, lets go through the mistakes I found in your code:
return was totally out of place, I wasn't sure what you were intending here.
if choice == "Heads" or "1" is invalid, "1" always evaluates to true. Correct is: if choice == "Heads" or choice == "1":
elif choice != coinnum: is unnecessary, if it doesn't run into if choice == coinnum: a simple else: would suffice.

Breaking a loop for basic python

I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...

How would I assign the list of operators so that the random numbers are worked out to tell the user if they're correct or not?

How would I assign the list of operators so that the random numbers are worked out to tell the user if they're correct or not?
# Controlled Assessment - Basic Times Table Test
import random
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is' ,Number1,Operator,Number2)
Answer= input ("Please Type Your Answer: ")
realanswer = (Number1,Operator,Number2)
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The code that needs to assign to the list of operators is...
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
It should work out the answer to each question using the function I'm telling the program that if the operator from the operator list is * to work out Number1*Number2
The current output for telling them if the answer is correct or not prints
Your answer is incorrect, the correct answer is Number1*Number2.
when if the question is what is 10*3 it should be printing
Your answer is incorrect, the correct answer is 30.
Now that I have this code...
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The program always prints that the question is incorrect even with the correct answer inputted, it will then print the correct answer, how would I make it so that It would tell them if it's correct too?
The operator module implements basic operations as functions. Define a dict that maps operator symbols such as "+" to the operator function then use that map to do the calculation.
import random
import operator
op_map = {'+':operator.add, '-':operator.sub, '*':operator.mul}
op_list = list(op_map.keys())
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
Operator =random.choice(op_list)
print ('what is' ,Number1,Operator,Number2)
while True:
try:
Answer= int(input("Please Type Your Answer: "))
break
except ValueError:
print("Must be an integer... try again...")
realanswer = op_map[Operator](Number1, Number2)
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
To perform multiple check like this you can use if, elif statements:
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
For your reference: Python Docs
...
def realanswer(Num1, Op, Num2):
return {
'+': Num1 + Num2,
'-': Num1 - Num2,
'*': Num1 * Num2,
}[Op]
for q in range(2):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is',Number1,Operator,Number2)
userInput = input("Please Type Your Answer: ")
Answer = 0
try:
Answer = int(userInput)
except ValueError:
print("Input not convertible to int!")
rAnswer = realanswer(Number1,Operator,Number2)
if Answer == rAnswer:
print("Correct!")
else:
print("Incorrect...")

Categories

Resources