Python3: How to loop my dice roller program back to the start - python-3.x

Writing my first solo program with no help from teacher or group, a simple code that can act as a D&D dice roller for any type or number of dice a user requires.
I've been working on it for about four hours, and I'm stuck on the last thing I want to do which is loop it back to the beginning instead of just ending when a user doesn't reroll the already chosen dice, I'd like it so it starts again from the top so the player can input a new dice value and number of rolls generated without closing the program and rerunning it.
import random
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break

You might try something like:
import random
while True:
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled or 0 to exit: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
if max == 0:
break
if max < 0:
continue
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
Also, I would suggest renaming "min" and "max" as they are reserved keywords

Related

Python while loop through program not working

import random
replay = 1
while replay == 1:
replay = replay - 1
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
count = 0
score = 0
while count == 0:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again == "yes" or "YES":
replay = replay + 1
elif again == "no" or "NO":
break
This is my code, except it doesn't do what I want it to do. After you guess the correct number, it doesn't see to properly loop through the game again when you say yes or no. It just goes through the final if statement again.
Why won't it go through the entire program again?
Your code will always be evaluated to true
if again == "yes" or "YES":
Change it to:
if again.lower() == "yes":
Or
if again in ("YES", "yes", "y",..)
When it is true, you need to break from you second loop:
if again.lower() == "yes":
replay = replay + 1
break
When it is false, don't break but exit the program using:
exit()
Since replay is only used to exit your code, you don't need it if you use exit().
Code would then be:
import random
while True:
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
score = 0
while True:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again.lower() == "yes":
break
elif again.lower() == "no":
exit()

How To Limit The Times a User Could Input

Hi I'm a beginner Making a Game Where The Program Generates a random Number And The User Needs To Guess The Number. If They Fail 5 Times They Lose. I Need To Count How Many Times The User Can Enter And If It Reaches 5 And Print You Lost And restart.
Something Like This
cnt = 0
if cnt >= 5:
print("You Lost")
pass
You need :
import random
op_number = random.randint(1,20)
# print(op_number)
number = int(input("Guess a number between 1 to 20 : "))
count=0
while True:
if count == 5:
print("You Lose.")
break
count+=1
if op_number == number:
print("You won")
break
else:
print("Incorrect guess. {} attempts left.".format(5-count))
number = int(input("Guess a number between 1 to 20 : "))

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Dice Rolling Simulator

I am making a Dice rolling simulator in python to play dnd. I am very new to python so please don't make fun of me if my code is really bad.
import random
while 1 == 1:
dice = input("What kind of dice would you like to roll?: ") # This is asking what kind of dice to roll (d20, d12, d10, etc.)
number = int(input("How many times?: ")) # This is the number of times that the program will roll the dice
if dice == 'd20':
print(random.randint(1,21) * number)
elif dice == 'd12':
print(random.randint(1,13) * number)
elif dice == 'd10':
print(random.randint(1,11) * number)
elif dice == 'd8':
print(random.randint(1,9) * number)
elif dice == 'd6':
print(random.randint(1,7) * number)
elif dice == 'd4':
print(random.randint(1,5) * number)
elif dice == 'd100':
print(random.randint(1,101) * number)
elif dice == 'help':
print("d100, d20, d12, d10, d8, d6, d4, help, quit")
elif dice == 'quit':
break
else:
print("That's not an option. Type help to get a list of different commands.")
quit()
My original attention was just to let it be and not make a number variable, but then my brother reminded me that some weapons have multiple rolls and instead of just rolling more than once, I want to have an input asking how many times to roll the dice. The problem with my code right now is that it will randomize the number and then times it by two. What I want it to do is times the number of different integers and add them together.
Maybe use a for-loop and iterate over the number of times the user wants to roll the dice, while saving those to a list to display each roll of the die.
For example, the first die may look like this:
rolls = []
if dice == 'd20':
for roll in range(number):
rolls.append(random.randint(1,21))
print('rolls: ', ', '.join([str(roll) for roll in rolls]))
print('total:', sum(rolls))
Example output:
What kind of dice would you like to roll?: d20
How many times?: 2
rolls: 10, 15
total: 25
import random
print("Rolling the Dice....")
dice_number = random.randint(1, 6)
print(dice_number)
limit = 0
while limit <= 4:
ask = input("Would you like to roll again?? Yes or No ").upper()
limit = limit + 1
if ask == "YES":
print(random.randint(1, 6))
elif ask == "NO":
print("Thank You.")
break
else:
print("Thank You.")
break
else:
print("Limit Reached..TRY AGAIN!!")

What is the best possible way to loop this program

count = 0
while (count >4):
fixedcosts = float(input("Enter fixed costs: "))
salesprice = float(input("Enter the price for one unit: "))
variablecosts = float(input("Enter the variable costs for one unit: "))
contribution = float(salesprice)-float(variablecosts)
breakevenpoint = float(fixedcosts)/float(contribution)
roundedbreakevenpoint = round(breakevenpoint)
#Finds break even point
if int(roundedbreakevenpoint) < float(breakevenpoint):
breakevenpoint2 = int(roundedbreakevenpoint) + 1
print("Your break even point is ",int(breakevenpoint2),"units")
else:
print("Your break even point is ",int(roundedbreakevenpoint),"units")
#Finds number of units needed to make a profit
if int(roundedbreakevenpoint) < float(breakevenpoint):
breakevenpoint3 = int(roundedbreakevenpoint) + 2
print("To make a profit you need to sell ",int(breakevenpoint3),"units")
else:
int(roundedbreakevenpoint) >= float(breakevenpoint)
breakevenpoint4 = int(roundedbreakevenpoint) + 1
print("To make a profit you need to sell ",int(breakevenpoint4),"units")
decision = input("Would you like to restart the program?")
if decision == 'yes' or 'Yes':
count = count + 1
print("This program will now restart")
else:
print("This program will now be terminated")
print("Press enter to stop the program")
quit()
What is the best way to loop this code? I have tried while loop but I can't seem to be able to get it to work with a yes no answer.

Resources