I'm a beginner in Python and I'm basically trying to make a basic maths program for myself and started off with a two-digit addition program with random questions each time and I'm even managing to mess that up. Each time I input a correct answer it says it's incorrect everytime. Here's the code:
import random
digit_one = random.randint(0,100)
digit_two = random.randint(0,100)
print "What is %s + %s?" % (digit_one, digit_two)
answer = digit_one + digit_two
userAnswer = raw_input()
if userAnswer == answer:
print "Well done that's correct!"
else:
print "That's incorrect!"
I'm working in 2.7 and the built-in IDLE IDE. I have a feeling I should have used a loop for this instead although I know I'll have to use one later on if I want it to keep reloading questions. I'd appreciate any help, thank you.
inton the string.inputis a horrible habit to get into.inputor any other variation ofevalto beginners without being extremely clear about all security and performance implications this has. And especially, don't do it in cases where there is a perfectly safe, fast, readable and obvious way to achieve the same task (which isintin this case).evaland evenliteral_evalas can be seen from my past answers. I personally never useinput(the py2 one). BUT, it seems to me, that a lot of tutorials seem to use it, because most (or at least very many) beginners questions use it. So I suspected thatinputwas quite common among beginners as your input gets parsed nicely and magically. And later one starts learning about types, type conversion, autoboxing, comparison, identity, etc... No intention to offend anyone.input/evalover and over again ;) Anyways, you contradict yourself - if you're a strong advocate againsteval, why recommendinputwhich uses it? Especially to a beginner who should rather be steered away from bad habits like this. Feels like a C programmer who, faced with a question about how to repeat statements, recommendsgotooverfor...