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).
Related
I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()
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()
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".
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.
I have a line in a function filter3 is a dict that I create via a shuffle function.
answer = shuffle(filter3)
print(answer)
userConfirm()
What I want to do is implement my userConfirm() function and if the user is unhappy with the output they select "N" and it will make answer go again.
Just not sure what to put in my "N" response in my function to make this happen.
import sys
def userConfirm():
"""get user confirmation to proceed"""
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == "N":
#What to do here
elif userChoice == "Q":
sys.exit("You Quit the Program")
elif userChoice == "Y":
print("OK Proceeding")
goto is considered harmful since the end of the sixties. Google for "goto considered harmful", there's an article by Dijkstra about that topic which became so famous that the phrase "considered harmful" nowadays is often reused for similar topics.
The reason is plain an simple: With goto you can create code which is hard to understand, hard to debug and hard to extend.
Use a proper loop for what you want. Rethink your problem from "I want to go back under this condition" to "I want to repeat this until this condition is met." Then writing it as a loop comes much easier and more natural.
Unfortunately, Python has no repeat … until for loops testing at the end. You only have for loops (for a specific list of iterations to perform) and while loops which test at the beginning, not the end. But you can use a while True for this and test explicitly in the end yourself:
while True:
do_something()
if break_condition:
break
Your second issue (given only in the comment below your question) can be solved by letting userConfirm() return a value stating whether the user wishes a repetition or not:
def userConfirm():
"""get user confirmation to proceed"""
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == "N":
return False
elif userChoice == "Q":
sys.exit("You Quit the Program")
elif userChoice == "Y":
print("OK Proceeding")
return True
while True:
do_something()
if userConfirm():
break
import sys
def userConfirm():
userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
if userChoice == 'N':
return False
elif userChoice == 'Q':
sys.exit("You Quit the Program")
elif userChoice == 'Y':
print "OK Proceeding"
return True
while True:
answer = shuffle(filter3)
print answer
if userConfirm():
break
goto is always considered a bad programming practice after the advent of modern programming languages. It becomes hard to debug, track bugs/errors or even try to understand what in the hell you've written a few months ago(especially when your program deals with multiple nested if/else statements or loops). The best way to solve a problem without using goto is by structuring your program well. Grab a paper, design the structure. Now after you have a concrete plan with good logic, start coding. Use LOOPS, use BREAK and CONTINUE statements where necessary. These simple tricks/methods will help you build neat programs and save you from headaches. As they say "weeks of coding saves you hours of paperwork".