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".
Related
Title.
I'm currently writing a choose your own adventure python script for my computer science class and need to give the player 5 lives and when they run out have a line of text appear. Any ideas?
(I'm not sure if I need to post the script or not but I can later today if needed.)
script:
# Name: Drew Dilley
**# Date: 12/7/20
# 1 REMOVED IMPORT MATH BECAUSE IT IS NOT NEEDED FOR THIS SCRIPT.
# 2
import random
answer: str = input("Do you want to go on an adventure? (Yes/No)")
# hint: the program should convert player's input to lowercase and get rid of any space player enters
# hint: check out what .upper(), .lower(), .strip() do on a string, reference: https://www.w3schools.com/python/python_ref_string.asp
# 3
if answer.upper().strip() == "yes":
# hint: pay attention to the variable name
# 4
ANSWER= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
# 5 UNNECESSARY INDENT
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack": #(HAD TO FIX UNEXPECTED INDENT)
print("She turned you into a green one-legged chicken, you lost!")
# 6 HAD TO ADD PARENTHESES AND FIX THE SEMICOLON AFTER "ANSWER"
elif answer := "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
# 7 SEMICOLON NEEDED AFTER "ELSE" PLANE/ANSWER + CAR/ANSWER NEEDED TO BE FLIPPED. NO INDENTATION NEEDED FOR "ELSE". == INSTEAD OF !=
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
elif "right" != answer:
else:
print("You are frozen and can't talk for 100 years...")
# hint: the program should randomly generate a number in between 1 and 3 (including 1 and 3)
# hint: remember random module? reference: https://www.w3schools.com/python/module_random.asp
# 8 HAD TO IMPORT "RANDOM"
num: int = random.randint(0,3)
# 9
answer = input("Pick a number from 1 to 3: ")
# hint: will the following if statement ever be executed even when the values of answer and num are the same? If not, can you fix the problem?
# hint: the error is not necessarily in the line below.
if answer == num:
print("I'm also thinking about {}".format(num))
print("You woke up from this dream.")
else:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print('You can\'t run away...')
# 10 NEEDED A SEMICOLON FOLLOWING THE ELSE STATEMENT, SO THAT IT KNOWS WHAT TO READ AND PERFORM NEXT IN THE SCRIPT.
else:
print ("That's too bad!")** ```
you can use a for loop with a counter variable which you can decriment at every time player looses and when it goes from 5 to zero you can use break to exit the loop or a print before break to display a message.
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'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.
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).
I'm new to python and am taking a class so far my program looks like:
if choice=="1":
def addition():
print("You are doing addition. X+Y=Z")
X = int(input("Enter X:"))
Y = int(input("Enter Y:"))
sum = X + Y
print ("your total is:")
print (sum)
Well = "y"
while Well == "y":
again = input("Would you like to go again? (y/n)")
if again == "y":
addition()
if again == "n":
project()
else:
print("sorry re-enter choice")
it asks if I wan to go again before showing the actual addition part. how do I fix this? Thanks for your help :)
Lots of ways, but you could put your addition() function at the top like this:
Well = "y"
while Well == "y":
addition()
again = input("Would you like to go again? (y/n)")
if again == "n":
project()
if again not in ("n", "y"):
print("sorry re-enter choice")
Just add a flag which changes from false to true on first run, so that you don't see the "again" statement on first run.
A few points:
You shouldn't use sum as a variable name. It is a Python built in.
Look at what variable you use for your loop check, you will notice it quickly.
I think it would make more sense to ask if you want to go again at the end of the loop, after you do your stuff:
while loop_condition:
#do_your_stuff:
bla bla bla
#see if you should go again
bla bla = raw_input("Do you want to go again")
In fact, 99% of the time your while loops will follow this pattern (check condition, run body of loop, update condition) and if you are doing things in a different order (like iupdating the condition before running the body) its usually a sign you might be doing something wrong.