i'm a beginner in python and I am coding a multiplicator challenge in terminal. I need to call the function randint in order to ask random questions about multiplication tables. The problem is that in my iterative loop, the number printed is always the same, it generates a random one but it is the same in every loop, that's a big problem for me, here's my code
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
multi=(randint(1,10))
for nombreQuestions in range(nombreQuestions):
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
Thank you very much
You only call randint at the start at line 6 where it is set once before you enter the loop
This means that each iteraction uses the same value
To fix this you need to set multi inside the loop (instead of outside)
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi=(randint(1,10)) # multi is now set every loop
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
Add multi=... in the loop so it will execute on every loop Iteration.
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi=(randint(1,10))
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
If you want to generate a random number each time then you need to call the randint() method inside the loop not outside.
Which mean this line multi=(randint(1,10)) should be used inside for loop.
Just like this,
from random import *
nombreQuestions = int(input("How many questions ? : "))
score = 0
choixTable= int(input("On which number do you want to get asked on ? : "))
for nombreQuestions in range(nombreQuestions):
multi = randint(1,10)
question=str(choixTable)+" x "+str(multi)+" = "
reponse = int(input(question))
if reponse == choixTable*multi:
print("Well played")
else:
print("Wrong !")
One thing more, specifying the name of the function in the import statement is more preferred i.e., instead of importing like from random import * use from random import randint
Related
Looking on for some guidance on how to write a python code
that executes the following:
The program will ask for math problems to solve.
The program will asks for the number of problems.
And asks for how many attempts for each problem.
For example:
Enter amount of programs: 4
Enter amount of attempts: 5
what is: 4x3 =?
Your answer: 16
and so goes on to another attempt if wrong if correct moves onto another problem, just like before and exits when attempts or problems are finished.
I have this code but I want to it only do multiplication ONLY and would like to know how to integrate how to put additional code to limit how many time one can solve the question and how many questions it asks
import random
def display_separator():
print("-" * 24)
def get_user_input():
user_input = int(input("Enter your choice: "))
while user_input > 5 or user_input <= 0:
print("Invalid menu option.")
user_input = int(input("Please try again: "))
else:
return user_input
def get_user_solution(problem):
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
return result
def check_solution(user_solution, solution, count):
if user_solution == solution:
count = count + 1
print("Correct.")
return count
else:
print("Incorrect.")
return count
def menu_option(index, count):
number_one = random.randrange(1, 21)
number_two = random.randrange(1, 21)
problem = str(number_one) + " + " + str(number_two)
solution = number_one + number_two
user_solution = get_user_solution(problem)
count = check_solution(user_solution, solution, count)
def display_result(total, correct):
if total > 0:
result = correct / total
percentage = round((result * 100), 2)
if total == 0:
percentage = 0
print("You answered", total, "questions with", correct, "correct.")
print("Your score is ", percentage, "%. Thank you.", sep = "")
def main():
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
main()
As far as making sure you're only allowing multiplication problems, the following function should work.
def valid_equation(user_input):
valid = True
for char in user_input:
if not(char.isnumeric() or char == "*"):
valid = False
return valid
Then after each user_input you can run this function and it will return True if the only things in the users string are numbers and the * sign and False otherwise. Then you just need to check the return value with a if statement that tells the user that their input is invalid if it returns False. You can add more "or" operations to the if statement if you want to allow other things. Like if you want to allow spaces (or char == " ").
As far as limiting the number of times a user can try to answer, and limiting the number of questions asked, you just need to store the values the user enters when you ask them these numbers. From there you can do nested while loops for the main game.
i = 0
user_failed = False
while ((i < number_of_questions) and (user_failed == False)):
j = 0
while ((j < number_of_attempts) and (user_correct == False)):
#Insert question asking code here
#In this case if the user is correct it would make user_correct = True.
j += 1
if j == number_of_attempts:
user_failed = True
i += 1
So in this situation, the outer while loop will iterate until all of the questions have been asked, or the user has failed the game. The inner loop will iterate until the user has used up all of their attempts for the question, or the user has passed the question. If the loop exits because the user used up all of their attempts, the for loop will trigger making the user lose and causing the outer loop to stop executing. If it does not it will add one to i, saying that another question has been asked, and continue.
These are just some ideas on how to solve the kinds of problems you're asking about. I'll leave the decision on how exactly to implement something like this into your code, or if you decide to change parts of your code to better facilitate systems like this up to you. Hope this helps and have a great one!
This question already has answers here:
Numeric comparison with user input always produces "not equal" result
(4 answers)
Closed 4 years ago.
whats up? I'm playing around with my mastermind project for school, only recently started dabbling into Python - and I've ran into a problem I simply cannot figure out? I've looked at other people's questions, who seem to have the same problem as me, but it seems to be more selective, and my code is kind of different. Can anyone tell me why whenever I reply to the question, it immediately skips to "Try again!", even if I know for a fact rnumber == tnumber? (Using Python 3.4.2).
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = input("Guess the four digit number. ")
type(tnumber)
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
elif rnumber != tnumber:
print ("Try again!")
numot = numot+1
you need to make your input an int so it considers it a number, try this
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = int(input("Guess the four digit number. "))
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
else rnumber != tnumber:
print ("Try again!")
numot = numot+1
I originally wrote this program in python 2, and it worked fine, then I switched over to python 3, and the while loop working.
I don't get any errors when I run the program, but it isnt checking for what the value of i is before or during the run. The while loop and the first if loop will run no matter what.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")
Thanks for any help in advance.
You are comparing something like '6' == 6, since you didn't convert the user input to an int.
Replace user_answer = input("Try to guess the magic number. (1 - 10) ") with user_answer = int(input("Try to guess the magic number. (1 - 10) ")).
user_answer will store the input as string and random.randint(1,10) will return an integer. An integer will never be equal to a string. So you need to convert user_input to integer before checking.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then
asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
# better use exception handling here
try:
user_answer = int(user_answer)
except:
pass
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")
When I choose to hold two dice it will not always follow the script. It occurs at approximately line 50. Sometimes it doesn't even print the list.
(As a side note- if anyone can simplify the code it would be much appreciated.)
Can anybody help offer a solution and reason for the problem.
(Script is below)
import random
points = 0
final = []
print("Welcome to Yahtzee")
print("Where there are closed questions answer lower case with 'y' or n'")
print("Please be aware that this a variation of the traditional game.\nShould you hold a number- you cannot 'unhold' it.\nIt has been added to your final roll for the round.")
print("Do not be tempted to hold onto a number you haven't rolled\n- this will not work and won't be added to your final score")
def roll_dice():
global collection
collection = []
input("Press Enter to roll the first die")
die_1 = random.randint(1,6)
collection.append(die_1)
print(die_1)
input("Press Enter to roll the second die")
die_2 = random.randint(1,6)
collection.append(die_2)
print(die_2)
input("Press Enter to roll the third die")
die_3 = random.randint(1,6)
collection.append(die_3)
print(die_3)
input("Press Enter to roll the fourth die")
die_4 = random.randint(1,6)
collection.append(die_4)
print(die_4)
input("Press Enter to roll the fifth die")
die_5 = random.randint(1,6)
collection.append(die_5)
print(die_5)
roll_dice()
print(collection)
yeno = input("Would you like to hold any dice? ")
if yeno == "n":
input("This will mean re-rolling all the dice: proceeding...")
del(collection)
roll_dice()
print(collection)
elif yeno == "y":
no = input("How many dice would you like to hold: " )
if no == "1":
num1 = input("Enter the number you would like to keep: ")
num1 = int(num1)
for x in range(len(collection)-1):
if collection[x] == num1:
final.append(num1)
del(collection[x])
print(collection)
print(final)
if no == "2":
num2 = input("Enter the first number you would like to keep: ")
num2 = int(num2)
num3 = input("Enter the second number you would like to keep: ")
num3 = int(num3)
for x in range(len(collection)-1):
if collection[x] == num2:
final.append(num2)
del(collection[x])
for x in range(len(collection)-1):
if collection[x] == num3:
final.append(num3)
del(collection[x])
print(collection)
print(final)
Seems you would do well to read up on what list and the random module has to offer.
Below a suggested simple solution to generate one round of Yatzy.
NOTE: the solution uses formatted string literals so Python 3.6 or greater is needed.
#! /usr/bin/env python3
import sys
import random
greeting = """Welcome to Yatzy
Where there are closed questions answer lower case with 'y' or n'
When asked which dice to hold answer with a list of dice separated by
space.
At most 3 rounds per turn. Between each turn decide what numbers to
keep before rolling again.
Please be aware that this a variation of the traditional game. Should
you hold a number- you cannot 'unhold' it. It has been added to your
final roll for the round.
Do not be tempted to hold onto a number you haven't rolled - this will
not work and won't be added to your final score.
"""
# Assume we have N dice. There are 3 rounds per turn and between
# rounds the player chooses r numbers to keep. The next round will
# then have N - r dice to roll. After each turn the kept dice
# collection is displayed.
#
# The turn stops when 3 rounds have been played or when there are no
# more dice to roll or when the player decides to stop.
def play_one_turn(dice=5, turns=3):
keep = []
msg = "Dice to hold: "
while turns and dice:
turns -= 1
print(f"Kept: {keep}")
play = random.choices(range(1, 7), k=dice)
print(f"Throw --> {play}")
for h in map(int, input(msg).split()):
if h in play:
keep.append(h)
dice -= 1
play.remove(h)
ask = "Another round? (yes/no) "
if not input(ask).strip().upper().startswith('Y'):
break
return keep
if __name__ == "__main__":
print(greeting)
score = play_one_turn()
print(f"Play result {score}")
first time writing here.. I am writing a "dice rolling" program in python but I am stuck because can't make it to generate each time a random number
this is what i have so far
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8)
print("Roll or Quit(r or q)")
now each time that I enter r it will generate the same number over and over again. I just want to change it each time.
I would like it to change the number each time please help
I asked my professor but this is what he told me.. "I guess you have to figure out" I mean i wish i could and i have gone through my notes over and over again but i don't have anything on how to do it :-/
by the way this is how it show me the program
COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r
1
r
1
r
1
r
1
I would like to post an image but it won't let me
I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU
Simply use:
import random
dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8) # this only gets called once, so r is always one value
print("Roll or Quit(r or q)")
Your code has quite a few errors in it. This will only work once, as it is not in a loop.
The improved code:
from random import randint
computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
print('COP 1000') # q and r are initialized to avoid user error, see the bottom description
print("Let's play a game of Chicken!")
player_input = '' # this has to be initialized for the loop
while player_input != 'q':
player_input = raw_input("Roll or quit ('r' or 'q')")
if player_input == 'r':
roll = randint(1, 8)
print('Your roll is ' + str(roll))
# Whatever other code you want
# I'm not sure how you are calculating computer/player score, so you can add that in here
The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q, it would stop the loop, and go to the next part of the program. See: Python Loops --- Tutorials Point
The picky part about Python 3 (assuming that's what you are using) is the lack of raw_input. With input, whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input 'q' or 'r'. However, a way to avoid an user error (if the player inputs simply q or r, without the quotes) is to initialize those variables with such values.
Not sure what type of dice has 8 numbers, I used 6.
One way to do it is to use shuffle.
import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])
Each time and it would randomly shuffle the list and take the first one.
This is a python dice roller
It asks for a d(int) and returns a random number between 1 and (d(int)).
It returns the dice without the d, and then prints the random number. It can do 2d6 etc. It breaks if you type q or quit.
import random
import string
import re
from random import randint
def code_gate_3(str1):
if str1.startswith("d") and three == int:
return True
else:
return False
def code_gate_1(str1):
if str1.startswith(one):
return True
else:
return False
def code_gate_2(str2):
pattern = ("[0-9]*[d][0-9]+")
vvhile_loop = re.compile(pattern)
result = vvhile_loop.match(str1)
if result:
print ("correct_formatting")
else:
print ("incorrect_formattiing")
while True:
str1 = input("What dice would you like to roll? (Enter a d)")
one, partition_two, three = str1.partition("d")
pattern = ("[0-9]*[d][0-9]+")
if str1 == "quit" or str1 == "q":
break
elif str1.startswith("d") and three.isdigit():
print (random.randint(1, int(three)))
print (code_gate_2(str1))
elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
for _ in range(int(one)):
print (random.randint(1, int(three)
print (code_gate_2(str1))
elif (str1.isdigit()) != False:
break
else:
print (code_gate_2(str1))
print ("Would you like to roll another dice?")
print ("If not, type 'q' or 'quit'.")
print ("EXITING>>>___")
This is one of the easiest answer.
import random
def rolling_dice():
min_value = 1
max_value = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
print("Rolling dices...")
print("The values are...")
print(random.randint(min_value, max_value))
print(random.randint(min_value, max_value))
roll_again = input("Roll the dices again? ")
rolling_dice()