I am completely new to coding and trying to write somewhat of a dice rolling program/game.
I want the program to ask how many dice the user wants to roll, and how many times they can "retry" to roll the dice per one game. After the user has rolled all of their tries the program jumps back to the first question.
So this is what i´ve got so far:
import random
def roll(dice):
i = 0
while i < dice:
roll_result = random.randint(1, 6)
i += 1
print("You got:", roll_result)
def main():
rolling = True
while rolling:
answer = input("To throw the dice press Y if you want to stop press any key")
if answer.lower() == "Y" or answer.lower() == "y":
number_of_die = int(input("How many dice do you want to throw? "))
roll(number_of_die)
else:
print("Thank you for playing!")
break
main()
This works but i am not sure though where to begin to make the program ask for how many tries one player gets per game so that if they are unhappy with the result they can roll again.
Been trying for a while to figure it out so appreciate any tips!
Here's a simpler approach-
from random import randint
def roll(n):
for i in range(n):
print(f"You got {randint(1, 6)}")
def main():
tries = int(input("Enter the number of tries each player gets: "))
dice = int(input("How many dice do you want to roll? "))
for j in range(tries):
roll(dice)
roll_again = input("Enter 'y' to roll again or anything else to quit: ")
if roll_again.lower() != 'y':
break
main()
Related
My goal is to create a dice roller which lets the user choose both the number of dice and number of sides.
The problem started when I made it possible for the user to go through the process again (select number of dice and of sides). Now it doesn't display the result of anything besides the first die and, when the user types "n" and function breaks, sometimes it does, and sometimes it keeps going. This last part makes sense because the function "start" comes next. I haven't figured a way to truly finish running the script.
from random import randint
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
# variable "roll" generates random number between 1 and user input
roll = randint(1, n_sides)
# variable "roll" is appended to the previously created empty list "rolls"
rolls.append(roll)
# enumerates however many results there was
i += 1
# prints the end result to the user
print("Result", i, ":", roll)
choice = input("Do you want to roll the dice again? (y/n)")
# if user input is "y", start over by running function "start"
if choice.lower() == 'y':
start()
# uses lower() so that lower case is allowed
elif choice.lower() == 'n':
# break terminates function
break
def start():
print()
try:
print("How many sides your dice has?")
n_sides = int(input().lower())
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
try:
print("How many dice do you want to use?")
n_dice = int(input().lower())
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
dice(n_sides, n_dice)
start()
Here's a better way to organize this. Have each function do one thing. When it has done its one thing, let someone else make the decisions.
Also, it's pointless to call lower() when all you want is integers.
from random import randint
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
# variable "roll" generates random number between 1 and user input
roll = randint(1, n_sides)
# variable "roll" is appended to the previously created empty list "rolls"
rolls.append(roll)
# prints the end result to the user
print("Result", i+1, ":", roll)
return rolls
def round():
print()
try:
n_sides = int(input("How many sides your dice has?"))
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
continue
try:
n_dice = int(input("How many dice do you want to use?"))
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
continue
print(dice(n_sides, n_dice))
while True:
round()
choice = input("Do you want to roll the dice again? (y/n)")
if choice.lower() == 'n':
break
What I understood is, you have n dices each having m sides and the user will roll all the dices per input.
Your code has the bug inside dice(n_sides, n_dice): function as you are executing all the statements in the for loop which is running same times the number of dices. Remember, indentation is important in python
Also, while you're taking input, you can use a while loop to force the user to input a valid number like this:
isNumeric = False
while(isNumeric == False):
try:
print("How many sides your dice has?")
n_sides = int(input().lower())
isNumeric = True
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
isNumeric = False
while(isNumeric == False):
try:
print("How many dice do you want to use?")
n_dice = int(input().lower())
isNumeric = True
# if something other than integers are typed by user
except ValueError:
print("This is not a whole number.")
To remove the bug in your dice function, you can do as follows:
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
# variable "roll" generates random number between 1 and user input
roll = randint(1, n_sides)
# variable "roll" is appended to the previously created empty list "rolls"
rolls.append(roll)
# prints the end result to the user
print("Result of Dice Number", i+1, ":", roll)
choice = input("Do you want to roll the dice again? (y/n)")
# if user input is "y", start over by running function "start"
if choice.lower() == 'y':
start()
# uses lower() so that lower case is allowed
This will smoothly solve all of your problems!
First of all, I would use exit() instead of break. Break can be used in loops (see here: https://www.programiz.com/python-programming/break-continue)
Secondly, use a while loop for the yes or no question, like:
while True:
a = input("Do you want to roll the dice again? (y/n)")
if a == "y":
start()
continue
elif a == "n":
exit()
else:
print("Enter either y/n")
So if you don't want to change the logic of the code:
from random import randint
def dice(n_sides, n_dice):
rolls = []
for i in range(n_dice):
roll = randint(1, n_sides)
rolls.append(roll)
i += 1
print("Result", i, ":", roll)
while True:
a = input("Do you want to roll the dice again? (y/n)")
if a == "y":
start()
continue
elif a == "n":
exit()
else:
print("Enter either y/n")
def start():
while True:
try:
print("How many sides your dice has?")
n_sides = int(input())
break
except ValueError:
print("This is not a whole number.")
while True:
try:
print("How many dice do you want to use?")
n_dice = int(input())
break
except ValueError:
print("This is not a whole number.")
dice(n_sides, n_dice)
if __name__ == '__main__':
start()
Edit:
you need to import exit to do this: from sys import exit
I am trying to create a dice game but after the game is complete I would like it to start again with the question "Do you want to roll the dice again" instead of going to the first statement. This is as far as I have gotten and am not sure what to do to correct the code. Any help is much appreciated!!
import random
dice_number = random.randint(1, 6)
play = True
while play:
roll_dice = input("Would you like to roll the dice?")
if roll_dice.lower() == 'yes':
print(dice_number)
else:
print("Let us play later then.")
break
again = str(input("Do you want to roll the dice again?"))
if again == 'yes':
print(dice_number)
if again == 'no':
play = False
print("It has been fun playing with you.")
continue
Try this:
import random
dice_number = random.randint(1, 6)
play = True
first = True
while play:
again = input("Would you like to roll the dice?") if first else str(input("Do you want to roll the dice again?"))
first = False
if again.lower() == 'yes':
print(dice_number)
else:
print("Let us play later then.")
break
You can try this one.
import random
dice_number = random.randint(1, 6)
play = True
started = False
while play:
if started:
again = str(input("Do you want to roll the dice again?"))
if again == 'yes':
print(dice_number)
elif again == 'no':
play = False
print("It has been fun playing with you.")
break
else:
roll_dice = input("Would you like to roll the dice?")
if roll_dice.lower() == 'yes':
started = True
print(dice_number)
else:
print("Let us play later then.")
break
Sample Output:
Would you like to roll the dice?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?yes
3
Do you want to roll the dice again?no
It has been fun playing with you.
I was writing a Roll the dice game but when I get the question "Would you like to roll the dice again?" and I say "no" it rolls anyway. I'm guessing it has something to do with the answer variable. However, I would like it to print "maybe next time" instead. Can you help me? Here's my code:
import random
def response():
if answer == "yes" or answer == "Yes" :
rolldice()
else:
print("Maybe next time!")
def rolldice():
randomnumb = random.randrange(1,7)
print("You got number " + str(randomnumb) + "!")
answer = input("Would you like to roll the dice again? \n ")
response()
answer = input("Would you like to roll the dice? \n")
response()
Try this. You have to pass answer as argument to the function response:
import random
def response(answer):
if answer == "yes" or answer == "Yes" :
rolldice()
else:
print("Maybe next time!")
def rolldice():
randomnumb = random.randrange(1,7)
print("You got number " + str(randomnumb) + "!")
response(input("Would you like to roll the dice again? \n "))
response(input("Would you like to roll the dice? \n"))
I am trying to make a guessing game in python 3 using jupyter notebook whereby two people take turns to guess a number between 1 and 10. What I don't want is that the answer is immediately given like this:
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
if player_input == rand_num:
print('You won!')
else:
print('You lost!')
print('The random number was: {}'.format(rand_num))
Instead I want everyone to guess and then the answer is given so that everyone has a fair chance at guessing the number. I tried the following here but this doesn't seem to work because I think the player_input doesn't account for every single player. So when one player got the number right, python prints that every player got the number right.
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
for player in players:
if player_input == rand_num:
print('You won {}!'.format(player))
else:
print('You lost {}!'.format(player))
print('The random number was: {}'.format(rand_num))
How can I make this work using lists and for loops?
Loops are probably not suitable for what you want to achieve, you better go with simple case selection by storing the answers of both players:
from random import randint
rand_num = randint(1,10)
players = ['player_1', 'player_2']
player_inputs = []
for player in players:
player_input = int(input('What is your guess {}? '.format(player)))
player_inputs.append(player_input)
if rand_num in player_inputs:
if player_inputs[0] == player_inputs[1]:
print('You both won!')
elif player_inputs[0] == rand_num:
print('You won {}!'.format(players[0]))
print('You lost {}!'.format(players[1]))
elif player_inputs[1] == rand_num:
print('You won {}!'.format(players[1]))
print('You lost {}!'.format(players[0]))
else:
print('You both lost')
print('The random number was: {}'.format(rand_num))
Every time I enter 4, 6 or 12 it doesn't accept it. Why? The code looks fine to me. Please tell me how to correct or what to change.
import random
def roll_the_dice():
print("Roll The Dice")
print()
repeat = True
while repeat:
number_of_sides = input("Please select a dice with 4, 6 or 12 sides: ")
if (number_of_sides in [4,6,12] and len(number_of_sides) == 0 and
number_of_sides == int):
user_score = random.randint(1,number_of_sides)
print("{0} sided dice thrown, score {1}".format(
number_of_sides,user_score))
roll_again = input("Do you want to roll the dice again? ")
roll_again.lower()
if roll_again == "no":
print("Have a nice day")
repeat = False
elif len(roll_again) == 0:
print("Error please type 'yes' or 'no'")
roll_again = input("Do you want to roll the dice again? ")
else:
print("You have entered an incorrect value, please try again")
number_of_sides = input("Please select a dice with 4, 6 or 12 sides: ")
In Python 3, when using input(), it returns a string. Thus, you would have something like "4". And "4" is not 4.
So in your script, specifically at the if number_of_sides in [4,6,12], it will always be False, because you are really saying if "4" in [4,6,12] (I'm just doing 4 as an example).
Convert the string to an integer:
>>> int("4")
4
It also looks like you are trying to determine if an input was given. len(...) == 0 is not needed. You can just say if number_of_sides. Because an empty string is False, and if one was entered, then the if-statement will not execute.
Also, number_of_sides == int is not the way to check if an object is an integer. Use isinstance():
>>> isinstance("4", int)
False
>>> isinstance(4, int)
True
Some other tiny things:
.lower() does not sort the string in place, as strings are immutable in python. You might just want to attach .lower() onto the end of the input().
You might also want to use a while loop for your second input. Observe:
roll_again = ''
while True:
roll_again = input('Do you want to roll the dice again? ')
if roll_again in ('yes', 'no'):
break
print("You have entered an incorrect value, please try again")
if roll_again == "no":
print("Have a nice day")
repeat = False
else:
print("Let's go again!")
Haidro gave you the reason, but here is a different way to approach your problem:
def get_dice_size():
dice_size = input('Enter the number of sides on the dice: ')
while dice_size not in ['4','6','12']:
print 'Sorry, please enter one of 4, 6 or 12:'
dice_size = input('Enter the number of sides on the dice: ')
return int(dice_size)
def main():
dice_size = get_dice_size()
repeat = True
while repeat:
print('Rolling the dice...')
user_score = random.randint(1,dice_size)
print("{0} sided dice thrown, score {1}".format(dice_size,user_score))
roll_again = input("Do you want to roll the dice again? ")
if roll_again.lower() == 'yes':
dice_size = get_dice_size()
else:
repeat = False
print('Thank you for playing!')
You should change your script like shown below.
This is the important part:
try:
number_of_sides = int(input("Please select a dice with 4, 6 or 12 sides: "))
except ValueError:
wrong = True
Convert to int right at input time with int(input("…. If the user enters anything that cannot be converted into an integer Python will raise a ValueError. You can catch this, show a message and go to the start of the loop with continue.
import random
def roll_the_dice():
print("Roll The Dice")
print()
repeat = True
while repeat:
wrong = False
try:
number_of_sides = int(input("Please select a dice with 4, 6 or 12 sides: "))
except ValueError:
wrong = True
if wrong or number_of_sides not in [4,6,12]:
print("You have entered an incorrect value, please try again")
continue
else:
user_score = random.randint(1,number_of_sides)
print("{0} sided dice thrown, score {1}".format(
number_of_sides,user_score))
roll_again = input("Do you want to roll the dice again? ")
if roll_again in ('y', 'Y', 'yes', 'Yes'):
continue
else:
print("Have a nice day")
repeat = False
roll_the_dice()