Ending an infinite loop issue (Python) - python

I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issue.
def main():
while True:
NoChild = int(0)
NoAdult = int(0)
NoDays = int(0)
AdultCost = int(0)
ChildCost = int(0)
FinalCost = int(0)
print ("Welcome to Superslides!")
print ("The theme park with the biggest water slide in Europe.")
NoAdult = int(raw_input("How many adults are there?"))
NoChild = int(raw_input("How many children are there?"))
NoDays = int(raw_input("How many days will you be at the theme park?"))
WeekDay = (raw_input("Will you be attending the park on a weekday? (Yes/No)"))
if WeekDay == "Yes":
AdultCost = NoAdult * 5
elif WeekDay == "No":
AdultCost = NoAdult * 10
ChildCost = NoChild * 5
FinalCost = (AdultCost + ChildCost)*NoDays
print ("Order Summary")
print("Number of Adults: ",NoAdult,"Cost: ",AdultCost)
print("Number of Children: ",NoChild,"Cost: ",ChildCost)
print("Your final total is:",FinalCost)
print("Have a nice day at SuperSlides!")
again = raw_input("Would you like to process another customer? (Yes/No)")
if again =="No":
print("Goodbye!")
return
elif again =="Yes":
print("Next Customer.")
else:
print("You should enter either Yes or No.")
if __name__=="__main__":
main()

You can change the return to break and it will exit the while loop
if again =="No":
print("Goodbye!")
break

Instead of this:
while True:
You should use this:
again = True
while again:
...
usrIn = raw_input("Would you like to process another customer? y/n")
if usrIn == 'y':
again = True
else
again = False
I just made it default to False, but you can always just make it ask the user for a new input if they don't enter y or n.

I checked your code with python 3.5 and it worked after I changed the raw_input to input, since input in 3.5 is the raw_input of 2.7. Since you're using print() as a function, you should have an import of the print function from future package in your import section. I can't see no import section in your script.
What exactly doesn't work?
Additionally: It's a good habit to end a command line application by exiting with an exit code instead of breaking and ending. So you would have to
import sys
in the import section of your python script and when checking for ending the program by the user, do a
if again == "No":
print("Good Bye")
sys.exit(0)
This gives you the opportunity in case of an error to exit with a different exit code.

Change this code snippet
if again =="No":
print("Goodbye!")
exit() #this will close the program
elif again =="Yes":
print("Next Customer.")
exit()#this will close the program
else:
print("You should enter either Yes or No.")

Related

not restarting for program and input integer not working

I'm trying to develop a program wherein at the finish of the game the user will input "Yes" to make the game restart, while if the user inputed "Not" the game will end. For my tries, I can't seem to figure out how to make the program work. I'm quite unsure if a double while True is possible. Also, it seems like when I enter an integer the game suddenly doesn't work but when I input an invalidoutpit the message "Error, the inputed value is invalid, try again" seems to work fine. In need of help, Thank You!!
import random
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
while True:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
else:
guess1=int(guess[0])
guess2=int(guess[1])
guess3=int(guess[2])
guess4=int(guess[3])
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
answer=input("Would you like to play again? (Yes or No) ")
if answer==Yes:
print ('Yay')
continue
else:
print ('Goodbye!')
break
Wrap your game in a function eg:
import sys
def game():
#game code goes here#
Then at the end, call the function to restart the game.
if answer=='Yes': # You forgot to add single/double inverted comma's around Yes
print ('Yay')
game() # calls function game(), hence restarts the game
else:
print ('Goodbye!')
sys.exit(0) # end game
try this
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
gueses=[]
while len(gueses)<=3:
try:
P1=="O" or P2=="O" or P3=="O" or P4=="O"
print("Here is your Clue :) :", P1,P2,P3,P4)
guess=int(input("\nTry and Guess the Numbers :). "))
gueses.append(guess)
except ValueError:
print("Error, the inputed value is invalid, try again")
continue
guess1=gueses[0]
guess2=gueses[1]
guess3=gueses[2]
guess4=gueses[3]
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
if P1=="x" and P2=="x" and P3=="x" and P4=="x":
print("you won")
else:
print("YOUE LOSE")
print("TRUE ANSWERS", A1,A2,A3,A4)
print("YOUR ANSWER", gueses)
game()
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print ('Yay')
game()
else:
print ('Goodbye!')
The previous answers are good starts, but lacking some other important issues. I would, as the others stated, start by wrapping your game code in a function and having it called recursively. There are other issues in the guess=int(input("\nTry and Guess the Numbers :). ")). This takes one integer as the input, not an array of integers. The simplest solution is to turn this into 4 separate prompts, one for each guess. I would also narrow the scope of your error test. I've included working code, but I would read through it and make sure you understand the logic and call flow.
import random
def game():
A1=random.randint(0,9)
A2=random.randint(0,9)
A3=random.randint(0,9)
A4=random.randint(0,9)
P1="O"
P2="O"
P3="O"
P4="O"
while True:
if P1=="O" or P2=="O" or P3=="O" or P4=="O":
print("Here is your Clue :) :")
print(P1,P2,P3,P4)
try:
guess1=int(input("\nGuess 1 :). "))
guess2=int(input("\nGuess 2 :). "))
guess3=int(input("\nGuess 3 :). "))
guess4=int(input("\nGuess 4 :). "))
except ValueError:
print("Invalid Input")
continue
if guess1==A1:
P1="X"
else:
P1="O"
if guess2==A2:
P2="X"
else:
P2="O"
if guess3==A3:
P3="X"
else:
P3="O"
if guess4==A4:
P4="X"
else:
P4="O"
else:
print("Well Done! You Won MASTERMIND! :D")
break
answer=input("Would you like to play again? (Yes or No) ")
if answer=="Yes":
print('Yay')
game()
else:
print('Goodbye!')
game()

invalid syntax for "from import random"

when I try to run this module
from import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart = Yes or y:
guessnum()
else:
end()
I get invalid syntax highlighting the import.
what is the issue?
I have already tried import random but it doesn't seem to want to work
Your code is full of errors. I have fixed indentation and other syntax issues.
You don't need to use from, just use import random.
Here is the code
import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart == "Yes" or "y":
guessnum()
else:
end()
Fixed your indentation, spelling, capitalization, insertion of unnecessary spaces and comparing between a string and int which would always be false.
Also added str.title to allow for all types of capitalization for restart
import random
import sys
def guessnum():
random_num = random.randint(1,6)
answer = int(input("What do you think the number is? "))
if answer == random_num:
print("Good job. you are correct!")
else:
print("Incorrect. Better luck next time. The number was %d" % random_num)
restart = input("Would you like to try again? ")
if restart.title() in ["Yes", "Y"]:
guessnum()
else:
end()
def end():
print("Goodbye!")
sys.exit(0)
guessnum()

Why isn't this code repeating? Python 3.3

This is a code that I have used when repeating a sequence I have used but it doesnt seem to be working can anyone see any problems?The code is for a currency converter. Im using Python 3.3
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()
Edit,This is the rest of the code:
if userChoice == "1":
userUSD = float(input("Enter the amount of USD you wish to convert.\n"))
UK = userUSD * 0.62
print("USD", userUSD, "= ", UK, "UK")
elif userChoice == "2":
UK = float(input("Enter the amount of UK Currency you wish to convert.\n"))
userUSD = UK * 1.62
print("UK", UK, "= ", userUSD, "USD")
def doagain():
userDoAgain = raw_input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()
Generally speaking, using recursion to handle a repeated control flow in Python is a bad idea. It's much easier, and less problematic to use loops instead. So, rather than defining a function doagain to ensure you get an answer to your question about running again, I suggest using a while loop. For the larger function that you'll be repeating, I suggest using a loop as well.
def repeat_stuff():
while True: # keep looping until told otherwise
# do the actual stuff you want to do here, e.g. converting currencies
do_stuff_once()
while True: # ask about doing it again until we understand the answer
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain.lower() == "yes":
break # go back to the outer loop
elif userDoAgain.lower() == "no":
print("Thank you for using this program")
return # exit the function
else:
print("Error: You entered invalid information.")
Note that I've changed the checks of the yes/no input strings to be case insenstive, which is a rather more user friendly way to go.
You are using recursion (the function calls itself) while it may be much nicer to just wrap the code you want to repeat in a while loop.
Example of this usage:
userContinue = "yes"
while (userContinue == "yes"):
userInput = input("Type something: ")
print("You typed in", userInput)
userContinue = input("Type in something else? (yes/no): ").lower()
Probably you need to use the function "raw_input" instead of only input.

Why will this program not work in the shell, but work in my IDE?

Im having a problem with a dice roller program (text for now but eventually graphical). It will not work in anything except for the IDE I use, Wing IDE 101 4.1. The error i get flashes too fast for me to read, but i will try to take a screenshot of it. (I will edit this post if i get a screenshot.)
Here is the program:
import random
#variables
available_dice = "D20"
main_pgm_start = False
#definitions of functions
def diePick():
print("Pick a die. Your choices are: ", available_dice)
print("")
which_dice = input("")
if which_dice == "D20" or which_dice == "d20":
rollD20()
else:
print("Error: Please try again")
print("")
diePick()
def rollD20():
print("Rolling D20 .... ")
print("")
d20_result = random.randrange(1, 20)
print("You have rolled a ", d20_result)
print("")
print("Would you like to roll again?")
print("")
y = input("")
if y == "y" or y == "Y" or y == "yes" or y == "Yes":
print("")
diePick()
def MainProgram():
print("Benjamin Ward's Random D&D Dice Roller")
print("")
x = input(" Press Enter to Continue")
print("")
diePick()
MainProgram()
You can redirect the log to the text file with "logging" module if my memory serves.
I dont think input() does what you expect it to. input reads a line of text, then executes it (as python).
I think what you want is more along the lines of stdin.readline(). To use it, you will have to from sys import stdin at the top, then replace all occurences of input with sys.readline(). Note also that this will return a newline at the end, which you have to account for.

How to restart a simple coin tossing game

I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.

Categories