Checking if two variables are equal - python

In my code I'm making a basic multiplying game.
But in my game,
When you get the answer right, it says you got it wrong
Here's my whole code:
import random
score = 0
while True:
num1 = random.choice(range(1,12))
num2 = random.choice(range(1,12))
answer = num1 * num2
a = input("Solve for " + str(num1) + "x" + str(num2))
if a == answer:
print("congrats you got it right")
score += 1
else:
print("Wrong sorry play again")
print("Score was: " + str(score))
break
When I get the right answer I get
Solve for 7x10 70
Wrong sorry play again
Score was: 0

Other languages might let you get away with this, but Python is strongly typed. The input function gets a string, not a number. Numbers can't be equal to strings. Either convert the number to a string or the string to a number before you compare them. You can use str or int to convert.

Function input returns what was typed as a string... in order to compare it with the answer, you need to either convert it to int:
if int(a) == answer:
or the other way around (convert answer to str):
if a == str(answer):
The first one may raise an exception if a is not parseable to an int.
Here the docs.
PS: I really wonder how ur random library picked a 1070 sampling from 0 to 11...

Or use int(input()):
import random
score = 0
while True:
num1 = random.choice(range(1,12))
num2 = random.choice(range(1,12))
answer = num1 * num2
a = int(input("Solve for " + str(num1) + "x" + str(num2)))
if a == answer:
print("congrats you got it right")
score += 1
else:
print("Wrong sorry play again")
print("Score was: " + str(score))
break

Related

Trouble with an assignment

I am doing an assignment for school where I need to make a list and assign 4 random integers to the list between 1 and 9. Then, I need to prompt the user for what their guess is for each value. If they get any of the numbers right, I need to say how many, but I've been working on this for like 3 hours and I'm getting nowhere. Currently, all I have is a massive useless nested if/elif statements.
This is the assignment prompt:
Program Specifications:
Computer should generate 4 random numbers from 1 - 9 as the "Secret Code".
User should be prompted for their guess of those four numbers.
After they provide their full guess, the user is told how many are correct.
As long as the user does not get all four correct, they keep getting asked for their guess.
After the user finally gets all of them correct (yes - all four), they are congratulated and then told how many tries it took them.
Technical Requirements:
Use at least one list
Use at least one function with parameters
I'm so confused and I don't know where to start. Here is my current code:
import random
count = 0
guess1 = 1
guess2 = 1
guess3 = 1
guess4 = 1
def getGuess(count,guess1,guess2,guess3,guess4):
while True:
guess1 = input("What is your guess for the first number? ")
guess2 = input("What is your guess for the second number? ")
guess3 = input("What is your guess for the third number? ")
guess4 = input("What is your guess for the fourth number? ")
if str(guess1) == numbers[0] and str(guess2) == numbers[1] and str(guess3) == numbers[2] and str(guess4) == numbers[3]:
print("Your first, second, third, and fourth numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1] and guess3 == numbers[2]:
print("Your first, second, and third numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1]:
print("Your first and second number are correct!")
elif guess1 == numbers[0]:
print("Your first number is correct!")
elif guess2 == numbers[1]:
print("Your second number is correct!")
elif guess2 == numbers[1] and guess3 == numbers[2]:
print("Your second and third numbers are correct!")
elif guess2 == numbers[1] and guess3 == numbers[2] and guess4 == numbers[3]:
print("Your second, third, and fourth numbers are correct!")
elif guess3 == numbers[2]:
print("Your third number is correct!")
elif guess3 == numbers[2] and guess4 == numbers[3]:
print("Your third and fourth numbers are correct!")
elif guess4 == numbers[3]:
print("Your fourth number is correct!")
else:
print("None of your numbers are correct. Try again.")
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
print(numbers)
getGuess(count,guess1,guess2,guess3,guess4)
I see your attempt so I'm going to tell you the problems, as comments said:
Logic flow: your if else statement are serving 4 numbers, what if 10, 100 numbers? It should be generic
You are comparing string with integer, should cast it
Should package your variables inside your function. Which is very ambiguous of guess1 = 1, guess1 function variable, guess1 from input,...
Init random numbers
import random
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
getGuess function, which is getting guess numbers from input string, then split it and convert to int.
def getGuess(numbers):
retryCount = 0
while True:
# You can put try catch here for number validation
guessNums = [int(x) for x in input("Numbers: ").split()]
# To make sure your input must be the same length
if len(guessNums) != len(numbers):
print('Not available numbers')
continue
# Here we just check for incorrect, once it's met, the for loop will be broken and go to the next while loop
isIncorrect = False
for index, num in enumerate(numbers):
if num != guessNums[index]:
isIncorrect = True
retryCount += 1
print('Order of ' + str(index + 1) + ' is incorrect')
break
# When every number is equal, not incorrect occured, return retry count
if isIncorrect == False:
return retryCount
Using:
print('Your retry count: ' + str(getGuess(numbers)))
You can optimize many of the parts of your code.
Assumption: You know how to use lists as you are already using numbers as a list. I am staying away from dictionary. Not sure if you know its use. Also assume you understand list comprehension. If you dont, see this link on list comprehension.
Now let's look at your code. Here are a few things to consider:
You don't need 4 variables to store the 4 input values. You can use a list and store all 4 of them there.
As many have already suggested, you should convert the input value into an integer. When you convert string to integer, there is a potential that the string is not an integer. This can result in code getting broken. So use Try Except to catch the error while converting to int
Your random.randrange(1,9) will create integers. So you dont have to explicitly convert them back to integer.
You have 4 inputs and 4 values to compare. You can map each value to the position and compare. That will reduce the complexity. For the ones that are successful, keep a tab of it. Then print the ones that matched. Again, this can be done using a list or dictionary.
With all that to consider, I have re-written your code as follows. See if this helps you with the solution.
import random
nums = [random.randrange(1,9) for _ in range(4)]
def getGuess():
g = ['first','second','third','fourth']
i = 0
gx = []
while i<4:
try:
x = int(input(f"What is your guess for the {g[i]} number? :"))
gx.append(x)
i+=1
except:
print ('Not numeric, please re-enter')
gwords = [g[i] for i in range(4) if nums[i] == gx[i]]
if gwords:
if len(gwords) == 1:
resp = "Your " + gwords[0] + ' number is correct!'
else:
resp = "Your " + ', '.join(gwords[:-1]) + ' and ' + gwords[-1] + ' numbers are correct!'
print (resp)
else:
print ("None of your numbers are correct. Try again.")
getGuess()
Here's an example run of the above code:
What is your guess for the first number? :1
What is your guess for the second number? :6
What is your guess for the third number? :5
What is your guess for the fourth number? :4
Your second, third and fourth numbers are correct!

Answer appears as a float and I don't know why in python

I am doing a programming project. It gives a user (aimed for primary school students) a randomly generated question. When I do my division code the answer is a real/float variable meaning that unless the user has a .0 at the end of a whole number, their answer is processed as incorrect. My code is:
while True:
num1 = str((random.randint(0,12)))
num2 = str((random.randint(0,12)))
if num1 >= num2:
question = (num1 + " " + "/" + " " + num2)
print(question)
answer = str((int(num1) / int(num2)))
reply = str(input())
if reply == answer:
score = score + 1
print("Correct")
break
else:
print("Incorrect")
print("The answer was", answer)
break
else:
print("")
I understand that sometimes the answer will have a decimal point in it but is there a way of allowing a whole number to not have a .0 at the end. If not then how can I improve the code so I don't get this issue. Any help is appreciated. My python-idle version is 3.8
/ is float division in Python. If you want to get an int with the line answer = str((int(num1) / int(num2))) then you should be using // instead, which is integer division.

What is the Syntax error in this code that detects an even or odd number in python?

Here is the code that the syntax is on:
# Odd or Even?
print('Hello! What is your name?')
PlayerName = input()
print("Hello, " + PlayerName + "! Enter your number and I\'ll tell you if it\'s even or odd!")
PlayerNum = input()
Decimal = PlayerNum % 2
if Decimal == 0.5
print('Your number is odd!')
else
print('Your number is even!')
It gives syntax on line 7 (if Decimal == 0.5). Let me know if there are any other errors. I'm also using python 3. What's the problem?
Thanks
Your code should look like this:
print('Hello! What is your name?')
playerName = input()
print("Hello, " + playerName + "! Enter your number and I\'ll tell you if it\'s even or odd!")
playerNum = int(input())
if playerNum % 2 == 0:
print('Your number is even!')
else:
print('Your number is odd!')
You need to insert a colon after if and else conditions.
The input is read as a string, you need to convert it to int or float
You need to indent your code (I recommend 4 spaces)

Random Maths Program

thanks for taking time to read this.
I have to create a program that generates 10 random maths questions based around =, - and *. I have the program working but everytime I run it after the main program it prints "none" even though that's not in my program.Any help at all would be much appreciated. Thank you.
import random
print ("Welcome")
name=input("What's your name?")
print("Nice to meet you", name, ",you will be given 10 multiplication, addition and subtraction questions.")
Num1 = random.randint(1,12)
Num2 = random.randint(1,12)
sign = random.randint(1,3)
if sign == 1: # If the random number generated is 1
question = Num1 + Num2
rightanswer1 = Num1 + Num2
answer1=input(print("What is", question ,"?"))
if answer1 == rightanswer1:
print("Well Done!")
if answer1 != rightanswer1:
print("Sorry, that's incorrect, the answer was", rightanswer1)
if sign == 2:
question = Num1 - Num2
rightanswer2 = Num1 - Num2
answer2=input(print("What is", Num1, "-", Num2 ,"?"))
if answer2 == rightanswer2:
print("Well done!")
elif answer2 != rightanswer2:
print("Sorry, that's incorrect, the answer was", rightanswer2)
if sign == 3:
question = Num1 * Num2
rightanswer3 = Num1 * Num2
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
if answer3 == rightanswer3:
print("Well done!")
elif answer3 != rightanswer3:
print("Sorry, that's incorrect, the answer was", rightanswer3)`
> Welcome
> What's your name? John
> Nice to meet you John ,you will be given 10 multiplication, addition and subtraction questions.
> What is 12 x 3 ?
> None 36
> Sorry, that's incorrect, the answer was 36
I think you are using python 3. In python 3 input is like raw_input in python 2. So you get the string as input. So convert it into int
var = int(input("Enter a number: "))
So in your code make it as
print("What is", Num1, "x", Num2 ,"?")
answer3 = input()
answer3 = int(answer3)
See this:
whats-the-difference-between-raw-input-and-input-in-python3-x
I'm reluctant to just give you an answer that just does it for you, so instead i'll provide you with a few hints to improve things. (i.e. this isn't an answer, just too large of a comment - and more like a codereview answer)
First off, you use a structure like this:
if x == 1:
#do something
if x == 2:
#do something else
...
In this case, which it makes no difference, it is easier to read if you use the if syntax as intended:
if <condition>:
#do this if the above test is true.
elif <more conditions>:
#do this only if the first test is false and this one is true
elif <more conditions>:
#same as above, except for the second test must be false too
else:
#do this if all the above tests are false
So you could use this something like:
if sign == 1:
...
elif sign == 2:
...
elif sign == 3:
...
else:
# something weird happened...
Which would make that section of the program easier to follow.
The same thing can be done with the if answer1 == rightanswer1: sections;
if answer1 == rightanswer1:
#correct!
else:
#incorrect.
That would be a clearer was to do it. You seem to have used the if...elif style in a couple of them, but not the first one.
Once you have this, it will be a little clearer.
The next way you could improve things is by removing duplicated code. You don't need separate branches for each sign, you can just roll it all into one:
number1 = randint(1,12)
number2 = randint(1,12)
op = randint(1,3)
question_string = "%d %s %d = ?" % (number1, number2, ["+", "-", "*"][op])
result = None
if op == 1:
result = number1 + number2
elif op == 2:
result = number1 - number2
elif op == 3:
result = number1 * number2
This will do most of the logic for you, and generate the strings you want, without duplicating all of the other code.
Small changes like this can make things much more readable.
It's printing None because the print() function returns None and you're passing that value of None from print() as the prompt to your input() functions. Eg,
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
So print("What is", Num1, "x", Num2 ,"?") prints its stuff, and returns None, which then gets printed as the prompt by input().
A simple way to fix this is to just move your print() function calls out of your input() functions.
Eg,
print("What is", Num1, "x", Num2 ,"?")
answer3=input()
However, there's another major problem with your program: the rightanswer variables are ints, but the inputted answers are strings. To compare them properly they need to be the same type. So you should either convert the inputted answers to int, or alternatively, convert the rightanswers to str.
There are two problems with how you use the input function:
You misuse the prompt argument
You forget to convert the result
First, have a better look at the reference of the input function
The prompt argument
input takes a string as argument that will be displayed ("prompted") to the user to indicate that the program is waiting an input. The print function also displays a string to the user, but it doesn't return anything. It does its job and that's all (and in Python a function that returns nothing, returns None). That's what input gets to display, so it displays None. You should use format instead. It will format and return the formatted string that input can display:
answer1_as_str=input("What is {} ?".format(question))))
or
answer2_as_str=input("What is {:d} - {:d} ?".format(Num1, Num2)))
The return value
input returns the user input as a string contrary to python 2 (i.e. exactly as entered). So you have to convert the input to the desired type if you need it. If you type 10 for example, the input will return "10". If you need an int, you have to convert it yourself.
answer1 = int(answer1_as_str)
It looks like you don't really understand how input() works. You might also want to review the different datatypes and conditional statements. Other than that, it was a very good attempt. Here's my solution:
from random import randint
print("Welcome")
name = input("What's your name?\n")
print("Nice to meet you " + name + ", you will be given 10 multiplication, addition and subtraction questions.")
for i in range(10):
print("\nProblem " + str(i+1))
num1 = randint(1,12)
num2 = randint(1,12)
sign = randint(1,3)
if sign == 1:
question = str(num1) + " + " + str(num2)
answer = num1 + num2
elif sign == 2:
question = str(num1) + " - " + str(num2)
answer = num1 - num2
else:
question = str(num1) + " x " + str(num2)
answer = num1 * num2
user_answer = input("What is " + question + "? ")
if user_answer == str(answer):
print("Well done!")
else:
print("Sorry, that's incorrect, the answer was", answer)

How to improve on my Division program? (Easy Python)

I am currently trying to make a division program which asks random division questions. There are 2 things blocking me from doing so: 1)My program thinks that everything divided by something is always 0. e.g. 8 divided by 2 = 0. 2) I need to make division without a floating point, like 144/5. So here it is:
import sys
import random
guessRight=0
guessWrong=0
while True:
num1 = random.randint(0,12) #probably messed up here
num2 = random.randint(12,144) #and here
print "To exit this game type 'exit'"
theyputinstuffhere = raw_input("What is " + str(num2) + " divided by " + str(num1) + "? ") #maybe messed up here
if theyputinstuffhere == "exit":
print "Now exiting game!"
sys.exit()
elif int(theyputinstuffhere) == num1/num2: #maybe messed this whole elif too
print num1/num2
print "Correct!"
guessRight=guessRight+1
print "You have gotten " + str(guessRight) + " answer(s) right and you got " + str(guessWrong) + " wrong"
else:
print "Wrong! The correct answer is: " + str(num1/num2)
guessWrong=guessWrong+1
print "You have gotten " + str(guessRight) + " answer(s) right and you got " + str(guessWrong) + " wrong"
This is what it currently prints:
To exit this game type 'exit'
What is 34 divided by 11? #I type any number (e.g. 3)
Wrong! The correct answer is: 0
You have gotten 0 answer(s) right and you got 1 wrong
If you are asking for num2 divided by num1, then you need to use num2/num1 in your code, not num1/num2. This is also why you are always getting 0, num1 will always be less than num2 so num1/num2 will be 0 when integer division is used (which is the default for dividing ints on Python 2.x).
To avoid questions like 144/5 and eliminate the division by zero issue you can use the following:
num1 = random.randint(1,12)
num2 = random.randint(1,12) * num1

Categories

Resources