How to properly quit a program in python - python

Im a middle school student, and im starting to learn coding in python. I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type q. here what i have..
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = q
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = 'q'
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
print('Game Over')
print('Press Q to Quit')
if run == False:
choice = input('Press Q to Quit')
if choice == 'q'
import sys
exit(0)

Getting Q as input
Quit = int(input('Press Q to Quit')
You're asking for Q as the input, but only accepting an int. So take off the int part:
Quit = input('Press Q to Quit')
Now Quit will be whatever the user typed in, so let's check for "Q" instead of True:
if Quit == "Q":
Instead of sys.exit(0), you can probably just end your while look with break or just return if you're in a function.
Also, I don't recommend the name "Quit" for a variable that just stores user input, since it will end up confusing.
And remember that indentation is important in Python, so it needs to be:
if run == False:
choice = input('Press Q to Quit')
if choice == "Q":
# break or return or..
import sys
sys.exit(0)
That may just be a copy/paste error though.
Indentation and Syntax
I fixed the indentation and removed some extraneous code (since you duplicate the outer loop and some of the print statements) and got this:
print('How old do you thing Fred the Chicken is?')
number = 17
run = True
while run:
guess = int(input('Enter What You Think His Age Is....t'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
if run == False:
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q'
break
This gave me a syntax error:
blong#ubuntu:~$ python3 chicken.py
File "chicken.py", line 23
if choice == 'q'
^
SyntaxError: invalid syntax
So Python is saying there's something wrong after the if statement. If you look at the other if statements, you'll notice that this one is missing the : at the end, so change it to:
if choice == 'q':
So with that change the program runs, and seems to do what you want.
Some suggestions
Your instructions say "Press Q to Quit", but you actually only accept "q" to quit. You may want to accept both. Python has an operator called or, which takes two truth values (True or False) and returns True if either of them is True (it actually does more than this with values besides True and False, see the documentation if you're interested).
Examples:
>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
So we can ask for Q or q with if choice == "Q" or choice == "q":.
Another option is to convert the string to lower case and only check for q, using if choice.lower() == "q":. If choice was Q, it would first convert it to q (with the .lower()), then do the comparison.
Your number is always 17. Python has a function called random.randint() that will give you a random number, which might make the game more fun. For example, this would make the chicken's age between 5 and 20 (inclusive):
number = random.randint(5, 20)

There are many ways to exit certain things. For loops, it is using break, and for functions you can use return. However, for programs, if you wish to exit your program before interpretation finishes (end of the script) there are two different types of exit() functions. There is sys.exit() which is part of the sys module, and there is exit() and quit() which is a built-in. However, sys.exit() is intended for programs not in IDLE (python interactive), while the built-in exit() and quit() functions are intended for use in IDLE.

You can use the break statement to break out of a while loop:
while True:
guess = int(input("...")
# ...rest of your game's logic...
# Allow breaking out of the loop
choice = input("Enter Q to quit, or press return to continue")
if choice.lower() == "q":
break
That means the interpreter exits the while loop, continues looking for more commands to run, but reaches the end of the file! Python will then exit automatically - there's no need to call sys.exit
(as an aside, you should rarely use sys.exit, it's really just used to set non-zero exit-status, not for controlling how your program works, like escaping from a while loop)
Finally, the main problem with the code you posted is indentation - you need to put the appropriate number of spaces at the start of each line - where you have something like:
if run == False:
choice = input('Press Q to Quit')
It must be like this:
if run == False:
choice = input('Press Q to Quit')
Same with anything like while, for, if and so on.

Related

how to loop python code

I made the beginning of a basic text adventure game, and I want it to loop whenever you die, but any examples of code I see aren't working, and thorugh research i still cant find something that could work.
print("A tale of time version 0.0.1. by Tylan Merriam")
print("you awaken, the room is dark and you cannot see. the sheets on your
bed are damp, and you hear a faint dripping sound.")
ch0pg1 = input('>: ')
if ch0pg1 == 'turn on light':
print("you flip the light on, it turns out the dripping was from a leaky
pipe above you. you see a dresser(outisde of bed) a chair with something
glinting on it(outside of bed) and a window(outisde of bed)")
ch1p1 = input('>: ')
if ch1p1 == 'stand':
print('you stand up, the game isnt finished so this is all there is,
try saying stand at the first choice or anything else')
else:
print('sorry, but i have no fricking clue what that means')
elif ch0pg1 == 'stand':
print('since you cannot see, you bump your head on a brick and collapse.
as you think of your last words you realize the only thing that comes to
mind is wushtub.')
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
else:
print('shut it, your dead')
else:
print('I have no clue what that means,')
You can try embedding a while loop within a while loop kind of like this.
while(1):
while(1):
# some code
# also some code
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
else:
print('shut it, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
It simply creates a while loop for the game inside of a while loop. Break breaks out of the while loop while being ran, so it just exits and starts again. If the user chooses to quit, it stops the whole program.
You would think that we could create a function to make it easier, but when I tried breaking with a function it won't break, so you are going to have to keep pasting this in as of what I know. :P
Could do:
while (true)
{
//print statements
//whenever you die:
continue;
}
Well, you first need to define what you want to loop. Make a function called game() with your included code. Then this would work:
if diemessage == "lol":
print("something")
else:
print("Shut it, your dead")
game()

Creating A Class/Def For A If Else Statement Python

so I'm making a simple python program to ask maths questions. It is currently fully working but I want to try and condense the code down. The user has an option of 6 menu items to pick from, each one of these is an Addition, Subtraction, Multiplication..... And each one of them has the following code at the end to check if the user wants to carry on or try a different menu item.
contC = input()
if contC == "Y" or contC == "y":
cont = True
elif contC == "N" or contC =="n":
cont = False
This code is being in every menu choice, I want to create one method to be able to use for all of them, a class or a def? I've tried different things but can't seem to get anything to work.
Try using:
def AskMethod(Operation):
while True:
print("Do you want to do " + Operation.name)
Answer = input()
if Answer.lower() in 'yes':
Operation.use() # Or return Operation. However you do it
return False
elif Answer.lower() in 'no':
return True
else:
print("Please choose yes or no.")
for i in Ops:
Continue = Ask(i)
if Continue == False:
break
To use this, you will need to make an op class, and an ops array containing all of the operations you want. You must add self.name and self.use as well. Hope I helped.
Just make a method
def should_continue(user_input):
if user_input in ('y', 'Y'):
return True
if user_input in ('n', 'N'):
return False
raise ValueError("please enter y/n")
and then just
user_text = input()
cont = should_continue(user_input)

Input needing to be entered twice for my code to work

I'm fairly new to coding and have been assigned a class project, in this project to make a game I was trying to write a function that upon losing/dying the
def playAgain(): function would ask the user if they want to play again.
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
if input("> ").lower().startswith('yes')== True:
start()
elif input("> ").lower().startswith('no')== True:
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
This function 'should' ask the user if they want to play again and depending on if yes or no was entered it would either go to the function start() or exit.
The issue is that when the input is entered the first time it is seemingly ignored in the code and must be entered a second time for any thing to happen in the code.
This has confused me a fair amount so any input on how to resolve this issue would be greatly appreciated.
Side note - this issue doesn't appear to happen when yes is entered first meaning this is probably an issue with the elif or else statements
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
choice = input("> ")
if choice.lower().startswith('yes'):
start()
elif choice.lower().startswith('no'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
If you want to write it as a function then really you should return a value upon which to base your next step.
def playAgain():
while True:
ans = input("Do you want to play again? (yes or no) ")
if ans.lower().startswith('y'):
return True
elif ans.lower().startswith('n'):
return False
else:
print ("I don't understand what you mean?")
def start():
print ("game restarted")
if playAgain():
start()
else:
print ("Bye for now")
quit()
Note that startswith allows you to check just y and n rather than the full words yes and no
The solution is to assign a variable to the input and compare the variable as many times as you want.
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
inp = input("> ").lower()
if inp.startswith('y'):
start()
elif inp.startswith('n'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand, what do you mean?")

Code not printing what I seek

For the first bit, as I print out the "ask2", it prints out "exit" as opposed to the licence plate that it's supposed to be printing.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
ask2 = ""
plate = ""
if int(ask) == 1:
ask2 = ""
print("========================================================================")
while ask2 != 'exit':
ask2 = input ("Please enter it in such form (XX00XXX): ").lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
**print("The program, will determine whether or not the car "+str(plate),str(ask)+" is travelling more than the speed limit")**
Also I am looking for a few good codes that are good for appending (putting the data in a list), and printing.
This is what I've done;
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == ["y","Y"]:
do_the_quiz()
if tryagain==["n","N"]:
cars.append(plate+": "+str(x))
print(cars)
When you print ask2 it prints 'exit' because you set it to exit with ask2 = 'exit', and your loop cannot terminate before ask2 is set to 'exit'.
You could use ask2 for the user's input, and another variable loop to determine when to exit the loop. For example:
loop = True
while loop:
# ...
if valid.match(ask2) or ask2 == 'exit':
loop = False
I am not quite sure what your other block of code is trying to achieve, but the way that you test tryagain is incorrect, it will never be equal to a two element list such as ["y","Y"], perhaps you meant to use in?, This change shows one way to at least fix that problem:
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == "y":
do_the_quiz()
else:
cars.append(plate+": "+str(x))
print(cars)

How do I re-run code in Python?

I have this word un-scrambler game that just runs in CMD or the python shell. When the user either guesses the word correctly or incorrectly it says "press any key to play again"
How would I get it to start again?
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while input("Guess the phrase: ") != phrase:
print("Incorrect.") # Evaluate the input here
print("Correct") # If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
This is obviously quite simple, but the logic sounds like what you're after. A slightly more complex version of which, with defined functions for you to see where your logic would fit in, could be like this:
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while not game(phrase):
print("Incorrect.")
print("Correct")
main()
The output is identical.
Even the following Style works!!
Check it out.
def Loop():
r = raw_input("Would you like to restart this program?")
if r == "yes" or r == "y":
Loop()
if r == "n" or r == "no":
print "Script terminating. Goodbye."
Loop()
This is the method of executing the functions (set of statements)
repeatedly.
Hope You Like it :) :} :]
Try a loop:
while 1==1:
[your game here]
input("press any key to start again.")
Or if you want to get fancy:
restart=1
while restart!="x":
[your game here]
input("press any key to start again, or x to exit.")
Here is a template you can use to re-run a block of code. Think of #code as a placeholder for one or more lines of Python code.
def my_game_code():
#code
def foo():
while True:
my_game_code()
You could use a simple while loop:
line = "Y"
while line[0] not in ("n", "N"):
""" game here """
line = input("Play again (Y/N)?")
hope this helps
while True:
print('Your game yada-yada')
ans=input('''press o to exit or any key to continue
''')
if ans=='o':
break
A simple way is also to use boolean values, it is easier to comprehend if you are a beginner (like me). This is what I did for a group project:
restart = True
while restart:
#the program
restart = raw_input("Press any key to restart or q to quit!")
if restart == "q":
restart = False
You need to bury the code block in another code block.
Follow the instructions below:
Step 1: Top of code def main()
Step 2: restart = input("Do you want to play a game?").lower()
Step 3: Next line; if restart == "yes":
Step 4: Next line; Indent - main()
Step 5: Next line; else:
Step 6: Indent - exit()
Step 7: Indent all code under def main():
Step 8: After all code indent. Type main()
What you are doing is encapsulating the blocks of code into the main variable. The program runs once within main() variable then exits and returns to run the main varible again. Repeating the game. Hope this helps.
def main():
import random
helper= {}
helper['happy']= ["It is during our darkest moments that we must focus to see the light.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Do not go where the path may lead, go instead where there is no path and leave a trail.",
"You will face many defeats in life, but never let yourself be defeated.",
"The greatest glory in living lies not in never falling, but in rising every time we fall.",
"In the end, it's not the years in your life that count. It's the life in your years.",
"Never let the fear of striking out keep you from playing the game.",
"Life is either a daring adventure or nothing at all."]
helper['sad']= ["Dont cry because it’s over, smile because it happened.",
"Be yourself; everyone else is already taken",
"No one can make you feel inferior without your consent.",
"It’s not who you are that holds you back, its who you think you're not.",
"When you reach the end of your rope, tie a knot in it and hang on."]
answer = input ('How do you feel : ')
print("Check this out : " , random.choice(helper[answer]))
restart = input("Do you want a new quote?").lower()
if restart == "yes":
main()
else:
exit()
main()
How to rerun a code with user input [yes/no] in python ?
strong text
How to rerun a code with user input [yes/no] in python ?
strong text
inside code
def main():
try:
print("Welcome user! I am a smart calculator developed by Kushan\n'//' for Remainder\n'%' for Quotient\n'*' for Multiplication\n'/' for Division\n'^' for power")
num1 = float(input("Enter 1st number: "))
op = input("Enter operator: ")
num2 = float(input("Enter 2nd number: "))
if op == "+":
print(num1 + num2)
elif op =="-":
print(num1 - num2)
elif op =="*":
print(num1 * num2)
elif op =="/" :
print(num1 / num2)
elif op =="%":
print(num1 % num2)
elif op =="//":
print(num1 // num2)
elif op == "^":
print(num1 ** num2)
else:
print("Invalid number or operator, Valid Operators < *, /, +, -, % , // > ")
except ValueError:
print("Invalid Input, please input only numbers")
restart = input("Do you want to CALCULATE again? : ")
if restart == "yes":
main()
else:
print("Thanks! for calculating keep learning! hope you have a good day :)")
exit()
main()
strong text
You maybe trying to run the entire code with an option for user to type "yes" or "no" to run a program again without running it manually.
This is my code for a 'calculator' in which i have used this thing.
Is that your solution?
By the way this is a reference link from where i learnt to apply this function.
https://www.youtube.com/watch?v=SZdQX4gbql0&t=183s

Categories

Resources