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.
Related
Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I'm writing a program as an exercise for if-elif-else statements and I could do with some advice as to why an elif statement is not running.
I want to give the option to pick up rocks for the inventory.
That works, but if I say I do NOT want to pick up the rocks, that elif statement seems to be ignored and I pick up the rocks and they are added to my inventory.
I have no actual errors, but cannot see why the elif statement is not being actined. I have used this several times in the same program as part of this exercise and not had this continual problem.
These are the statements I seem to be having issues with:
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
Here is the whole of the function:
def fog():
global inventory
global rocks_there
print("You walk along the path to the left of the castle when a thick fog starts swirling around you.")
print("Do you want to CARRY on or go BACK to the courtyard?")
choice = input("> ").lower()
if "back" in choice:
grounds()
elif "carry" in choice:
num = random.randint(0,10)
if num < 2:
print("""The fog envelopes you until you have no idea where you are and can see nothing else.
Suddenly you feel yourself fall as you step over the edge of a towering cliff.
You die, but at least you are not undead.""")
exit(0)
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
elif num >= 2 and rocks_there == False:
print("You follow the castle walls around to the front of the castle.")
else:
print("The fog has scrambled your brain and I do not understand you.")
print("I hope you find your way out.")
print("Goodbye!")
exit(0)
If you try this simple code
mylist = []
if "yes" or "y" in mylist:
print("oops")
you'll see that the code is interpreted as
mylist = []
if "yes" or ("y" in mylist):
print("oops")
And since
if "yes":
print("oops")
it will always run through the if-part and never through the elif part. That's because "yes" is considered a truthy value.
What you probably wanted is
if take in ["y", "yes"]:
which is "check if the user input (take) is in the list ([]) of possible answers". And similar for the no-part of the statement.
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.
I am trying to make a Heads Or Tails program in Python. I am a newbie and I have just got into Python. What I try to achieve is to have the program pick either Heads or Tails without me knowing it (Yes, import random, etc.) and I would like to have a single try when guessing. This is what I have achieved so far, yet it is not very close to what i am looking for. Any thoughts? I have tried implementing the different random arguments I found on a Python website but they don't work (such as randint for integers)... Thanks!
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = "Heads" # For Debugging purposes to check if the program works
notCorrectAnswer = "Tails" # To eliminate the possibility of not being either tails or heads in case of mistaken answer
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"
You should try:
import random
ch = random.choice(["Heads","Tails"])
which will put into the variable ch either "Heads" or "Tails". Try to do something from that.
To make the whole thing continue until exited by user, and including #Baruchel's answer:
import random
print """
Welcome to our game. This is a heads or tails game and you will be the one who gets to pick a possible answer. Lets begin!
"""
cont = 1 #To force the game to run for one round without user input
while(cont == 1): #cont is used to take user choice, whether to run it again or not
print "~-~-~-~-" * 10
theirGuess = raw_input("Whats your guess? : ")
ourAnswer = random.choice(["Heads","Tails"])
if ourAnswer == "Heads":
notCorrectAnswer = "Tails"
else:
notCorrectAnswer = "Heads"
if theirGuess == ourAnswer:
print "You got it!"
elif theirGuess != notCorrectAnswer and ourAnswer:
print "You didnt get it! Try entering either Tails or Heads!"
else:
print "You didnt get it! Try again next time!"
cont = input("Do you want to continue? Press 1 if yes, press 0 if no.: ") #Take user choice on whether to run it again or not
while (cont != 0 and cont != 1): # If user puts in a different number (neither 1 or 0), make them enter until they put a right choice
cont = input("Please try again. Press 1 if yes, press 0 if no.: ")
I have to make this game for my comp class, and I can't figure out how how break out of this loop. See, I have to play against the "computer," by rolling bigger numbers, and seeing who has the bigger score. But I can't figure out how to "break" from my turn, and transition to the computers turn. I need "Q" (quit) to signal the beginning of the computers turn, but I don't know how to do it.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
if ans=='Q':
print("Now I'll see if I can break your score...")
break
A couple of changes mean that only an R or r will roll. Any other character will quit
import random
while True:
print('Your score so far is {}.'.format(myScore))
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans.lower() == 'r':
R = np.random.randint(1, 8)
print("You rolled a {}.".format(R))
myScore = R + myScore
else:
print("Now I'll see if I can break your score...")
break
What I would do is run the loop until the ans is Q
ans=(R)
while not ans=='Q':
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
Don't use while True and break statements. It's bad programming.
Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.
The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.
Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
else:
print("Now I'll see if I can break your score...")
ans = False
break
Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:
myScore = 0
while ans := input("Roll...").lower() == "r":
# ... do something
else:
print("Now I'll see if I can break your score...")