Using input() to quit - python

I'm a pretty new programmer and have been working with Python 3 for a few weeks. I tried making a little magic 8 ball program where you get an answer to a question and it asks if you want to play again. however no matter what I enter it never quits and keeps looping. I'm not sure what I'm doing wrong. Any help is greatly appreciated!
#Magic 8 Ball V2
import random
import time
class Magic8ball:
def __init__(self, color):
self.color = color
def getanswer(self):
responselist = ['The future looks bright!', 'Not too good...', 'Its a fact!',
'The future seems cloudy', 'Ask again later', 'Doesnt look too good for you',
'How would i know?', 'Maybe another time']
cho = random.randint(0, 7)
print ('Getting answer...')
time.sleep(2)
print (responselist[cho])
purple = Magic8ball('Purple')
blue = Magic8ball('Blue')
black = Magic8ball('Black')
while True:
print ('Welcome to the magic 8 ball sim part 2')
input('Ask your question:')
black.getanswer()
print ('Would you like to play again?')
choice = ' '
choice = input()
if choice != 'y' or choice != 'yes':
break

Three things wrong with your code:
1)
choice = ' '
choice = input()
No need for the first line, you are immediately overriding it.
2)
print ('Would you like to play again?')
choice = input()
Instead of this, use just input("Would you like to play again?")
3)
The logic on the line of if choice != 'y' or choice != 'yes': is wrong.
In my opinion it would be better if you did this:
if choice not in ("y", "yes"):
This would make it really clear what you are trying to do.
Also, you might want to consider using choice.lower() just for the convenience of the users. So that Yes still counts.

Use sys.exit() to quit the shell.
Also, as #jonrsharpe notes, you want and instead of or on this line:
if choice != 'y' or choice != 'yes':
That's because if the user supplies 'y', the program will do two checks: First, it checks if choice != 'y', which is false. Then, because you are using or, it checks if choice != 'yes', which is true. Therefore, the program will break out of the while loop no matter what the user inputs.

Related

I'm trying to quit a python program with q or Q as an option [duplicate]

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.

Python dice rolling game stuck on code, want to loop to restart if certain user input is met [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So I'm fairly new to this whole coding scene and I'm doing some beginner projects to build upon what I've learned.
Essentially what I'm trying to do is get the program to restart back at the top of the loop if the user wants to roll again, or accidently types something else that is not "yes" or "no".
In addition, is there a way to skip a certain line of code, so that way the user isn't asked if they want to roll twice?
Should I be using functions instead?
Couldn't find any info that helped me directly so thought I would ask, any info at all would be helpful, thanks!
import random
useless_varaible1 = 1
useless_varaible2 = 1
# this is the only way I know to set a while loop, I know yikes.
while useless_varaible1 == useless_varaible2:
lets_play = input('Do you wish to roll? Yes or no: ')
if lets_play.lower() == 'yes':
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
ask = input('Do you wish to roll again? ')
if ask.lower() == 'yes':
# How do I return to give the user another chance?
elif ask.lower() == 'no':
print('Alright, later!')
break
elif lets_play.lower() == 'no':
print('Alright, later!')
break
else:
print('Not any of the options, try again...')
# how do I return to the top to give the user another chance?
(Original code as image)
You've asked a couple of questions in one, but I'll try and answer them with an example. First off, to have an infinite running while loop, you can just set it to True (basically the same as your 1=1 statement, just easier).
Your second question regarding functions is typically yes - if some code needs to be repeated multiple times, it's usually good to extract it to a function.
Your third question regarding skipping a line of code - easiest way to do this is if/else statements, like you've already done. One thing that can be improved, is by using continue; it restarts the loop from the beginning, whereas break breaks out of the loop.
Here's a simple code example for your scenario:
import random
def roll():
print('First roll:', random.randint(1, 6))
print('Second roll:', random.randint(1, 6))
play = input('Do you wish to roll? Yes or no: \n')
while True:
if play.lower() == 'yes':
roll()
play = input('Do you wish to roll again? \n')
elif play.lower() == 'no':
print('Alright, later!')
break
else:
play = input('Not any of the options, try again... Yes or no: \n')
Hey I would do it like this
import random
useless_variable = 1
lets_play = input("Do you want to roll. yes or no: ")
if lets_play.lower() == "yes":
while useless_variable == 1:
useless_variable == 0
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print("You got a: ", d1, "from the first dice")
print("You got a: ", d2, "from the seond dice")
ask = input("Wanna roll again(yes or no):")
if ask.lower() == "yes":
useless_variable = 1
else:
break
If you want to do an infinite loop then while True: Otherwise you can put in your while something like while condition == true and in your answer when is "no" change the condition to false.
I would do it like this
def roll():
if(lets_play.lower() == "yes"):
//Code here
elif lets_play.lower() == "no":
//Code here
else:
print("invalid")
while True:
lets_play = input("Roll?")
if lets_play.lower() == "exit":
break
else:
roll()

variable not defined! (python)

I have been trying to run my first full text adventure but whenever i run it it says that answer is undefined! please help. in case if you're wondering, here's the code
accept = input("would you like to play the game??")
if accept.lower() .split() == "yes":
answer: str = input ("you wake up in a room with two doors in front of you. do you go to the left or the right?")
if answer.lower() .split() == "left":
answer2 = input(" you enter the left door. you find a phone with a peice of paper attached to the wall with the phone\n there are two numbers on the peice of paper\n will you choose to call the first one or the second one")
The reason is because the condition did not meet the if statement's requirement, so yo never defined answer. It was the .split() that made it wrong:
accept = input("would you like to play the game??")
if accept.lower() == "yes":
answer = input ("you wake up in a room with two doors in front of you. do you go to the left or the right?")
if answer.lower() == "left":
answer2 = input(" you enter the left door. you find a phone with a peice of paper attached to the wall with the phone\n there are two numbers on the peice of paper\n will you choose to call the first one or the second one")
You see, when yo have str.split(), python will return a list, not a string.
Have a look at this:
print("hello".split())
Output:
["hello"]
Your problem is similar to this:
x = False
if x:
answer = "yes"
print(answer)
Note how, because x is False, answer never gets defined and when Python reached the line where it needs to print answer, it will report the error.
You either need to define an else clause, or define the value up front, i.e.:
x = False
answer = "no"
if x:
answer = "yes"
print(answer)
Or:
x = False
if x:
answer = "yes"
else:
answer = "no"
print(answer)
Whether you pick a default or an explicit alternative should depend on what makes more sense for your code, they are both valid ways of solving this. In your case, it depends on what you need to do if they player does not answer "yes".

Python wont choose between 2 if options [duplicate]

I'm learning python and I found myself lost trying to create a an if statement that should be true if the user input y or yes.
#!/usr/bin/env python3
user_input = input('Would you like to go on?')
lowui = user_input.lower
if lowui == ('y' or 'yes'):
print('You want to go on')
else
print('See you later, bye')
The problem is that it becomes true only if I type y but not for yes. If I remove the parenthesis it becomes always false. Ok, I can do a workaround like
if lowui == 'y' or lowui == 'yes':
but I was wondering if there is any trick that don't force me to write so many times tha variable.
Thank you in advance.
Change it to
if lowui in ('y', 'yes'):
Also this is wrong:
lowui = user_input.lower
it should be:
lowui = user_input.lower() # Actually call the lower function

python - checking string for certain words

What I'm trying to do is that, if I ask a question only answerable by Yes and
No, I want to make sure that yes or no is the answer. Otherwise, it will stop.
print("Looks like it's your first time playing this game.")
time.sleep(1.500)
print("Would you like to install the data?")
answer = input(">").lower
if len(answer) > 1:
if answer == "no":
print("I see. You want to play portably. We will be using a password system.")
time.sleep(1.500)
print("Your progress will be encrypted into a long string. Make sure to remember it!")
else:
print("Didn't understand you.")
elif len(answer) > 2:
if word == "yes":
print("I see. Your progress will be saved. You can back it up when you need to.")
time.sleep(1.500)
else:
print("Didn't understand you.")
First:
answer = input(">").lower
should be
answer = input(">").lower()
Second, len(answer) > 1 is true for both "no" and "yes" (and anything larger than one character, for that matter). The elif block will never be evaluated. Without modifying significantly the logic of your current code, you should do instead:
if answer == 'no':
# do this
elif answer == 'yes':
# do that
else:
print("Didn't understand you.")
Something like:
if word.lower() in ('yes', 'no'):
would be the simplest approach (assuming case doesn't matter).
Side-note:
answer = input(">").lower
Is assigning a reference to the lower method to answer, not calling it. You need to add parens, answer = input(">").lower(). Also, if this is Python 2, you need to use raw_input, not input (In Python 3, input is correct).

Categories