Continue outside of loop, dice rolling script - python

I'm making a dice rolling game. The following code produces an error, saying "continue outside of loop":
import random
repeat="y" or "yes"
while repeat == "y" or "yes"
print("Rolling the dice")
print(random.randint(1,6))
repeat = input("Do you wanna roll again Y/N?").lower()
if repeat =="y" or "yes":
continue
else:
print("Thanks for rolling")
break
Why am I getting this error?

You cannot affect 2 walues as teh same time, chose "y" or "Y" in your expressions.
repeat="y"
while (repeat == "y") or (repeat == "yes"):
You have to check your indentation too,
repeat = input has to be inside the loop, so you get a new input to check each time.
The final print can be put outside the loop at the very end.
Here is a working example, and you can type anything starting with "y"/"Y" to continue rolling:
import random
repeat="y"
while (repeat[0]) == "y":
print("Rolling the dice")
print(random.randint(1,6))
repeat = input("Do you wanna roll again Y/N?").lower()
print("Thanks for rolling")

Related

Python function not working as I expected it to

I am new to Python and writing a program for a number guessing game. Here's the code:
import random
import math
def guessing_game_func():
name = input("Enter your name: ")
print("Welcome ", name)
lower_bound = 0
upper_bound = 50
#generating random number between 0 and 50
random_number = random.randint(lower_bound, upper_bound)
min_guessing_num = int(math.log(upper_bound - lower_bound + 1, 2))
print("INSTRUCTION: Guess a number between 0 and 50"
"\nHOT means you are close to the correct number and COLD means you are far from it")
print("You have only ", round(min_guessing_num), "tries")
#initializing number of guesses
count = 0
while count < min_guessing_num:
count += 1
guess = int(input("Guess a number: "))
if random_number == guess:
print("Congratulations. You guessed correctly after", count, "tries")
break
elif random_number > guess:
print("Hot")
elif random_number < guess:
print("Cold")
if count >= min_guessing_num:
print("Fail! The number is", random_number)
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
#if decision == "yes":
#guessing_game_func()
if decision == "no":
print("Close IDE")
guessing_game_func()
When I run this code, in the case where the user selects No, the game starts again but I do not want it to.
I just want it to print Close IDE and that should be it. However, the game starts again and I know this is because I am calling the function after it, but if I do not do that, then nothing will happen. What I mean by this is that, the code will run and all I'll see is Process finished with exit code 0
How do I fix this please?
The problem you have is with the loop that calls your function recursively:
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
if decision == "no":
print("Close IDE")
You have the recursive call which effectively implements a loop, and a while loop around that. When the inner call returns, remember that decision does not change within the outer function's while loop. That means that another call will be made and the loop will continue forever.
The simple solution is to decide whether you want to iterate via loop or recursion. I would recommend the former, but since you've already chosen the latter, just replace the while loop with a simple if:
decision = ""
while decision not in {"yes", "no"}:
decision = input("Do you wish to play again? YES or NO").lower()
if decision == "yes":
guessing_game_func()
else:
print("Close IDE")
Mad Physicist's answer covers the why does this happen and suggests a simple fix. However, I'd discourage you from using recursion to implement a replayed game. Instead, move the logic that decides whether to replay a game outside the function that implements the game logic.
def guessing_game_func():
...
while count < min_guessing_num:
...
# The function ends immediately after this while loop
# Now we're OUTSIDE the function
# Initialize decision to "yes", so the while loop is entered by default
decision = "yes"
while decision == "yes":
guessing_game_func()
decision = input("Do you wish to play again? YES or NO").lower()
if decision == "no":
print("Close IDE")
This way, you aren't limited to the recursion limit and can replay as many times as you like, since the next call of guessing_game_func only happens after the first call has ended.
I'm not sure why you want to print Close IDE only when "no" is entered -- what if decision is something other than "yes" and "no"? If you want to force decision to be one of those two options, you can pop it in another while loop, as shown in Asking the user for input until they give a valid response:
while decision == "yes":
guessing_game_func()
while True:
decision = input("Do you wish to play again? YES or NO").lower()
if decision in ("yes", "no"):
break # Acceptable input, so break out of the infinite loop
# Close IDE can be unguarded by an `if`, because the only way to get here is to enter "no" when asked for decision
print("Close IDE")
import random
import math
def guessing_game_func():
name = input("Enter your name: ")
print("Welcome ", name)
lower_bound = 0
upper_bound = 50
#generating random number between 0 and 50
random_number = random.randint(lower_bound, upper_bound)
min_guessing_num = int(math.log(upper_bound - lower_bound + 1, 2))
print("INSTRUCTION: Guess a number between 0 and 50"
"\nHOT means you are close to the correct number and COLD means you are far from it")
print("You have only ", round(min_guessing_num), "tries")
#initializing number of guesses
count = 0
while count < min_guessing_num:
count += 1
guess = int(input("Guess a number: "))
if random_number == guess:
print("Congratulations. You guessed correctly after", count, "tries")
break
elif random_number > guess:
print("Hot")
elif random_number < guess:
print("Cold")
if count >= min_guessing_num:
print("Fail! The number is", random_number)
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
break
#if decision == "yes":
#guessing_game_func()
if decision == "no":
print("Close IDE")
guessing_game_func()
Try this . I have added break after you call your function.now it works.

How to make a python calculator program repeat when the user requests it?

I am trying to write a python program that does addition, subtraction, division, and multiplication. When it completes an equation, it needs to ask the user if they want it to repeat the program to do another equation. I have already written the calculator, but how do I make it able to repeat at the user's request?
Would it work to make the calculator a function that could be called? How would I set that up to be able to repeat? I'm just starting out with python so any guidance on how to format this would be great. Thanks in advance!
Here is my calculator if that helps
amount= int(input("how many numbers will you be calculating?"))
list=[]
count=0
while count<amount:
s=int(input("enter a number:"))
list.append(s)
count= count+1
print("your numbers are: ",list)
choice= input("enter a choice exactly as written in this list: add, subtract, multiply, or divide: ")
if choice== "add" :
print("you chose addition")
sum=0
for i in list:
sum=sum+i
print("the sum of your numbers is: ", sum)
if choice== "subtract" :
print("you chose subtraction")
sum=list[0] + list [0]
for i in list:
sum= sum-i
print("the difference between your numbers is: ",sum)
if choice== "multiply":
print("you chose multiplication")
sum=1
for i in list:
sum=sum*i
print(sum)
if choice== "divide":
print("you chose division")
sum=list[0]*list[0]
for i in list:
sum=sum/i
print(sum)
You could wrap it in a while True: loop and break out of it at the end of the code. For example:
while True:
# Code here
if input("Do you want to calculate something else (y/n)? ") != "y":
break
one simple way to do it is just as you said, make the calculator a function and then you can do something like this
while True:
print("Continue")
n = str(input())
if n == "Yes":
calculator() #funtion call for calculator
elif n == "No":
break
else:
print("Yes/No")
This is how I would do it, to make the code easier to understand but if you want you could just put the whole calculator on a loop or something else
The answer to do this is to ask if the player would like to repeat:
while True:
start_again = input("Would you like to calculate another thing? (y/n)")
if start_again == "y" or "yes":
use_calculator() #function that uses the calculator again
if start_again == "n" or "no":
exit() #closes program
break

Why does my code make me type "yes" or "no" twice to get the result I want instead of just once?

Why does this code make me type yes or no twice to get the result I want instead of just once?
This is for the python dice roll text game, btw...
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
answer = input()
if answer == ('yes'):print("OK, here we go!")
elif answer == ("no"):print("Sorry about that, please try again another time.")
I am entering into a python class on Monday, this is one of the more common types of beginners code (granted I spiced it up by changing the dice from 6 sided to 20 sided, but it's more fun that way...lol) that I have read in some of the python books and sites I have visited, so I wanted to kind of get my feet wet a bit before I start my class.
So, any idea why I have to type yes or no twice, hitting enter after each time, to get it to run properly?
For the record, I am on Win10 right now but I also mostly use Parrot Security OS (Linux)...
Thanks for any and all feedback which anyone can provide...I know it's probably a stupid noob mistake or oversight, since I don't really know or understand the basics, but the quicker I can grasp them the better...
Python's function input() asks for users to input and waits the answer. As it can be seen in your code, you're doing it two times:
roll_again = input("Would you like to play again?")
answer = input()
The variable roll_again is being redeclarated to the first user's input, then the variable answer is getting the second user's input. You maybe meant to do something like:
roll_again = input("Would you like to play again?")
answer = roll_again
But first of all, there is no need to create an answer variable, you could simply use the roll_again on the if. Also the if statement is out of the while so your code might not work as you're trying to anyways~ (it will re-roll if user inputs yes but it will not print the message you're trying to; that will only happen when the user inputs no as that will go out of the while and blah blah blah)
This should be alright:
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
if roll_again == 'yes' or roll_again == 'y': print("OK, here we go!")
else: print("Sorry about that, please try again another time.")
Every time you call the input() function, it prompts for input. Since you call it twice for each iteration of your while loop, the user is prompted twice per iteration. You should instead only call the input() function once in your while loop.
You can also avoid using the answer variable if you just use the roll_again variable for your conditions for your if and elif.

I don't understand why this nested while loop works please python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
Hello everyone so I started working on a dice rolling game that rolls the dice then displays the value and asks if the user would like to re-roll. I know how to do all that but I wanted to put in a part that would loop if the user put in a value that was not Y(Yes) or N(No). So I created another while statement to accomplish this. If you input an invalid response the program asks you to type Y or N. Then if you type an invalid response again it keeps asking until the expected value is entered. Here is the code and I'll highlight the part where I don't understand. I commented why I think it works but I'm not sure. If someone could explain why it works I appreciate it thanks a lot!
import random
value = random.randint(1, 2)
run = True
while run:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = input("Do you want to play again? (Y or N) \n")
if answer == "Y":
continue
if answer == "N":
print("Thanks for playing \n")
exit()
# after you type an invalid response it's stored in variable answer
# the program then goes to answer2 input which asks please enter Y or N
# if the program then detects an invalid answer it goes back to the top
# of the while statement and uses answer ones response which is still
# an invalid response???? I'm guessing since answer is always invalid and the
# decisions only two options that are yes or no it goes back to the top of the 2nd while loop
# Not sure tho.
# 2nd while loop
while answer != "Y" or "N":
answer2 = input("Please enter Y or N \n")
while answer2 == "Y":
print("You roll a six sided dice \n")
print("The dice landed on " + str(value) + "\n")
answer2 = input("Do you want to play again \n")
continue
if answer2 == "N":
print("THanks for playing")
exit()
I've commented out why I think it works but
import random
value = random.randint(1, 2)
def getans():
while True:
answer = raw_input("Do you want to play again? (Y or N) \n")
if answer == "Y":
return True
elif answer == "N":
return False
else:
print ("Please enter Y or N \n")
continue
while True:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = getans()
if answer == True:
continue
elif answer == False:
print("Thanks for playing \n")
exit()
else:
print ("this will never run")

Dice game query While loop

I am trying to create a dice game using a while loop and if's. I have done this successfully however I am trying to figure out how to program the game so that if numbers 4,6 or 12 are not input it will state invalid choice and will ask diceChoice again.
Can anybody help?
So far I have...
rollAgain = "Yes" or "yes" or "y"
while rollAgain == "Yes" or "yes" or "y":
diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
if diceChoice == "4":
import random
print("You rolled a ", random.randint(1,4))
if diceChoice == "6":
import random
print("You rolled a ", random.randint(1,6))
if diceChoice == "12":
import random
print("You rolled a ", random.randint(1,12))
rollAgain = input ("Roll Again?")
print ("Thank you for playing")
Fixed While Loop, Tidied up all the repetition. Moved import statement to the top. Structured to allow more options for rollAgain and diceChoice.
import random
rollAgain = "Yes"
while rollAgain in ["Yes" , "yes", "y"]:
diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
if diceChoice in ["4","6","12"]:
print("You rolled a ",random.randint(1,int(diceChoice)))
else:
print "Please input 4,6, or 12."
rollAgain = input ("Roll Again?")
print ("Thank you for playing")
Doing this sort of assignment:
rollAgain = "Yes" or "yes" or "y"
Is unnecessary - only the first value will be inputted. Pick one for this variable; you only need one for its purposes.
This sort of assignment doesn't work here either:
while rollAgain == "Yes" or "yes" or "y":
It will again only check the first value. You either have to split it up like other posters have done, or use a different data structure that will incorporate them all like a list in the code above.
You should only import random once at the top
import random #put this as the first line
Your rollAgain declaration should only set it to one value
rollAgain = "yes" # the or statements were not necessary
You forgot to do rollAgain == in your subsequent conditionals, here is a simpler way
while rollAgain.lower().startswith("y"): #makes sure it starts with y or Y
To do an invalid input statement, you could use elif: and else: statements to keep it simple
if diceChoice == "4":
print("You rolled a ", random.randint(1,4))
elif diceChoice == "6":
print("You rolled a ", random.randint(1,6))
elif diceChoice == "12":
print("You rolled a ", random.randint(1,12))
else:
print("Invalid Input, please enter either 4, 6, or 12")
Your old while loop would never have exit because you were basically saying this
while rollAgain == "Yes" or True or True #because non-empty strings are treated as True
edit since you asked about in statements, here is a brief example
>>>5 in [1,2,3,4]
False
>>>5 in [1,2,3,4,5]
True
The in statement is similar to a contains() in other languages it checks to see if the variable is inside the list
Since 5 is not in the list [1,2,3,4] it returned False
however, 5 IS in the list [1,2,3,4,5] so it returns True
You could use this several places in your code, specifically if you want to make sure a variable is within a set of options. I didn't recommend it to keep it simple for you.
diceChoice = None
while diceChoice not in ["4","12","6"]:
diceChoice = input("enter choice of dice(4,6,12)")
print "You picked %d"%diceChoice
Just my take on it:
# If you are only using one function from random
# then it seems cleaner to just import that name
from random import randint
while True:
choice = int(input("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?\n:"))
# Using sets for 'in' comparisons is faster
if choice in {4, 6, 12}:
print("You rolled a", randint(1, choice))
else:
print("Please input 4, 6, or 12.")
# Make the input lowercase so that it will accept anything that can be
# interpreted as "yes".
if input("Roll Again?\n:").lower() not in {"yes", "y"}:
# End the game by breaking the loop
break
# You should use an input at the end to keep the window open to see the results
input("Thank you for playing!")

Categories