I'm trying to create a sum game where the problems are randomly generated. I'm using the random module to generate numbers and then asking for the user to input answers, then trying to compare user input to a variable that already contains the correct answer.
After 5 questions I want the while loop to break and 'end the game', but it's doing some strange things. It will loop 3 times then call a correct answer incorrect (See function CheckAnswer()) It's like my function to check user input against the correct answer isn't running, but I can't find where it's failing.
I'm pretty new to Python and this is the first project i'm attempting on my own. I didn't want it to be simple.
I've really just tried messing around with my functions and code to see if anything improves and it's worked for me until now.
point = 0
q_num = 0
def RandomNums():
rNum1 = random.randrange(51)
rNum2 = random.randrange(51)
return rNum1
return rNum2
def Add():
rNum1 = RandomNums()
rNum2 = RandomNums()
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = rNum1 + rNum2
return question
print(answer)
return answer
#Check actual answer against user input
def CheckAnswer():
if question == answer:
point += 1
print("Correct! +1 Point!")
print(point)
else:
print("Wrong. Next question.")
time.sleep(1)
# Ask user to choose their operator
op = input("Which operator do you want to use (x, -, /, +)?: ").strip().lower()
if op == 'x':
while q_num < 5:
RandomNums()
Multiply()
question = Multiply()
answer = Multiply()
CheckAnswer()
q_num += 1
print(point)
elif op == '+':
while q_num < 5:
RandomNums()
Add()
question = Add()
answer = Add()
CheckAnswer()
q_num += 1
print(point)
else:
print("What!? That's not a choice!")
I expect that if I get the answer correct (on input) that I'll get the print statement inside my CheckAnswer() function and that 1 will be added to my 'point' variable. I also expect that my 'q_num' variable will increase by 1 regardless because I want the while loop to break at 5 questions, ending the game.
What I get when I run the program is I can input anything and it won't tell me anything, regardless of whether it's correct or not. The while loop will loop 3 times and say my answer is incorrect on the 4th loop. Then it seems to reset the loop and q_num count.
Several problems here, and first I strongly recommend taking a python course, or working through an online book. I worry that you're going to develop some very serious misconceptions that I already see in your code.
First off, and I don't know how to say this so that you'll absorb it, the computer executes instructions in order, one at a time. This is a hard lesson to learn, especially if you try to learn it after already playing around with code some!
I know, because I remember as a kid wanting something to work with BASIC for loops that makes no sense if you've properly absorbed this lesson, but that made perfect sense to me at the time.
In your code, the consequence of not absorbing this lesson properly are the multiple return statements in a function. Once the computer hits one return statement, it leaves the function. This means that stuff after the first return statement that's encountered doesn't happen.
So let's take a look at your Add function:
def Add():
rNum1 = RandomNums()
rNum2 = RandomNums()
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = rNum1 + rNum2
return question
print(answer)
return answer
It's going to get two random numbers (we'll ignore the issues in RandomNums for the moment), then it's going to ask a question, take what the user did, put it in the local variable question, compute something for the local variable answer and then return the local variable question.
That's it. It's done then. It never does anything else.
This means that later in your program, when you say:
question = Add()
answer = Add()
What happens is that you ask the user two questions, and then set the global variable question to what the user said the first time, and set the global variable answer to what the user said the second time.
So your loop is really doing this:
RandomNums() # Compute two random numbers, return one, throw result away
Add() # Make a question, ask the user, throw the result away
question = Add() # Make a question, ask the user, store what they said
answer = Add() # Make a question, ask the user, store what they said
CheckAnswer() # Check if what the user said both times is the same, print message
q_num += 1 # increment loop number
print(point) # print point total
So your while loop wasn't running three times - it was running once, and in that one loop you were asking the user a question three times.
So you'd think then that something you could do is answer the same thing the last two times, and then you'd at least get the "correct answer" message. Unfortunately, you don't, because of another problem that's something slightly tricky about Python. What happens is this:
Which operator do you want to use (x, -, /, +)?: +
What is 40 + 31?: 3
What is 13 + 31?: 3
What is 2 + 9?: 3
Traceback (most recent call last):
File "/tmp/quiz.py", line 49, in <module>
CheckAnswer()
File "/tmp/quiz.py", line 24, in CheckAnswer
point += 1
UnboundLocalError: local variable 'point' referenced before assignment
What's happening here is that python thinks that point is a variable name that is local to the function CheckAnswer, when you of course want CheckAnswer to be modifying the global variable called point. Usually, python does the right thing with whether a variable should be global or local, (after all, it correctly deduced that you wanted to deal with the global answer and question) but += 1 looks like you're setting a new value (it's equivalent to point = point + 1), so python thought you meant a local variable called point. You can tell it otherwise by adding a global point statement to the top of CheckAnswer:
def CheckAnswer():
global point
if question == answer:
point += 1
print("Correct! +1 Point!")
print(point)
else:
print("Wrong. Next question.")
time.sleep(1)
Now when I play your quiz, this happens:
$ python /tmp/tst.py
Which operator do you want to use (x, -, /, +)?: +
What is 19 + 18?: 3
What is 4 + 39?: 3
What is 15 + 27?: 3
Correct! +1 Point!
1
1
What is 19 + 31?: 3
What is 21 + 47?: 4
What is 23 + 39?: 3
Wrong. Next question.
1
What is 45 + 12?: 2
What is 8 + 32?: 3
What is 28 + 16?: 3
Correct! +1 Point!
2
2
What is 23 + 0?: 0
What is 20 + 28?: 1
What is 0 + 49?: 2
Wrong. Next question.
2
What is 42 + 4?: 0
What is 27 + 18?: 1
What is 16 + 8?: 2
Wrong. Next question.
2
So that's a tiny improvement, and you can see that the loop is happening five times as expected.
Okay, so what about the problem you had before that you need to return two things, but the function stops at the first return statement?
What you can do is return something that in python is called a tuple, and then you can unpack it at the other end:
def RandomNums():
rNum1 = random.randrange(51)
rNum2 = random.randrange(51)
return (rNum1, rNum2) # return two things as a tuple
def Add():
(rNum1, rNum2) = RandomNums() # Unpack the tuple into two variables
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = rNum1 + rNum2
return (question, answer) # return a tuple of question and answer
And then later:
elif op == '+':
while q_num < 5:
(question, answer) = Add()
CheckAnswer()
q_num += 1
print("Points are: {}".format(point))
So this almost works. Unfortunately, it says our answer is wrong every time!
That's because in python, strings and integers are different things. What you got from the user (question) will be the string '40' whereas the answer you computed will be the integer 40. So to properly compare them, you need to either turn answer into a string or turn question into an integer.
I chose in the code below to turn answer into a string, but you could take the other choice if you're okay with your program blowing up when the user enters something that isn't an integer. (My experience with users is that they'll start to enter swear words into your program after a bit, which naturally won't turn into integers). The function in python to turn most things into a string is str.
So here's the whole program now:
# in your post, you forgot these import statements
import time
import random
# set up global variables
point = 0
q_num = 0
def RandomNums():
rNum1 = random.randrange(51)
rNum2 = random.randrange(51)
return (rNum1, rNum2) # return a tuple
def Add():
(rNum1, rNum2) = RandomNums() # unpack tuple into two variables
question = input("What is {} + {}?: ".format(rNum1, rNum2))
answer = str(rNum1 + rNum2) # Note how answer is now a string
return (question, answer)
#Check actual answer against user input
def CheckAnswer():
global point # need this since we assign to point in this function
if question == answer:
point += 1
print("Correct! +1 Point!")
print(point)
else:
print("Wrong. Next question.")
time.sleep(1)
# Ask user to choose their operator
op = input("Which operator do you want to use (x, -, /, +)?: ").strip().lower()
if op == 'x':
while q_num < 5:
print("Not done yet, come back later")
break # Now the computer won't try anything below; break exits the while loop
(question, answer) = Multiply()
CheckAnswer()
q_num += 1
print("Points are: {}".format(point))
elif op == '+':
while q_num < 5:
(question, answer) = Add()
CheckAnswer()
q_num += 1
print("Points are: {}".format(point))
else:
print("What!? That's not a choice! (yet)")
Now go implement the rest of your quiz.
A small suggestion: for - and especially for /, you might want to have the two random numbers chosen be the second operand and the answer, instead of the two operands. For example:
def Divide():
(answer, rNum2) = RandomNums() # unpack tuple into two variables
product = rNum2 * answer # good thing answer isn't a string yet, or this wouldn't work
question = input("What is {} / {}?: ".format(product, rNum2))
answer = str(answer) # change answer to a string, now that we're done doing math
return (question, answer)
Related
I have a python code that is a song guessing game, you are given the artist and the songs first letter, I used 2 2d arrays with on being the artist and the other being the song. I know I should've done a 3d array though to change it this late into my code I'd have to restructure the whole code and I wouldn't have time. Here is the appropriate code below:
attemptnum = 5
attempts = 0
for x in range (10):
ArtCount = len(artist)
print(ArtCount)
randNum = int(random.randint(0, ArtCount))
randArt = artist[randNum]
ArtInd = artist.index(randArt)# catches element position (number)
songSel = songs[randNum]
print ("The artist is " + randArt)
time.sleep(1)
print( "The songs first letter be " + songSel[0])
time.sleep(1)
print("")
question = input("What song do you believe it to be? ")
if question == (songSel) or ("c"):
songs.remove(songSel)
artist.remove(randArt)
print ("Correct")
print ("Next Question")
else:
attempts = attempts + 1
att = attemptnum = attemptnum - attempts
print("")
print("Wrong,")
print (att) and print (" attempts left.")
print("")
time.sleep(0.5)
if attempts == 5:
print("GAME OVER")
#input leaderboard here
print("Exiting in 3 seconds")
time.sleep(3)
exit()
Apologies if my code isn't so polished, this is a project for school. So what this code does is randomly a number from 0 to the number of how many elements the artist's list has. It then chooses an artist using the random number, it catches the number used with index so that it can be used on the songs array to get the corresponding song (I know very bad) It pitches the question and shows the first letter of the song. If you get the song you get the same code again but with the prior song and artist removed to prevent dupes. That's where the problem comes in, when usually running the code it'll randomly give me the error where the element I'm trying to output is not in the list:
randArt = artist[randNum]
IndexError: list index out of range
This can happen anywhere throughout the code when you're being asked a question, you can get to question 3 and get the error, or not even get to question 9 and get the error. It's completely random. I feel like its trying to occasionally get a hold of an artist and song that's been removed but that doesn't make sense since it only chooses from the amount counted on the list, not the original 10. I'm not sure if my way of saying it is right or if any one would understand, because I sure don't. To clarify, my code counts how many elements there are in the list, uses that number to find a song and artist, then removes it after to stop duping, but from what I can see it seems like it's trying to find and element simply out of the range of how many elements there actually are. Thanks for bearing with my amateur code.
random.randint is inclusive in both ends. randint(0, 10) will return a number in the range
0 <= _ <= 10.
However Python uses 0-based indexes.
If li is [1, 2, 3] then len(li) is 3, but li[3] does not exist.
Only li[0], li[1] and li[2] do.
When you are doing
ArtCount = len(artist)
randNum = int(random.randint(0, ArtCount))
randArt = artist[randNum]
You are asking for a number in the range 0 <= n <= len(artist). If n == len(artist) then artist[n] will cause an IndexError.
BTW, randint returns an int (hence the int in its name). int(randint(...)) is totally unnecessary.
You should either ask for a random number in the range 0 <= n <= len(artist) - 1 or simply use random.choice:
randArt = random.choice(artist)
You may want to catch an IndexError just in case artist is an empty list:
try:
randArt = random.choice(artist)
except IndexError:
print('artist list is empty')
Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return(result)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue
this might seem very basic to you, and I think I know what is wrong with my code, I just can't seem to figure out how to fix. Basically, I am building a very simple hangman game, and I want to make the user lose a life every time he guesses a letter wrong. Here is the code:
import random
word_choice = ["list", "microsoft", "cars", "philosophy", "mother", "powder", "star", "baby", "elephant"]
guessed_letters = []
right_guessed_letters = []
def user_turn(c):
lives = 10
while True:
guess = input("\nGuess a letter or a word: ")
guessed_letters.append(guess)
print ("\n")
if lives != 0 and guess != comp_choice:
if guess in comp_choice:
right_guessed_letters.append(guess)
for i in comp_choice:
if i in right_guessed_letters:
print (i, end= ' ')
else:
print ('-', end = ' ')
else:
lose_life(lives)
continue
elif guess == comp_choice:
print ("Good job, you guessed the word correctly!")
break
elif lives == 0:
print ("You lost, your lives are all depleated...")
break
def lose_life(l):
l -= 1
print (f'Wrong letter, you have {l} lives remaining')
print (f"The letters you already guessed are {guessed_letters}")
comp_choice = random.choice(word_choice)
word = '-' * len(comp_choice)
print (f"Your word is : {word} long.")
user_turn(comp_choice)
Basically, my problem is that the user can only lose one life. In fact, I would like that every time lose_life is called, the user loses a life so his lives decrease by one every time, however the variable lives gets it's original value right after the function is done rolling. So every time the function is called, the user is at nine lives. Here is the output:
microsoft
Your word is : --------- long.
Guess a letter or a word: d
Wrong letter, you have 9 lives remaining
The letters you already guessed are ['d']
Guess a letter or a word: e
Wrong letter, you have 9 lives remaining
The letters you already guessed are ['d', 'e']
Guess a letter or a word:
Anyways, If you could help, it would be very appreciated!
Your lose_life function is not returning anything, so all it effectively does is printing the two statements.
if you added a return l at the end of lose_life function, and change your lose_life(lives) in the else statement to lives = lose_life(lives), it should now work.
If this seems cumbersome and you're feeling adventurous, you may consider using Classes instead:
class Live(object):
def __init__(self, value=10):
self.value = value
def __str__(self):
return str(self.value)
def __repr__(self):
return self.__str__()
def lose(self):
self.value -= 1
print(f'Wrong letter, you have {self.value} lives remaining')
print(f"The letters you already guessed are {guessed_letters}")
def gain(self):
self.value += 1
# insert your own print messages if you wish.
Mind you I wouldn't recommend doing it for this use case (KISS principal applies), but for more complex projects where you have objects that need their own attributes and functions, Classes are great for that purpose.
Mastermind Game using "ABCEF"I dont know how to check whether it is partial correct. I have to use red to mean correct letter and position. I use white to mean correct letter.
import random
def play_one_round():
N_code=''.join(random.sample("ABCDEF",4))
print (N_code)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess= 1
while N_code != guess and count_guess < 10:
check(N_code,guess)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess=count_guess + 1
print("This is your",count_guess, "guess")
if guess==N_code:
print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order.
def check(N_code,guess):
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)]
for index, char in enumerate(guess):
if result[index] !='r':
if char in result:
result[result.index(char)]='w'
print(result)
def Master_m():
print("Welcome to Mastermind!\n")
print("Start by Choosing four letters")
play_one_round()
answer=input("Play Again? ")
if answer[0]=='y':
Master_m()
Master_m()
I wrote this ages ago but it will do the trick
import random
import itertools
def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
rules()
elif path == '2':
print('Great lets play some Mastermind!\n')
begingame()
start()
else:
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')
start()
def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')
start()
def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""
#generate a 4 digit number
num = random.sample(range(1,9), 4)
#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))
return roll
def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')
#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0
#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
try:
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
pass
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
pass
else:
print ( "Your choice is", choice)
#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]
#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]
#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)
#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0
#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')
#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])
print ('Oh Mastermind that was a good try! ')
#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)
#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed
#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)
# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses
collectScore.append(totalResults)
#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')
break
#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')
#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")
#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)
#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')
if __name__ == '__main__':
start()
When you are stuck, decompose into smaller chunks and test those. Focusing on check, you can check whether a guess letter exactly matches the code via its index and whether its in the code at all with in. Here is a self-contained example. Notice that I've pulled out everything except the problem at hand.
If this works for you, I suggest writing a self-contained example of your next problem, test it, and if you are still stuck, post that as a new question.
def check(N_code, guess):
print('code', N_code, 'guess', guess)
result = []
# enumerate gives you each letter and its index from 0
for index, letter in enumerate(guess):
if N_code[index] == letter:
# right letter in right position
vote = 'red'
elif letter in N_code:
# well, at least the letter is in the code
vote = 'white'
else:
# not even close
vote = 'black'
# add partial result
result.append('{} {}'.format(letter, vote))
# combine and print
print(', '.join(result))
check('ABCD', 'ABCD')
check('DEFA', 'ABCD')
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
name = input('What is your name?')
print('Welcome to my quiz',name)
guess = 0
tries = 0
answer = 5
score = 0
while guess != answer and tries < 2:
guess = int(input("10/2 is..."))
if guess == answer:
print ("Correct")
score = score + 1
else:
print ("Incorrect")
score = score + 0
tries = tries + 1
guess = 0
tries = 0
answer = 25
while guess != answer and tries <2:
guess = int(input("5*5 is..."))
if guess == answer:
print("Correct")
score = score + 1
else:
print("Incorrect")
score = score + 0
tries = tries + 1
print("Thank you for playing",name,". You scored",score,"points")
I'm trying to loop the questions with random numbers but I'm not sure how to do it. How can I make a quiz that asks the user multiplication, addition, subtraction and division questions using random numbers and records their scores.
>>> import random
>>> random.randint(0,10)
3
>>> random.randint(0,10)
8
>>> random.randint(0,10)
10
You can use python random library to generate random number for your question.
>>> help(random.randint)
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
So you can give a range to random.randint method and it will generate unique values for you each time you call it.
You want to use the module random. The coding would look something like this.
import random
name = input('What is your name? ')
print('Welcome to my quiz',name)
guess = 0
tries = 0
answer = 1
score = 0
num1=random.randint(1,100) #you can use whatever numbers you want here
num2=random.randint(1,100) #see above
answer=num1+num2
while guess != answer and tries < 2:
#print("What is",num1,"+",num2,"?") #you can use print or...
question="What is the sum of " + str(num1) +"+"+ str(num2)+"? "
guess=float(input(question)) #if you use print, remove the word question
if guess == answer:
print ("Correct")
score = score + 1
else:
print ("Incorrect")
score = score + 0
tries+=1
guess=0
tries = 0
num1=random.randint(1,100) #you can use whatever numbers you want here
num2=random.randint(1,100) #see above
answer=num1*num2
while guess != answer and tries <2:
#print("What is",num1,"*",num2,"?") #you can use print or...
question="What is the product of " + str(num1) +"*"+ str(num2)+"? "
guess=float(input(question)) #if you use print, remove the word question
if guess == answer:
print("Correct")
score = score + 1
else:
print("Incorrect")
score = score + 0
tries+=1
print("Thank you for playing",name,". You scored",score,"points")
What I did was I created two random numbers(num1 and num2), and then added/multiplied them together. Hope this helps answer your question.