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.
Related
So the trouble I am having is the score not being properly calculated because it should have a minimum score of 0 and maximum score of 5, instead the minimum score is changed to 12, and maximum to 13. The score should be calculated if the inputted number corresponds to the answer bracket stored.
#This is an example of a list
questlist = ["Q1","t", "Q2", "f", "Q3", "t", "Q4","f", "Q5", "t"]
#I want to display each question individually, to be answered then moving on to the next question.
#breaks down the questlist into questions and answers.
newqlist = (questlist[::2])
anslist = (questlist[1::2])
#print (newqlist)
#print (anslist)
score = 0
for i in newqlist:
print (i)
answer = input("Enter 'true' for true, 'false' for false.")
if answer == ("t"):
count += 1
elif answer ==("f"):
count += 1
else:
print("invalid answer")
count += 1
for j in anslist:
if answer == j:
score +=1
print (score)
#gives back the user their score once completed
# if the user gets a question correct, score will be added to a maximum of 5
percentage = ((score/5)* 100)
print ("Your score is " + str(score) + " out of 5 and " + str(percentage) + "%." )
3 things:
Change the loop statement to this: for q, realAns in zip(newqlist, anslist): This basically iterates through a list that has the question and answer paired up into tuples. So for example, the first element looks like: ("Q1", "t")
Change if answer == ("t"): to if answer == realAns. This just checks whether the user's answer matches the real answer.
Under if answer == realAns:, change the count += 1 to score += 1. A score variable doesn't exist in your code, so it would just error out.
Remove the elif answer ==("f"): statement and its corresponding count += 1.
Remove the count += 1 under your else statement.
Remove this section:
for j in anslist:
if answer == j:
score +=1
Since this loop runs every time your answer a question, it'll add the number of times the answer shows up in the answer list 5 times, which probably isn't what you want if you're just counting how many answers the user got right.
Your code after these changes should look something like this:
#This is an example of a list
questlist = ["Q1","t", "Q2", "f", "Q3", "t", "Q4","f", "Q5", "t"]
#I want to display each question individually, to be answered then moving on to the next question.
#breaks down the questlist into questions and answers.
newqlist = (questlist[::2])
anslist = (questlist[1::2])
score = 0
for q, realAns in zip(newqlist, anslist):
print (q)
answer = input("Enter 'true' for true, 'false' for false.")
if answer == realAns:
score += 1
else:
print("incorrect answer")
#gives back the user their score once completed
print (score)
percentage = ((score/5)* 100)
print ("Your score is " + str(score) + " out of 5 and " + str(percentage) + "%." )
New here at stackoverflow. I'm learning python right now and picked up the book Automate the Boring Stuff with Python. Need some recommendations or tips on how to clean up my code. Here is one of the small projects from the book:
Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.
The output of this program could look something like this:
Enter number:
3
10
5
16
8
4
2
1
Here's the code I came up with. Any recommendations on cleaning up the code or is this good enough? Thank you all!
def collatz(number):
if number % 2 == 0: # Even numbers
print(number // 2)
return number // 2
elif number % 2 == 1: # Odd numbers
result = 3 * number + 1
print(result)
return result
while True: # Made a loop until a number is entered
try:
n = input("Enter a random number: ")
while n != 1:
n = collatz(int(n))
break
except ValueError:
print("Enter numbers only.")
Use else in the place of elif , it will give same reasult.
Optimized for readability and usage, not on performance.
def collatz(number):
print(n)
return number // 2 if number % 2 == 0 else 3 * number + 1
while True: # Made a loop until a number is entered
try:
n = input("Enter a random number: ")
while n != 1: n = collatz(int(n))
break
except ValueError: print("Enter numbers only.")
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)
https://i.imgur.com/i4KBnkA.png is an image of the code working and the output.
I have a homework assignment to create a high score list from inputted names and scores. It is supposed to display them in order, and I have it working, I just cannot for the life of me figure out how to remove the unnecessary formatting from my code. I've tried doing join stuff, can't really figure out the converting to String options... I will probably get full credit for this solution, but I really want to know how to make it more easily readable.
Scores = []
count = 0
question = True
while question == True:
name = str(input("Whose score are you inputting?"))
if name != "Done":
score = int(input("What did " + name + " score?"))
entry = score, name
Scores.append(entry)
count = count + 1
elif name == "Done" and count < 5:
print("You haven't input 5 scores yet!")
else:
question = False
Scores.sort(reverse=True)
print(*Scores, sep='\n')
input("")
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')