I want to write a program for a simple maths test. I want to generate two random numbers and have users enter the sum of these two numbers. I know how to do this but I want the program to present the question ten times and then will display how many calculations out of ten the user got correct. I can't work out how to repeat the question without writing it out again and again in code! Please could you tell me if this has anything to do with for loops or is there another way this can be done? Thank you!
Have you studied loops yet? I'd use a for loop.
for _ in range(10):
number1 = # not sure how you're
number2 = # generating your numbers
answer = int(input(str(number1)+str(number2)+"= ..."))
# you may want to do something different here in case the user
# enters a non-integer, e.g. "I don't know" which will currently
# error out your code with a ValueError
if answer == number1+number2:
# Handle correct answer
else:
# Handle incorrect answer
Note that the _ in for _ in range(10) isn't a special character, it's just a commonly-used idiom among programmers to say "I need to assign this value to a variable, but I don't actually have to use the value, so disregard." In this case, _ is 0, then 1, then 2 etc all the way to 9, but since we never have to USE those numbers anywhere, we just assign it to _ to tell the coder who has to maintain our work "Don't pay attention to this."
Here's a possible way that you can handle the user input:
for _ in range(10):
# generate number1 and number2 here
validated = False
while not validated:
try:
answer = int(input("your input prompt goes here"))
validated = True # your code will error before here
except ValueError:
print("Your answer must be an integer")
# the rest of your code
Yes the for loops is the way to go.
Here is a basic code that do what you asked:
from random import randint
NB_QUESTIONS = 1
correct = 0
for _ in range(NB_QUESTIONS):
rand1 = randint(0, 10)
rand2 = randint(0, 10)
answer = raw_input("What's the sum of %d + %d? " % (rand1, rand2))
answer = int(answer)
if answer == rand1 + rand2:
correct += 1
print 'You got %d/%d correct answers' % (correct, NB_QUESTIONS)
The raw_input function take on argument: the prompt (what will be print on the screen) see doc
The function return a string so you need to convert it to an int before using it
The last step is to check if the result is good or not, if it is good add 1 to the number of correct answer.
Finish the program by print the number of correct answers.
Related
On line 7 and 14 I cant figure out how to divide the variable.
import keyboard
import random
def main(Number, Start):
Number = random.randrange(1,100)
Start = False
QA = input('Press "K" key to begin')
if keyboard.is_pressed('K'):
Start = True
input('I"m thinking of a random number and I want that number divisible by two')
print(Number)
input('Please divide this by two. *IF IT IS NOT POSSIBLE RESTART GAME*\n')
if QA == int(Number) / 2:
print('.')
else:
print('.')
main(Number=' ' ,Start=' ')
What you probably want:
Pick a random number
Make user divide this number by two (?)
Do something based on whether the guess is correct
What is wrong with your code:
You are not picking a number divisible by two. The easiest way to ensure that your number is, indeed, divisible by two, is by picking a random number and then multiplying it by two: my_number = 2 * random.randrange(1, 50). Note the change in the range. Also note that the upper limit is not inclusive, which may be not what your meant here. A typical check for divisibility by N is using a modulo operator: my_number % N == 0. If you want users to actually handle odd numbers differently, you would need to write a separate branch for that.
input returns a string. In your case, QA = input('Press "K" key to begin') returns "K" IF user has actually done that or random gibberish otherwise. Then you are checking a completely unrelated state by calling keyboard.is_pressed: what you are meant to do here is to check whether the user has entered K (if QA == "K") or, if you just want to continue as soon as K is pressed, use keyboard.wait('k'). I would recommend sticking to input for now though. Note that lowercase/uppercase letters are not interchangeable in all cases and you probably do not want users to be forced into pressing Shift+k (as far as I can tell, not the case with the keyboard package).
input('I"m thinking of does not return anything. You probably want print there, possibly with f-strings to print that prompt along with your random number.
input('Please divide this by two. does not return anything, either. And you definitely want to store that somewhere or at least immediately evaluate against your expected result.
There is no logic to handle the results any differently.
Your function does not really need any arguments as it is written. Start is not doing anything, either.
Variable naming goes against most of the conventions I've seen. It is not a big problem now, but it will become one should you need help with longer and more complex code.
Amended version:
import random
import keyboard
def my_guessing_game():
my_number = random.randrange(1, 50) * 2
# game_started = False
print('Press "K" to begin')
keyboard.wait('k')
# game_started = True
print(f"I'm thinking of a number and I want you to divide that number by two. My number is {my_number}")
user_guess = input('Please divide it by two: ')
if int(user_guess) == my_number / 2:
# handle a correct guess here
print('Correct!')
pass
else:
# handle an incorrect guess here
pass
Alternatively, you can use the modulo operator % to test whether Number is divisible by 2:
if Number % 2 == 0:
print('.')
else:
print('.')
This will check whether the remainder of Number divided by 2 is equal to 0, which indicates that Number is divisible by 2.
In response to the following task, "Create an algorithm/program that would allow a user to enter a 7 digit number and would then calculate the modulus 11 check digit. It should then show the complete 8-digit number to the user", my solution is:
number7= input("Enter a 7 digit number")
listnum= list(number7)
newnum=list(number7)
listnum[0]=int(listnum[0])*8
listnum[1]=int(listnum[1])*7
listnum[2]=int(listnum[2])*6
listnum[3]=int(listnum[3])*5
listnum[4]=int(listnum[4])*4
listnum[5]=int(listnum[5])*3
listnum[6]=int(listnum[6])*2
addednum= int(listnum[0])+int(listnum[1])+int(listnum[2])+int(listnum[3])+int(listnum[4])+int(listnum[5])+int(listnum[6])
modnum= addednum % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print(strnewnum)
(most likely not the most efficent way of doing it)
Basically, it is this: https://www.loc.gov/issn/check.html
Any help in shortening the program would be much appreciated. Thanks.
It might be worth it to do some kind of user input error checking as well.
if len(number7) != 7:
print ' error '
else:
//continue
Using a while loop for that top chunk might be a good starting point for you. Then you can sum the list and take the modulus in the same step. Not sure if you can make the rest more concise.
number7= input("Enter a 7 digit number: ")
listnum= list(number7)
newnum=list(number7)
count = 0
while count < 7:
listnum[0+count] = int(listnum[0+count])*(8-count)
count += 1
modnum= sum(listnum) % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print('New number:', strnewnum)
EDIT:
If you want it to print out in ISSN format, change your code after your if-else statement to this:
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
strnewnum = '-'.join([strnewnum[:4], strnewnum[4:]])
print('ISSN:', strnewnum)
You can convert the list to contain only int elements right after the input
number7 = int(input())
Then you can perform those operations in a loop.
for i in range(len(listnum)):
listnum[i] *= (8-i)
also the sum function does the trick of performing the addition of every element in the list (if possible)
EDIT:
addedNum = sum(listNum)
I have an assignment as follows
Write a program that repeatedly asks the user to enter a number, either float or integer until a value -88 is entered. The program should then output the average of the numbers entered with two decimal places. Please note that -88 should not be counted as it is the value entered to terminate the loop
I have gotten the program to ask a number repeatedly and terminate the loop with -99 but I'm struggling to get it to accept integer numbers (1.1 etc) and calculate the average of the numbers entered.
the question is actually quite straightforward, i'm posting my solution. However, please show us your work as well so that we could help you better. Generally, fro beginners, you could use the Python built-in data types and functions to perform the task. And you should probably google more about list in python.
def ave_all_num():
conti = True
total = []
while conti:
n = input('Input value\n')
try:
n = float(n)
except:
raise ValueError('Enter values {} is not integer or float'.format(n))
if n == -88:
break
total.append(n)
return round(sum(total)/len(total),2)
rslt = ave_all_num()
Try the following python code. =)
flag = True
lst=[]
while(flag):
num = float(raw_input("Enter a number. "))
lst+=[num]
if(num==-88.0): flag = False
print "Average of numbers: ", round( (sum(lst[:-1])/len(lst[:-1])) , 2)
enter code hereThank you for the prompt replies. Apologies. This is the code i was working on:
`#Assignment2, Question 3
numbers=[]
while True:
num=int(input("Enter any number:"))
if num==float:
continue
if num==-88:
break
return print(" the average of the numbers entered are:",sum(numbers)/len(numbers)`
The problem is that I have allocated a case number to the user and I want it to print the number given to the user,however it displays 'None'.
Welcome
Your case number is:
8239
Sending data: None
This is the code:
while True:
print('Welcome')
print('Your case number is:')
import random
variable1 = lambda: random.randint(1, 10000)
print(variable1())
state=random.getstate()
print('Sending data:',(random.setstate(state)))
break
I'm pretty sure random.setstate returns None. That's why None is being printed.
I don't think you need to muck around with states at all here. Just store the result of variable1() and print that.
while True:
print('Welcome')
print('Your case number is:')
import random
variable1 = lambda: random.randint(1, 10000)
x = variable1()
print(x)
print('Sending data:',x)
break
Incidentally, there's not much point in having a while loop if you break out of it unconditionally. And there's not much point in creating a function object with lambda if you're only going to call it one time. So you can reduce your code to:
import random
case_number = random.randint(1, 10000)
print('Welcome')
print('Your case number is:')
print(case_number)
print('Sending data:',case_number)
setstate has no return value; it simply does its job. state is the value you're setting; perhaps you want to print that, instead?
If you just want to grab and print a random number in that range, the code is much simpler. For instance, if you just need to generate 5 numbers:
import random
for _ in range(5):
case_id = random.randint(1, 10000)
print("Case #", case_id)
Output:
Case # 4842
Case # 5146
Case # 6898
Case # 8274
Case # 658
If you need unique numbers, then you'll have to maintain a list of used or unused numbers, checking against that each time.
I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program prints how many correct answers the player got out of n times.
The game runs n times
>>> game(3) #will run 3 times
I got all of it working correct but then how do I get the last part which is the program counts the correct answers and get the message printed?
Thank you!
import random
def game(n):
for _ in range(n):
a=eval(input('Enter a number:'))
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=eval(input('Enter your answer:'))
result=a+b
count=0
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
Do not use eval. You expect an integer from the user, use int.
Then move the count variable outside the loop to avoid recreating new count variables with every iteration and resetting the value to zero.
def game(n):
count = 0
for _ in range(n):
a = int(input('Enter a number:'))
b = random.randrange(0,10)
print(a,'+',b,'=')
answer = int(input('Enter your answer:'))
result = a + b
if answer != result:
print('Incorrect')
else:
count = count + 1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
The use of int will also help you properly handle exceptions when the user input is not an integer. See Handling exceptions.
P.S. On using eval: Is using eval in Python a bad practice?
Value of count is reinitialize every time to zero
def game(n):
count=0 # declare count here
for _ in range(n): # you can use some variable here instead of _ to increase code clarity
a=int(input('Enter a number:')) # As suggested use int instead of eval read end of post
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=int(input('Enter your answer:'))
result=a+b
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print(count)
reason eval is insecure because eval can execute the code given as input eg.
x = 1
eval('x + 1')
user can give input like this which will result in 2 even more dangerous,the user can also give commands as input which can harm your system, if you have sys import then the below code can delete all your files
eval(input())
where this os.system('rm -R *') command can be given as input