Python for Beginners: Roll the dice - python

I have typed the code from this page PythonForBeginners
but if I execute it, it will go on forever and not ask me whether I want to roll the dices again. Did I miss something? Should this work?
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print "Rolling the dices..."
print "The values are...."
print random.randint(min, max)
print random.randint(min, max)
roll_again = raw_input("Roll the dices again?")

Well one way to do it is using a class like this.
import random
class RollTheDice(object):
def __init__(self):
self.min = 1
self.max = 6
super(RollTheDice, self).__init__()
def ask_something(self):
while True:
userInput = str(raw_input("Roll Again? Yes or No" + "\n"))
if (userInput == "Yes" or userInput == 'Y'):
self.rollDice()
else:
print("You didn't type 'Yes' or 'Y' no roll for you. Bye....")
exit()
def rollDice(self):
print "Rolling the dices..."
print "The values are...."
print random.randint(self.min, self.max)
print random.randint(self.min, self.max)
RollTheDiceObject = RollTheDice()
RollTheDiceObject.ask_something()
I exit the program if the user doesn't type "Yes" or "Y" with some more code you can make this smarter.
some information on the while loop - https://www.tutorialspoint.com/python/python_while_loop.htm

I've just been working on the same problem as a beginner. I made a few tweaks to your initial code, set out below, and it worked.
import random
min = 1
min = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print "You rolled..."
print random.randint (1,6)
roll_again = raw_input("Do you want to roll again?")
A more efficient and elegant solution would be the following:
import random
repeat = True
while repeat:
print ("You rolled", random.randint(1,6))
print ("Do you want to roll again? Y/N")
repeat = ("y" or "yes") in input().lower()

Related

How do I stop this from repeating?

I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?

When I run this code it repetitively rolls over and over again. How do I fix this?

import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
print (random.randint(min, max))
roll_again = raw_input("Want to roll again?");
You need to make sure that the user input is in the while loop, otherwise roll_again is permanently set to "yes" and you are stuck in an infinite loop.
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
print (random.randint(min, max))
roll_again = raw_input("Want to roll again?");
And the following is a more pythonic approach
import random
min = 1
max = 6
while True:
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
print (random.randint(min, max))
roll_again = input("Want to roll again?");
if roll_again != "yes" and roll_again != "y":
break
Because you're setting your loop to always be "yes". Thus its looping over and over and over until it becomes false which it will not.
Try this:
import random
while True:
min = 1
max = 6
roll_again = input("Do you want to roll again? Type: Yes or y")
if roll_again.lower() == "yes" or roll_again == "y":
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
This code will promt a user everytime after the roll to see if they want to roll again.

Calling a function in an if statement?

I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")
This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.
If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.

if statement doesnt work python 2.7 using if and while in function

I am using Python 2.7. The program generates a random number and asks the user to guess what it is. The while statements work good. The conditional if statement ends the program without following instructions of print followed by calling the function to see if the user wants to play again.
What makes an if statement not follow instructions? Is there a conflict with the later while statements?
# generate random number between 1 & 9
# have user guess the number, then
# tell them if they guessed too low,
# too high, or exactly right
# keep the game going until user types "exit"
# track how many guesses the user has taken, and when game ends, print it out
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
guessThis()
elif wieder == "N":
print ("Have a day")
elif wieder != "Y" or "N":
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
while findout > a:
print ("too high")
findout = int(input("Enter a number from 1 to 9 "))
i += 1
while findout < a:
print ("too low")
findout = int(input("Enter a number from 1 to 9 "))
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Two issues (might be more):
wieder != "Y" or "N": you can't do that, you probably meant to do: wieder not in ["Y", "N"]:
When you declare findout inside a function - it will not be recognized outside. If you want it to be accessed from the outside - create it outside and pass it to the function, or alternatively, make the function return the value that you want back to the caller. Same goes for i.
Comment: regards #1, since you already checked both for 'Y' and 'N', the last condition can be modified from elif wieder != "Y" or "N": to a simple else
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = raw_input("Do you wish to play again? Y or N ")
if wieder == 'Y':
guessThis()
elif wieder == 'N':
print ("Have a day")
elif wieder != 'Y' or 'N':
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
if findout > a:
print ("too high")
guessThis()
i += 1
if findout < a:
print ("too low")
guessThis()
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Replace guessThis() and everything after with this:
def guessThis():
findout = int(input("Enter a number from 1 to 9 "))
i = 1
#Keep going until win condition reached
while findout != a:
#too high guess
if findout > a:
print ("too high")
#too low guess
if findout < a:
print ("too low")
#get next guess
findout = int(input("Enter a number from 1 to 9 "))
i += 1
#We got out of the while, so the game is done :)
print ("You got it correct")
playAgain()
guessThis()
As yours is currently it will not work if the user guesses too high and then too low.
The main problem was that none of your code was executed in the right order cause your indents were off. You need to put the checking logic in the guessThis() function.
Also there is are issues on this function:
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
#need to reset a when playing again
a = random.randint(1, 9)
guessThis()
elif wieder == "N":
print ("Have a day")
#because we have already checked (Y || N), simple 'else' gives us (!Y && !N)
else:
wieder = input("Do you wish to play again? Y or N ")
The !"Y" or "N" doesn't work quite like you expect it does, and I assume you want a new value of a for a new game

Break from raw_input in while loop

I've written a very simple dice rolling script in Python. It'll allow you to roll three times. However, I don't know how to break out of the while loop and avoid the raw_input the final time.
#!/usr/bin/python
from random import randrange, uniform
def rollDice():
dice = randrange(3,18)
print ("You rolled: %s" % dice)
maxReRoll = 2
c = 0
reRoll = "y"
while reRoll in ["Yes", "yes", "y", "Y"]:
if c > maxReRoll:
break
else:
rollDice()
c+=1
reRoll = raw_input("Roll again? y/n ")
Just a little swap is needed.
while reRoll in ["Yes", "yes", "y", "Y"]:
rollDice()
c+=1
if c >= maxReRoll: # notice the '>=' operator here
break
else:
reRoll = raw_input("Roll again? y/n ")
This should work for you:
from random import randrange
def roll_dice():
dice = randrange(3,18)
print("You rolled: %s" % dice)
max_rolls = 2
c = 0
re_roll = "y"
while re_roll.lower() in ["yes", "y"] and (c < max_rolls):
roll_dice()
c += 1
if c != max_rolls:
re_roll = input("Roll again? y/n ")

Categories