Reputation: 21
I made a simple program where a user guesses a randomly generated computer number. To test if the program is working, I changed the generated computer value to 5. However, when I "guess" 5, I am somehow still incorrect.
Can someone please tell me what is wrong with this code?
I tried messing about with returning variables but I don't understand how the return command works so I was not successful.
def computer_roll():
global comproll
comproll = random.randint(1,3)
# comproll = 5
user_guess()
def user_guess():
global user
user = input("Input a number: ")
guess_evaluation()
def guess_evaluation():
if user != comproll:
print("You are incorrect.")
again = input("Would you like to try again? ")
if again in("y"):
user_guess()
elif again in ("n"):
print("Thanks for playing.")
elif user == comproll:
print("You are correct.")
again = input("Would you like to play again? ")
if again in("y"):
user_guess()
elif again in ("n"):
print("Thanks for playing.")
computer_roll() # Start```
# Expected Results:
# When I enter 5 it should say "You are correct." and then "Would you like to play again?"
# Actual Results:
# When I enter 5 it says "You are incorrect" and then "Would you like to play again?"
Upvotes: 2
Views: 54
Reputation: 1338
You are comparing integer with string which is why it will never be correct.
Try, user = int(input("Input a number: "))
On a sidenote, you really shouldn't be using global variables. Learn to use returns especially since you are using functions, otherwise there is no point using functions at all.
Below is a sample code:
import numpy as np
import random
def computer_roll():
return random.randint(4,6)
def user_guess():
return int(input("Input a number: "))
def guess_evaluation():
if user_guess() != computer_roll():
print("You are incorrect.")
else:
print("You are correct.")
again = input("Would you like to play again? ")
if again in ("n"):
print("Thanks for playing.")
else:
guess_evaluation()
guess_evaluation()
Upvotes: 1
Reputation: 706
user input curently a string when comproll is a int. You can change this with:
user = int(input("Input a number: "))
Upvotes: 0
Reputation: 1366
For me it works, except for the syntax error at the input field:
def guess_evaluation():
if user != comproll:
print("You are incorrect.")
again = input("Would you like to try again? ")
if again in("y"): # syntax error here, enter space between "in" and "('y')".
user_guess()
elif again in ("n"):
print("Thanks for playing.")
Upvotes: 0