Now, I just can't seem to figure it out
What i'm after I think is a global Boolean that'll be set to False unless door two has been accessed then it'll flip the Boolean to be True but because i'm invoking roomChoice() to go back to the start after entering room two it's all being restarted.
Just wondering the logic to achieve this.
try and ignore the horrible mess that is this code ha, I'm doing this program in an attempt to convert from Java to Python and learn Vim in the process, so just slowly learning here.
global key = False
def roomChoice():
print("It is now time to make a decision, so go on, 1, 2 or 3")
userinput = int(input())
while userinput != 1 or 2 or 3:
if(userinput == 1):
print("Doors locked")
roomChoice()
elif(userinput == 1 and key == True):
print(
"You've entered the room, it's now time to decide if you want to steal the wallet?")
userinput = input()
if(userinput == "yes"):
print("Nice move, quick lets get out of here")
elevator()
elif(userinput == "no"):
print("Well, on your way back to the elevator someone sees you coming out of the apartment, later they realise a wallet has been stolen, because you have been seen at the crime you are falsely imprisoned for burglary. 10 years, the judge really didn’t like you.")
exit()
else:
roomChoice()
elif(userinput == 2):
print("Oh look a key, I wonder if that'll get you into room one?")
key = True
roomChoice()
else:
roomChoice()
break
I figured it out, one of those fun kinds of answers, I just had to flip my if & elif around as it was meeting the requirements of the if statement so it was never getting to the elif section. Nice.
global key = False
def roomChoice():
print("It is now time to make a decision, so go on, 1, 2 or 3")
userinput = int(input())
while userinput != 1 or 2 or 3:
if(userinput == 1 and key == True):
print(
"You've entered the room, it's now time to decide if you want to steal the wallet?")
userinput = input()
if(userinput == "yes"):
print("Nice move, quick lets get out of here")
elevator()
elif(userinput == "no"):
print("Well, on your way back to the elevator someone sees you coming out of the apartment, later they realise a wallet has been stolen, because you have been seen at the crime you are falsely imprisoned for burglary. 10 years, the judge really didn’t like you.")
exit()
else:
roomChoice()
elif(userinput == 1):
print("Doors locked")
roomChoice()
elif(userinput == 2):
print("Oh look a key, I wonder if that'll get you into room one?")
key = True
roomChoice()
else:
roomChoice()
break
EDIT: You just have a logic error in your first if/elif statement, you have to check that the key is still false in the if statement, or it will always execute instead of the elif below it.
Did you try declaring the key as a global variable inside the function?
key = False
def roomChoice():
global key
userinput = int(input("It is now time to make a decision, so go on, 1, 2 or 3: ")) # you can pass the prompt string as a parameter to the input method
while userinput != 1 or userinput != 2 or userinput != 3:
if(userinput == 1 and key is False): # key has not yet been found
print("Doors locked")
roomChoice()
elif(userinput == 1 and key is True): # now key has been found
print()
userinput = input("You've entered the room, it's now time to decide if you want to steal the wallet? ")
if(userinput == "yes"):
print("Nice move, quick lets get out of here")
elevator()
elif(userinput == "no"):
print("Well, on your way back to the elevator someone sees you coming out of the apartment, later they realise a wallet has been stolen, because you have been seen at the crime you are falsely imprisoned for burglary. 10 years, the judge really didn’t like you.")
exit()
else:
roomChoice()
elif(userinput == 2):
print("Oh look a key, I wonder if that'll get you into room one?")
key = True
roomChoice()
else:
roomChoice()
break
Related
How do I make a loop in an if-statement within an if-statement? I'm busy with How to learn Python 3 the hard way, and so far I know I can do the following:
while True:
print("choose 1st branch")
choice = input()
if choice == '1':
print('1, now choose second branch')
while True:
choice = input("")
if choice == "2":
print("2")
while True:
choice = input("")
if choice == "3":
print('3')#
else: #needs to ask for input for choice 3 again
print("try again")
else:print("try again")#needs to ask for input for choice 2 again
ive edited a simpler code example of what im trying to accomplish
Instead of creating a loop everywhere you want to check if the user input is a valid choice, you can extract that "checking if user input is within a valid choices" into a function. Said function will be something like
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
With this new function, we check the validity of the choices first, then after we received the correct input, we then process with the logic for each of the choices.
occu = "ranger"
prompt = "-->"
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
def room1():
print("you walk into an bare room")
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = "ranger"
while True:
print("you see a door infront of you")
print("do you go left, right or forward?")
choice = get_user_choice(prompt, ("left", "right", "forward"))
if choice == "left" and hole == False:
print("\nDo you \ndodge \nor \nattack?")
choice = get_user_choice(prompt, ("dodge", "attack"))
if choice == "dodge" and occu == "ranger":
trap = True
rat = True
print("\nhole \nroom")
choice = get_user_choice(prompt, ("hole", "room"))
if choice == "hole" and rat == True:
print("you walk up to the hole, you see a faint glitter")
print("do you reach your hand in?")
print("\nyes \nno")
choice = get_user_choice(prompt, ("yes", "no"))
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
choice = True
elif choice == "no":
print(" you go back to the centre of the room")
Notice that other input also get modified to use this function to check if the choice user selected is valid or not.
The problem is that you are reusing the variable choice, and assigning it to be a boolean value and later on be the input. Try using another variable as well for either the boolean or the input, i.e. proceed.
proceed = False # CREATE VARIABLE PROCEED
while proceed == False: # LOOP WHILE PROCEED IS FALSE
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
proceed = True # CHANGE PROCEED, NOT CHOICE
elif choice == "no":
print("You go back to the center of the room")
# Perhaps assign proceed to be True here as well?
else:
print("unknown choice, try again")
occu = 'ranger'
prompt = "-->"
def room1():
print("you walk into an bare room"
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = 'ranger'
while True:
print("you see a door infront of you")
print("do you go left, right or foward?")
if input(prompt) == 'left' and hole == False:
print('\nDo you \ndodge \nor \nattack?')
if input(prompt) == 'dodge' and occu == 'ranger':
trap = True
rat = True
print("\nhole \nroom")
if input(prompt) == 'hole' and rat == True:
print("you walk up to the hole, you see a faint glitter")
while True:
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice not in ['yes', 'no']:
print("unknown choice, try again")
continue # <-- Starts loop over.
elif choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
else:
print(" you go back to the centre of the room")
break # <-- Breaks out of loop.
I know that a "not repeat with random from a list" is probably seen as a info you can find, but as someone who does not have a lot of knowledge of python yet, i cannot seem to understand those answers or they do not work for my problem. So I hope any of you are able to help.
as my first small project I am building a truth or dare program, and now I am at the point that I want to make it that the questions cannot be asked twice, and that if the truth questions are all done it prints that announcement, and I want the same for my dare questions.
here is my program so far, sorry if it is messy:
import random
import time
truth = ["If you could be invisible, what is the first thing you would do?",
"What is a secret you kept from your parents?",
"What is the most embarrassing music you listen to?",
"What is one thing you wish you could change about yourself?",
"Who is your secret crush?"]
dare = ["Do a free-style rap for the next minute",
"Let another person post a status on your behalf.",
"Hand over your phone to another player who can send a single text saying anything they want to anyone they want.",
"Let the other players go through your phone for one minute.",
"Smell another player's armpit."]
print("Hello, and welcome to my truth or dare show, just type truth or type dare to get a question!")
lives = 3
while lives > 0:
choice = input("truth or dare?: ").lower()
time.sleep(0.5)
if choice == "truth":
print(random.choice(truth))
time.sleep(0.5)
while True:
answer_truth = input("want to answer? type yes or no: ").lower()
if answer_truth == "yes":
input("> ").lower()
print("good answer")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif answer_truth == "no":
print("you lost a life!")
time.sleep(1)
lives -= 1
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
elif choice == "dare":
print(random.choice(dare))
time.sleep(0.5)
while True:
do_dare = input(f"did you do the dare? type yes or no: ").lower()
if do_dare == "yes":
print("well done!")
time.sleep(0.5)
print(f"you have {lives} lives left")
break
elif do_dare == "no":
print("you lost a life!")
lives -= 1
time.sleep(0.5)
print(f"you have {lives} lives left")
break
else:
print("that is not an option")
else:
print("that is not an option")
time.sleep(0.5)
print("GAME OVER!")
This should work:
choice = random.choice(truth)
time.sleep(0.5)
# inside the loop
truth.remove(choice)
if len(truth) == 0:
print("all questions are done")
do the same for dare
You probably want a construct like this:
from random import shuffle
ls = ["a", "b", "c"]
shuffle(ls)
lives = 3
while lives > 0 and ls:
current_question = ls.pop()
... # Rest of your code
So you want to select a random option, but then no longer have it in the set that you select random things from in the future.
If you imagine it physically, you have a jar list that has papers item's in it and you want to take them out at random. Obviously, any that you take out can not be taken out again.
We can accomplish this by removing the item from the list after it's 'picked'
To answer your question about having it let them know there are no more truths or no more dares, we can simply add a conditional to the whole truth segment and one to the whole dare segment as well, then further, if both run out, end the game.
while lives > 0 and (len(truth)>0 or len(dare>0)):
# Rest of the program
if choice == "truth":
if len(truth) > 0:
# Code
else:
print("there are no more truths (existential crisis), maybe try a dare instead")
elif choice == "dare":
if len(dare)>0:
# Code
else:
print("there are no more dares *sigh of releif*, maybe try a truth instead")
I'll try to keep it short and sweet.
I'm writing an interactive story that changes based on the "roll" of a d20 dice. I've managed to figure out getting started, but I've hit a point where I don't think Python is actually listening to the parameters I'm giving it, because it kind of just does whatever.
Essentially, here's what's supposed to happen:
Player agrees that they want to play the game -> Player Rolls dice -> Game uses the randomly rolled number to determine which start that the player will have.
What's currently happening is, all goes well until it's supposed to spit out the start that the player has. It doesn't seem to actually decide based on my parameters. For example, you're supposed to have the "human" start if the player rolls 5 or less, and an "elf" start for anything between 6 and 18. Here's what happened yesterday:
venv\Scripts\python.exe C:/Users/drago/PycharmProjects/D20/venv/main.py
Hello! Would you like to go on an adventure? y/n >> y
Great! Roll the dice.
Press R to roll the D20.
You rolled a 15!
You start as a human.
As a human, you don't have any special characteristics except your ability to learn.
The related code is below:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
print("You rolled a " + str(RollD20()) + "!")
PostGen()
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
def PostGen():
if RollD20() <= 5:
print("You start as a human.")
PostStartHum()
elif RollD20() >= 6:
print("You start as an elf.")
PostStartElf()
elif RollD20() >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
def RollD20():
n = random.randint(1, 20)
return n
def PostStartHum():
print("As a human, you don't have any special characteristics except your ability to learn.")
def PostStartElf():
print("As an elf, you have a high intelligence and a deep respect for tradition.")
def PostStartDemi():
print("As a demigod, you are the hand of the gods themselves; raw power incarnated in a human form...")
print("However, even mighty decendants of gods have a weakness. Be careful."
Thanks for all your help.
Turn your PostGen function into the following:
def PostGen(rollValue):
if rollValue <= 5:
print("You start as a human.")
PostStartHum()
elif rollValue >= 6:
print("You start as an elf.")
PostStartElf()
elif rollValue >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
Change your NewGame function to the following:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
rollValue = RollD20()
print("You rolled a " + str(rollValue) + "!")
PostGen(rollValue)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
You are generating a new random number every time you call RollD20(). You need to store the value somewhere and reuse it for the game session.
Each time you call RollD20, you get a new random number. So if you want to use the same random number in multiple ifs, you need to tuck that value into another variable.
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
result = RollD20()
print("You rolled a " + str(result) + "!")
PostGen(result)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
And from there you change PostGen() to accept the result:
def PostGen(result):
if result <= 5:
print("You start as a human.")
PostStartHum()
elif result >= 6:
print("You start as an elf.")
PostStartElf()
elif result >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
I'm doing an assignment where I have to conduct a quiz for different topics. This is my code so far.
print("Hello and welcome to Shahaad's quiz!") #Introduction
name = input("What is your name? ")
print("Alright", name,", these will be today's topics:")
print("a) Video Games")
print("b) Soccer")
print("c) Geography")
choice = input("Which topic would you like to begin with?")
if choice == 'video games' or choice == 'Video Games' or choice == 'Video games' or choice == 'a)':
print("You picked Video Games.")
print("Question number one:")
print("What is the most popular FPS (First Person Shooter) game?")
print("a) Call of Duty")
print("b) Battlefield")
print("c) Grand Theft Auto 5")
print("d) Counter Strike")
answer = input("Your answer:")
guessesTaken = 0
if answer == 'Call Of Duty' or answer == 'Call of duty' or answer == 'Call of duty' or answer == 'a)' or answer == 'call of duty':
print("You are correct!")
else:
guessesTaken = guessesTaken + 1
print("Incorrect!")
print("You have", guessesTaken, "guess left!")
I am trying to make it so that if they get the answer wrong, they get another chance at answering the question. Right now once they get it wrong, they can't type again. Thanks!
You should do as #BartoszKP says, use a while loop to check that the user has entered a valid input.
That being said, I have a few recommendations that might improve the readability of your code.
Instead of this
if choice == 'video games' or choice == 'Video Games' or choice == 'Video games' or choice == 'a)':
print("You picked Video Games.")
You could take advantage of the str().lower() method:
if choice.lower() == 'video games' or choice == 'a':
print('You picked Video Games.")
The lower() method converts all letters to lower-case.
Regarding the while loop, I don't like to use a flag variables - it adds an extra variable to the code that isn't really needed. Instead, you could make use of break
while True:
choice = input('Which topic would you like to begin with?')
if choice.lower() == 'video games' or 'a':
print('You picked Video Games.')
break #This breaks out of the while loop, and continues executing the code that follows the loop
Another solution is to define the choice variable before the while loop, and run it until the input is like you want:
choice = input('Which topic would you like to begin with?')
while choice.lower() != 'video games' and choice != 'a':
print('Please pick a valid option')
choice = input('Which topic would you like to begin with?')
print('You picked "{}".'.format(choice))
If you want to be able to choose between different options, the code could be further improved by checking if the input string is one of the items in a list:
valid_options = ['video games', 'a', 'software', 'b', 'cartoons', 'c']
choice = input('Which topic would you like to begin with?')
while choice.lower() not in valid_options:
print('Please pick a valid option')
choice = input('Which topic would you like to begin with?')
print('You picked "{}".'.format(choice))
Output:
Which topic would you like to begin with?Movies
Please pick a valid option
Which topic would you like to begin with?vIdeO gaMes
You picked "vIdeO gaMes".
Which topic would you like to begin with?software
You picked "software".
If you use Python 2.x, you should also consider using raw_input() instead of input(). Please see this related SO question to understand why.
This is a simple and quite often encountered problem. The solution usually fits this scenario:
flag = False
while not flag:
x = input("Get input from the user:")
if validate(x):
flag = True
else:
print "Input invalid. Try again"
Where variable names should be of course changed to be suitable to the current task (e.g. flag --> answerCorrect or similar, x --> answer etc.).
I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.