Loop never seems to actually loop - python

print("Welcome to my dice game.")
print("First enter how many sides you would like your dice to have, 4, 6 or 12")
print("Then this program will randomly roll the dice and show a number")
#Introduction explaing what the game will do. Test 1 to see if it worked.
while True:
#starts a while loop so the user can roll the dice as many times as they find necessary
import random
#Imports the random function so the code will be able to randomly select a number
dice = int(input("Enter which dice you would to use,4, 6, or 12? "))
#set a variable for the amount of dice number
if dice == 12:
x = random.randint(1,12)
print("You picked a 12 sided dice. You rolled a " + str(x) + " well done")
#Test 2 see if it does pick a random number for a 12 sided di
elif dice == 6:
x = random.randint(1,6)
print("You picked a 6 sided dice. You rolled a " + str(x) + " well done")
#Test 3 see if it does pick a random number for a 6 sided di
elif dice == 4:
x = random.randint(1,4)
print("You picked a 4 sided dice. You rolled a " + str(x) + " well done")
#Test 4 see if it does pick a random number for a 4 sided di
else:
print("Sorry, pick either 12, 6 or 4")
#Test 5 tells the user that they can only pick 4, 6 or 12 if anything else is entered this error shows
rollAgain = input ("Roll Again? ")
if rollAgain == "no":
rollAgain = False
if rollAgain == "yes":
rollAgain = True
break
print ("Thank you for playing")
#if the user enters anything apart from yes y or Yes. The code ends here.
That is the code i have so far. However the code will never actually go to the beginning of the loop, no matter what i enter the code just displays "Thanks for playing" and ends. Can anyone please tell me where i have went wrong?

First, you should be using raw_input to get the user's selection. (assuming python 2) If you're using python 3 then input is fine and keep reading.
Anyway, it'll still quit when you type yes because you break out of the loop! You should move the break statement into the "no" case so it breaks out when you say you do not want to roll again.
rollAgain = raw_input ("Roll Again? ")
if rollAgain == "no":
break
You don't need to set rollAgain to true or false at all. With the above code, anything other than "no" is assumed to be "yes" but you can add checks for that easily.

The problem is that you break your loop when the user wants to roll the dice again. The loop should break when the player doesn't want to play again so you have to do :
http://pastebin.com/hzC1UwDM

Related

How to either restart or end a game

I am trying to insert code at the end of my game to either restart or end the game. I'm not quite sure what I'm missing here.
This is where I'm at:
print("NIM: The Python Game")
print("Hello! My name is AI (the clever computer). \nIn this game, 2 other players will play against me and each other. \nThe player to go first will randomly choose between 30 and 50 stones in a pile to start the game.")
print("She\He will also be the first to remove the first stones. \nPlayers will then take turns at removing between 1 and 3 stones from the pile until a player removes the final stone. \nThe player to remove the final stone is the winner.")
player1=str(input("\nPlayer 1, what is your name and MIT ID? "))
print("Hello, " + player1.capitalize())
player2=str(input("\nPlayer 2, what is your name and MIT ID? "))
print("Hello, " + player2.capitalize())
player3="The computer"
howMany=0
stonesNumber=0
while True:
stonesNumber=int(input("\nNEW GAME \nHow many stones do you want to start with (between 30 and 50), " + player1.capitalize() + "? "))
if stonesNumber <30:
print("The number must be between 30 and 50!")
elif stonesNumber >50:
print("The number must be between 30 and 50!")
else:
print("The number of stones is ", stonesNumber)
while True:
print("\nIt's your turn, ",player1.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
print("Numbers of stones left: " + str(stonesNumber))
if stonesNumber==0:
print(player1.capitalize()," wins.")
break
print("\nIt's your turn, ",player2.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
if stonesNumber==0:
print(player2.capitalize()," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nIt's my turn!")
if stonesNumber % 3==0:
howMany=2
else:
howMany=1
stonesNumber=stonesNumber-(howMany)
if howMany == 1:
print("The computer has taken 1 counter")
if howMany == 2:
print("The computer has taken 2 counters")
if stonesNumber==0:
print(player3," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nThe game is over!")
answer=str(input("\nDo you want to play again?(y/n)"))
if answer == "y" or "yes":
print("\nRestarting the game")
else:
break
print("\nThanks for playing the game!")
The condition if answer == "y" or "yes": does NOT check if answer equals "y" or equals "yes". Due to semantics of OR-Operator it "transposes" to a piece of code like if "yes":, which is always true. Therefore it will always restart your game.
You will need to change it to that:
if answer == "y" or answer == "yes":
I am assuming the problem you are having now is that you cannot escape the loop regardless of what you answer at the end of the game.
The reason your game can never escape the while loop is because of this line
if answer == "y" or "yes":
Your above if statement is made up of two parts:
if answer == "y" (Evaluates to true or false depending on answer)
if "yes" (Evaluates to true every time)
Since its an OR case, where either the result will be true/false OR true, you will always end up with if answer == "y" or "yes" as true.
Therefore, you will always be stuck in the loop.
As per felix's answer, your solution would be to evaluate if answer == "y" OR answer == "yes" instead

how to write dice rolling game project. this is my first project

did i write correct code
no1 = 1
no2 = 6
enter code here
dice = input("enter number: "):
no1 = int(input("enter number one: "))
no2 = int(input("enter number two: "))
print("you have enter "+str(no1))
print("you have enter "+str(no2))
if dice == "5":
print("you want to roll again")
elif dice == "6":
print("roll dice automatically")
check that you have not incorrectly formatted all of your question as code
There are many ways to write a dice rolling program. However, the simplest way would use a built-in library called random. Below I have fixed and cleaned the code:
import random # The libary used from generating random numbers
def dice_roll(): # function usedto reset the game
input("Press enter to roll the dice ")
print("The dice rolled: ", random.randint(0,6))
UserInputNew = input ("Would you like to roll again? ")
if UserInputNew == "5":
print("\n") # displays a blank line
dice_roll()
else:
print ("Thanks for playing!")
dice_roll() # loads the game
Above would do what you want. From your example above, you have loads of inputs which doesn't make sense from something like a dice roll. If you need help understanding certain bits of the code then I'll be more than happy to help.
help on this one
Alice, Bob and Carol have agreed to pool their Halloween candy and split it evenly among themselves. For the sake of their friendship, any candies left over will be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.
Write an arithmetic expression below to calculate how many candies they must smash for a given haul.

Python Roll dice with 2 parameters: Number of sides of the dice and the number of dice

This is the problem I have: Write a function roll dice that takes in 2 parameters - the number of sides of the die, and the number of dice
to roll - and generates random roll values for each die rolled. Print out each roll and then return the string
“That’s all!” An example output
>>>roll_dice(6,3)
4
1
6
That's all!
This is the code I have so far using a normal roll dice code:
import random
min = 1
max = 6
roll_dice = "yes"
while roll_dice == "yes":
print random.randint(min,max)
print random.randint(min,max)
print "That's all"
import sys
sys.exit(0)
Try this:
def roll_dice(sides, rolls):
for _ in range(rolls):
print random.randint(1, sides)
print 'That\s all'
This uses a for loop to loop rolls amount of times and prints a random number between 1 and sides each loop.
import random
def roll_dice(attempts,number_of_sides):
for i in range(attempts):
print(random.randint(1, number_of_sides))
print("thats all")
In a more advanced, you can have two parameters where you ask the users input to set the values and it will run the functions and give the numbers rolled, the sum and ask if the user wants to try again.
#Import 'random' module
import random
def main():
#Get values from user to determine slides_per_dice and number_of_die.
sides_per_die = get_value(1,50, 'How many sides should the dice to have
(1-50): ', 'That is not a correct response, enter a value between 1 and
50')
number_of_dice = get_value(1,10, 'How many dice should be rolled (1-10):
', 'That is not a correct response, enter a value between 1 and 10')
#Simulate rolling specified number of dice with specified sides on each
dice.
outcome = rolling_dice (sides_per_die, number_of_dice)
#Asking user if they would like to roll again.
roll_again = input("Would you like to play again (y/n): ") .lower()
while roll_again != 'n':
if roll_again =='y':
main()
else:
print('Error: please enter "y" or "n".')
roll_again = input("Would you like to play again (y/n): ")
#Final message if user ends the game.
print('Thanks for playing.')
#Asking user for side_per_dice and number_of_nice input.
def get_value(lower_limit, upper_limit, prompt, error_message):
number = int(input(prompt))
while number < lower_limit or number > upper_limit:
print(error_message)
number = int(input(prompt))
return number
#Determining the outcome of the rolls and summing up total for all rolls.
def rolling_dice (sides_per_die, number_of_die):
roll_sum = 0
print('Rolling dice .....')
for roll in range (number_of_die):
result = random.randint(1, sides_per_die)
roll_sum += result
print(result, end = " ")
print(f'\nThe sum of all dice rolled is {roll_sum}')
main()

Converting input to lower case to accept in a while loop

I am trying to create a program that takes an input and will convert whatever input for example Yes / YES to lower case to be accepted in the while loop below. Ive tried to do it but doesnt work. Any idea?
#Import the random function - This only needs to be imported once.
import random
#Use a while loop to allow the user to repeat the process
repeat = "YES"
while repeat == "yes":
#User is able to input which sided dice they want to throw.
dice = input("What side dice do you want to use? 4, 6, or 12?\n")
#4 sided
if dice == "4":
#Outputs what sided dice has been chosen and the score thay they rolled.
print(dice, "sided dice chose.\nYou rolled a", random.randint(1,4))
#6 sided
elif dice == "6":
print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,6)))
#12 sided
elif dice == "12":
print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,12)))
#Incorrect value entered
else:
#Informs the user that the number they have chosen is not a valid option.
print(dice, "is not a valid choice")
#Asks user if they want to use the program again.
print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
repeat = input()
Your code will never even enter the while loop, as you set repeat to "YES" and then immediately check if it is "yes", which it isn't.
I would have solved this in another way
while True:
dice = input(....)
#etc
repeat = ''
while repeat.lower() not in ['yes', 'no']:
repeat = input('Do you want to use the program again? (yes/no)?')
if repeat.lower() == 'no':
break
This would ask the user to input yes or no, and keep on asking until yes or no in supplied.
Daniel is entirely correct. The 'YES' at the beginning of the code should be formatted as 'yes' because clearly 'YES does not equal 'yes' and thus the while loop won't run at all

Simulate rolling dice in Python?

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()

Categories

Resources