this is kinda my homework and I'm stuck on making the code becoming a follow up question, like this code here, I've tried inserting an if statement after that but it gave me an unexpected incent error.
Here are my codes so far:
Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
You have an extra indent. Just remove the extra level of indentation:
Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
Indentation is the way to create code blocks in Python. Your error says exactly what you did wrong.
if condition:
# executes if condition is met
if internalCondition:
# executes if both condition and internalCondition is met
elif otherCondition:
# executes if first statement didn't and otherCondition is met
else:
# executes if nothing else executed
You indented if internalCondition: with excess whitespaces.
Related
I'm writing a program in Python that asks a user what toppings they would like on their pizza, as shown below.
print("PIZZA TOPPINGS: \n mushrooms \n pineapple \n anchovies \n pepperoni \n sausage \n extra cheese \n")
toppings = ["pepperoni", "ham", "pineapple", "mushrooms", "sausage", "anchovies", "extra cheese"]
your_toppings = []
maxLengthList = 3
while len(your_toppings) < maxLengthList:
item = input("Add up to 3 toppings: ").lower()
if item == "ham":
print("Sorry, out of ham")
continue
elif item in toppings:
print("Adding " + item)
elif item == "":
ans = input("Are you sure you don't want to add any more toppings? Y/N ").lower() #this is the line I'm trying to loop back to
if ans == "yes" or ans == "y":
break
elif ans == "no" or ans == "n":
continue
else:
print("Please answer y/n")
#trying to loop back to Y/N prompt
else:
print("Not an option")
continue
your_toppings.append(item)
if len(your_toppings) > 0:
print("Your toppings: " + ', '.join(your_toppings))
else:
print("No toppings for you!")
The part I've been stuck at is inside the nested If statement (see the 2nd comment), if the user does not answer with the required y/n. I'm trying to figure out how I can loop back to the input prompt, "Are you sure you don't want to add any more toppings? Y/N" until they respond with y/n.
I did try to use a nested while loop before the ans = input line, but that breaks the program as answering with y/n does not break/continue in the original while loop (i.e. back to the topping prompt), but in the inner while loop instead.
Is there a simpler way of accomplishing this?
I'm still pretty new to Python so I'm playing around primarily with these If statements/While loops at this point, so I understand my program may start to look messy with so much nesting. I am willing to modify it using another angle if that would accomplish the same thing.
Thanks to everyone in advance!
In your nested while loop, break from the loop when you get a correct yes or no response. Then outside the loop, check whether it is yes or no and break.
Better yet, make a function that asks your yes/no question and doesn’t return until you get a yes/no answer. Then call that from your main loop.
I think you're on the right track with the nexted loop, but maybe just make it a small inner loop to check for validity. Something like this:
elif item == "":
while True:
ans = input("Are you sure you don't want to add any more toppings? Y/N ").lower() #this is the line I'm trying to loop back to
if ans not in ['yes', 'y', 'no', 'n']:
print("Please answer y/n")
else:
break
if ans == "yes" or ans == "y":
break
else:
continue
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.
optionone = 0 #DEFINING BOTH VARIABLES
optiontwo = 0
class first_day_morning: #WORKING
optionone = input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input()))
I am trying to make it so that the user input decides the outcome of the if statement, if user inputs 1, then something happens, if user inputs 2 then something else happens, if user inputs anything else, than the if statement runs again as only 1 or 2 are valid inputs. However, the problem is that no matter what the user inputs, the if statement does not run, and no error is shown either. I tried a try/except in case an error just isn't showing for some reason (try except ValueError:) and nothing seemed to work I have also tried to specify the input as str, int, float, no specification, raw_input etc. and nothing really works, can someone help?
ps. I am using Visual Studio Code
As you can see, the if statement does not run as no error is shown even after user input.
When the program runs, the class body will be evaluated, meaning the input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ") will prompt for input. That value will then be kept in first_day_morning.optionone, however first_choice's optionone is different. It is equal to the parameter supplied on the final line, int(input()), which will silently prompt for another input, and then convert it to an integer. From what I think you're trying to achieve, I'd recommend you remove the class and change the final line to:
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
def first_choice():
print('')
print("You have chosen to get out of the house for once")
def second_choice():
print('')
print("DO LATER")
def third_choice():
print('')
print("please choose a valid option")
while True:
print("""Select a choice""")
c = int(input('enter your choice:'))
if c == 1:
first_choice()
elif c == 2:
second_choice()
elif c == 3:
third_choice()
elif c == 4:
break
i dont really understand what u r trying to acomplish here, but the code works for me, some tips from a beginer:
-you define optiontwo and never use it
-you you are filling optionone with input inside a class, dont know why, cause is never used
not sure what do u want, but try this:
import time
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
although, test it in console, not sure about vscode but running inside sublime does not ask for input
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 have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.