Trying to make a small program where a user can answer basic questions (1+1 etc). But the questions should be random, in my code, no random numbers are generated. Is the for loop in wrong place?
import random
from random import randrange
x = random.randrange(0, 101)
y = random.randrange(0, 101)
sum = (x + y)
for sum in range(1, 5):
a = int(input(f'What is {x} + {y}? '))
if a == sum:
print('Correct')
else:
print(f'Not correct, the correct answer is {sum}.')
There are a few issues. To begin with, sum is a function name in python, so it's not a good idea to use that as a variable name. Also, you declare that variable in line 11 but then you overwrite it in line 13 by using it as your variable in the for loop. Your random number generation AND your if/else should take place inside your for loop. With the current code, you are looping over the same question 5 times before you get to the if statement.
Here is the general structure you need:
# Imports
# For loop starts
# Generate random numbers and variable for total
# Ask question and get input
# If/else to check answer
(Jun-17-2020, 12:44 PM)buran Wrote: [ -> ]sum
is built-in function and you should not use it as variable name
...is it that you want to ask 5 different questions
Oh, will never use sum as a variable again. :) I was unclear, should be 5 different questions.
Updated code, still no success. User is beeing asked only once. So I am thinking of the for loop which contains the variable
i. Why? Well, good question. I am just learning by doing so would like to have some feedback.
import random
from random import randrange
for i in range(1, 5):
x = random.randrange(0, 101)
y = random.randrange(0, 101)
tot = (x * y)
a = int(input(f'What is {x} + {y}? '))
if a == tot:
print('Correct')
else:
print(f'Not correct, the correct answer is {tot}.')
lines 13-20 are still outside the loop
tot
is result of multiplication, but the question is about addition
with
range(1, 5)
you will ask 4 questions
import random
for i in range(1, 5): # ask 4 questions. You can do just range(4)
x = random.randrange(0, 101)
y = random.randrange(0, 101)
tot = x + y
answer = int(input(f'What is {x} + {y}? '))
if answer == tot:
print('Correct')
else:
print(f'Not correct, the correct answer is {tot}.')
Look at the indentation of lines 13 to 20. If you want that part to loop it needs to be indented with the rest of the for loop above it. Also, check the docs on the range() function. Your loop will not iterate 5 times ut only 4.
Thanks for your feedback (and patience). Surely, will read more about range and specially
indent.
import random
from random import randrange
for i in range(1, 6):
x = random.randrange(0, 101)
y = random.randrange(0, 101)
tot = (x + y)
a = int(input(f'What is {x} + {y}? '))
if a == tot:
print('Correct')
else:
print(f'Not correct, the correct answer is {tot}.')