I've been having a problem in my multiplication game where else would be displayed even if the answer was correct.
Here is a sample of the code:
for num in range(0,1):
number1 = random.randint(2,5)
number2 = random.randint(2,5)
answer = number1*number2
guess = input("What is %d x %d? " % (number1, number2))
if guess == answer:
print('Correct')
else:
print('Incorrect')
In Python 3.x, Input returns a str, vs. in Python 2.x where it attempted to evaluate the input as python code. And str == int always returns False, and doesn't throw an exception. You'd need to change your code to:
if guess == str(answer):
if you'd like to avoid throwing exceptions if the input isn't actually a number, or
gess = int(input(...))
if you intend to actually use guess as a number later on, but will then have to handle what happens if the user enters not a number.
Related
I'm new in coding or programming so I hope for respect.
How can I create a program that continually accepts input from the user. The input shall be in this format operatornumber like -3
Like
num = 0
while((a := input("Enter operatornumber like -9;")) != "-0"):
if (len(a) >= 2) and (a[0] in "/*-+"):
num = eval(f"{num}{a}")
else:
print("Invalid input, try again.")
print(num)
But how can I make the first input of the user to only use the add (+) or subtract(-) operators but in the next input they can now use the other operators.
Like
Enter operatornumber like -9; +9
Enter operatornumber like -9; -8
Enter operatornumber like -9; -0
1
And how can I combine all the input like
+9-9 is 1?
In the input statement, you're closing the "Enter operator and number like" msg. This is creating more problems after that line, where all green parts are considered as string now. Also, in while statement, "w" should be small letter, python is case sensitive. Try doing this:
Number = input("Enter operator and number like '-9' ")
Operator = ("+","-","/")
while Number == (Operator + Number):
if Number == "-0":
Total = 0
Total += Number
print(f"the result of {num} is {total} ")
You can use double quotes for the text and single quotes for the number, so they don't close each other.
You can get input forever using following code:
while True:
Number = input("Enter operator and number like '-9'")
# Place your next code here.
Here is another answer. We have to take input from user with operator as well, so len(<user_input<) should be >=2. Now, we'll take another variable h in which we'll traverse the string from index 1 to end, which means the operator gets removed and we'll convert it into int. Then we'll put if condition in which we'll check the user_input[0] is +,-,*,/ and then acc to that, we'll update the result. We'll ask the user whether he wants more operations or no, if y, then keep asking, else, break the while loop. Here's my code:
result=0
while True:
a=input("Enter operator and number= ")
if len(a)>=2 and a[0] in ["+","-","*","/"]:
h=int(a[1::])
if a[0]=="+":
result+=h
elif a[0]=="-":
result-=h
elif a[0]=="*":
result*=h
elif a[0]=="/":
result/=h
else:
print("choose only from +-/*")
else:
print("invalid input")
ch=input("Enter more?")
if ch=='n':
break
print(f"The result is {result}")
Check for indentation errors because I've copied and pasted it so it may have indentation errors
Switching from Unity JS to Python for a bit, and some of the finer points elude me as to why this does not work.
My best guess is that the variable guess is actually a string, so string 5 is not the same as integer 5?
Is this what is happening and either way how does one go about fixing this.
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
guess = input("")
if guess == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
Yes, you are absolutely right that "5" is distinct from 5. You can convert 5 into a string by using str(5). An alternative would be to convert "5" into an integer by int("5") but that option can fail, so better handle the exception.
So, the change to your program could be e.g. the following:
if guess == str(a):
instead of:
if guess == a:
Another option would be to convert guess into an integer, as explained in the other answer.
EDIT: This only applies to Python versions 2.x:
However, you're using input(), not raw_input(). input() returns an integer if you type an integer (and fails if you type text that isn't a valid Python expression). I tested your program and it asked What is 4 - 2?; I typed 2 and it sait Correct! so I don't see what is your problem.
Have you noticed that if your program asks What is 9 - 4? you can type 9 - 4 and it says Correct!? That's due to you using input(), not raw_input(). Similarly, if you type e.g. c, your program fails with NameError
I would however use raw_input() and then compare the answer to str(correct_answer)
I am assuming you are using python3.
The only problem with your code is that the value you get from input() is a string and not a integer. So you need to convert that.
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
Now you have the input as a integer and you can compare it to a
Edited Code:
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
# Math Quizzes
import random
import math
import operator
def questions():
# Gets the name of the user
name= ("Alz")## input("What is your name")
for i in range(10):
#Generates the questions
number1 = random.randint(0,100)
number2 = random.randint(1,10)
#Creates a Dictionary containg the Opernads
Operands ={'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
#Creast a list containing a dictionary with the Operands
Ops= random.choice(list(Operands.keys()))
# Makes the Answer variable avialabe to the whole program
global answer
# Gets the answer
answer= Operands.get(Ops)(number1,number2)
# Makes the Sum variable avialbe to the whole program
global Sum
# Ask the user the question
Sum = ('What is {} {} {} {}?'.format(number1,Ops,number2,name))
print (Sum)
global UserAnswer
UserAnswer= input()
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
def score(Sum,answer):
score = 0
for i in range(10):
correct= answer
if UserAnswer == correct:
score +=1
print("You got it right")
else:
return("You got it wrong")
print ("You got",score,"out of 10")
questions()
score(Sum,answer)
When I enter a float number into the console the console prints out this:
What is 95 * 10 Alz?
950
Please enter a correct input
I'm just curious on how I would make the console not print out the message and the proper number.
this is a way to make sure you get something that can be interpreted as a float from the user:
while True:
try:
user_input = float(input('number? '))
break
except ValueError:
print('that was not a float; try again...')
print(user_input)
the idea is to try to cast the string entered by the user to a float and ask again as long as that fails. if it checks out, break from the (infinite) loop.
You could structure the conditional if statement such that it cause number types more than just float
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
Trace through your code to understand why it doesn't work:
UserAnswer= input()
This line offers no prompt to the user. Then it will read characters from standard input until it reaches the end of a line. The characters read are assigned to the variable UserAnswer (as type str).
if UserAnswer == input():
Again offer no prompt to the user before reading input. The new input is compared to the value in UserAnswer (which was just entered on the previous line). If this new input is equal to the previous input then execute the next block.
UserAnswer= float(input())
For a third time in a row, read input without presenting a prompt. Try to parse this third input as a floating point number. An exception will be raised if this new input can not be parsed. If it is parsed it is assigned to UserAnswer.
elif UserAnswer != float() :
This expression is evaluated only when the second input does not equal the first. If this is confusing, then that is because the code is equally confusing (and probably not what you want). The first input (which is a string) is compared to a newly created float object with the default value returned by the float() function.
Since a string is never equal to a float this not-equals test will always be true.
print("Please enter a correct input")
and thus this message is printed.
Change this entire section of code to something like this (but this is only a representative example, you may, in fact, want some different behavior):
while True:
try:
raw_UserAnswer = input("Please enter an answer:")
UserAnswer = float(raw_UserAnswer)
break
except ValueError:
print("Please enter a correct input")
The validation doesnt work. im not sure why, is there a way to validate a string. The questions asked are endless i need 10 questions to be asked
import random
name=(input("Please enter your name"))
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10)
numbers=random.randint(1,10)
arith=random.choice("+" "-" "/")
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
if arith=="-":
print(number,arith,numbers)
answer=number-numbers
if arith=="/":
print(number,arith,numbers)
answer=number/numbers
while True:
try:
usersanswer= int(input())
except ValueError:
print ("That is not a valid answer")
continue
if usersanswer==answer:
print("correct")
break
else:
print("incorrct")
The validation doesnt work. im not sure why, is there a way to validate a string
I've taking silentphoenix's answer and made it somewhat more pythonic and six'ed.
You should almost never use python2's input, because on top of being massive security hole, it sometimes does things that can be...rather unexpected.
import random
import operator # contains the python operators as functions
try:
input = raw_input # rebind raw_input to input, if it exists
# so I can just use input :P
except NameError:
pass
name = input("Hi, what is your name?\n")
print("Hi {} let's get started! Question 1".format(name))
#Get out of the habit of using string concatenation and use string
#formatting whenever possible. Strings are *immutable*;
#concatenation has to produce a lot temporary strings and is *slow*
#str.join and str.format are almost always better ideas.
#Python does not have a switch-case, so emulating one with a dictionary
operator_mapping = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
#'/': operator.truediv, #hey, division exists.
#But if you want division to actually work, you'll
#have to introduce a fudge factor :P
}
for i in range(10): # If you're just going for 10 iterations, it should be a for loop
# Brevity :P This is a list comprehension
first_number, second_number = [random.randint(1,10) for _ in range(2)]
oper = random.choice(list(operator_mapping))
answer = operator_mapping[oper](first_number, second_number)
while int(input("{} {} {} = ".format(first_number, oper, second_number))) != answer:
#while abs(float(input("{} {} {} = ".format(first_number, oper, second_number)))-answer) < 0.001: if you want truediv.
print('Wrong answer! try again!')
#If I've left the loop, user has given correct (enough) answer
if i <9: # all but last
print('Well done! Now onto question number {0}'.format(i+2))
print('Well done! You are done!')
In the third line, you ask for input. But a name is a string, so you need raw_input. raw_input takes strings, input only takes numerical values.
Python 2.7 getting user input and manipulating as string without quotations
Nowhere in your code do you update the variable questions, which I am guessing is a counter. You have to update that whenever a question is asked, using question += 1.
Finally, your code at the end does not really make sense. Based off the code, it checks for whether or not it is a string, but then compares it to the answer regardless. The if statement needs to be within the try.
The else statement does not match any outer indentation.
Finally, because of the while True: your code will never exit the loop unless the answer is wrong. At the point the entire program terminates. I see what kind of program you are trying to write, but the parameters for random number generation have to be within some kind of a while question <= 10 loop. As of now, only two lines in the program are being affected by that first while loop.
EDIT: I am working on a good example code. Hopefully this answer will help until I can finish it.
EDIT: Here is code that shows how it works within a while loop.
import random
from random import randint
name = raw_input("Hi, what is your name?\n") # Asks for name
print "Hi " +name+ " let's get started!"
score_count = 0
question_count = 0 # creates counter
while question_count <= 10: # Everything MUST BE WITHIN THIS LOOP
# makes numbers and operator
first_number = randint(1,10)
second_number = randint(1,10)
oper = random.choice("+""-""*")
# determines the problem
if oper == "+":
answer = first_number + second_number
print first_number,second_number,oper
elif oper == "-":
answer = first_number - second_number
print first_number,second_number,oper
elif oper == "*":
answer = first_number*second_number
print first_number, second_number, oper
user_answer = int(raw_input("Your answer: "))
if user_answer != answer:
print 'Wrong answer! try again!'
user_answer = int(raw_input('Your answer: '))
if user_answer == answer: # exits the while loop when the correct answer is given
if question_count < 10:
print 'Well done! Now onto question number {0}'.format(question_count+1)
score_count += 1
elif question_count == 10:
print 'Well done! You are done!'
score_count += 1
else:
print 'Something is wrong.'
question_count += 1 # updates the variable
# GOES BACK TO THE BEGINNING UNTIL question_count IS GREATER THAN OR EQUAL TO 10
print "Your score was: {}".format(score_count)
Happy coding! and best of luck!
hi im Nathan and I saw this post I am 5 years to late but I figured if someone on here is knew to python I have a much easier (in my opinion) way to do this in python 3, the code is below:
import random #random module automatically downloaded when you install python
name = input("Please enter your name ")
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10) #creating a random number
numbers=random.randint(1,10) #creating a random number
list = ["+","-","/"] #creating a list (or sometimes called array)
arith=random.choice(list) #getting random operators from list (+,-,/)
question += 1 #basically means add one to question variable each time in loop
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
elif arith=="-":
print(number,arith,numbers)
answer=number-numbers
elif arith=="/":
print(number,arith,numbers)
answer=number/numbers
answer = int(answer)
#from HERE
useranswer = "initialising this variable"
while useranswer == "initialising this variable":
try:
usersanswer= int(input())
if usersanswer==answer:
print("correct")
break
else:
print("incorrect")
except ValueError:
print ("That is not a valid answer")
#to HERE it is input validation this takes a while to explain in just commenting
#but if you dont know what this is then copy this link https://youtu.be/EG69-5U2AfU
#and paste into google for a detailed video !!!!!!
I hope this helps and is a more simplified commented bit of code to help you on your journey to code in python