Python Programming Loop - python

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.).

Related

how to make it that it does not repeat?

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")

Text based adventure challenge issues

I'm new at coding and I've been trying this text-based adventure game. I keep running into syntax error and I don't seem to know how to solve this. Any suggestions on where I could have gone wrong would go a long way to helping.
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
def game_over(reason):
print("\n", reason)
print("Game Over!!!")
play_again()
def diamond_room():
print("\nYou are now in the room filled with diamonds")
print("what would you like to do?")
print("1) pack all the diamonds")
print("2) Go through the door")
answer = input(">")
if answer == "1":
game_over("The building collapsed bcos the diamonds were cursed!")
elif answer == "2":
print("You Win!!!")
play_again()
else:
game_over("Invalid prompt!")
def monster_room():
print("\nYou are now in the room of a monster")
print("The monster is sleeping and you have 2 choices")
print("1) Go through the door silently")
print("2) Kill the monster and show your courage")
answer = input(">")
if answer == "1":
diamond_room()
elif answer == "2":
game_over("You are killed")
else:
game_over("Invalid prompt")
def bear_room():
print("\nThere's a bear in here!")
print("The bear is eating tasty honey")
print("what would you like to do?")
print("1) Take the honey")
print("2) Taunt the bear!")
answer = input(">").lower()
if answer == "1":
game_over("The bear killed you!!!")
elif answer == "2":
print("The bear moved from the door, you can now go through!")
diamond_room()
else:
game_over("Invalid prompt")
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
start()
it keeps popping error and i cant detect where the error is coming from.
You have 2 problems.
Assertion instead of Assignment.
Calling the wrong function.
For 1. You have
def start():
print("Do you want to play my game?")
answer = input(">").lower()
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
if answer == "l":
bear_room()
elif answer == "r":
monster_room()
else:
game_over("Invalid prompt!")
You should uuse answer = input(">") and not answer ==.
For 2. You have
def play_again():
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
play_again()
else:
exit()
You should call start not play_again
In this part of your code, you should change you last line:
if answer == "y":
print("\nyou're standing in a dark room")
print("you have 2 options, choose l or r")
answer == input(">")
to answer = input(">").lower()
use = to assign a value to a variable, and use == to check the similarity(ex. in an if)
it is better to make the user input to lower case as other parts of your code, because in next lines of you've checked its value in an if condition with lower case (r and l).
3)another problem is that in def play_again(): you have to call start() function, sth like this:
print("\nDo you want to play again? (y/n)")
answer = input(">")
if answer == "y":
start()

Boolean to change value after certain steps followed

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

Is there a way for me to pass parameters from one function to another in an if statement?

I am currently producing a menu-driven program. Here is a code snippet:
def main():
intro()
loop = True
while loop:
print("\n<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>")
print("\nChoose your option below:")
print("1 - Patient Registration")
print("2 - Total Patients")
print("3 - Total Sales")
print("Q/q - Quit")
choice = str(input("Your choice?"))
print("\n<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>")
menu(choice)
def intro():
print("Welcome to CTI System.")
print("This system is used to track and manage Covid-19 testing")
def menu(choice):
if choice == '1':
patientRegistration()
elif choice == '2':
testType(pcr,antigen)
elif choice == '3':
totalSales()
elif choice == 'Q' or choice == 'q':
print("\nThank you for using this program.\n")
exit()
else:
print("\nInvalid choice! Please select from the list of choices.\n")
loop = False
When choosing the first choice, it will prompt the user to gather information. Afterwards, once the user is done with the first choice, the user will be prompted to continue, if 'N' then it will go back to the main menu.
This is where where problem starts. I want to choose the 2nd choice in the menu which is the total number of patients. How can I pass the parameters from the first condition to the second?
Your help is greatly appreciated.
Thank you!

Function not Running inside an "if" statement Python 3

I'm attempting to write an escape room game in Python.
When I run the code with pycharm the process ends with "process finished with exit code 0."
Is there something wrong in the defining of the functions?
Here is my code (its a bit lengthy):
choice = None
def main_choice():
print("1. Examine door")
print("2. Examine painting")
print("3. Examine desk")
print("4. Examine bookshelf")
choice == input("Make your choice: ")
def door():
print("1. Try to open door")
print("2. Take a closer look")
print("3. Go back to where you were.")
door_choice = input("What now? ")
if door_choice == "1":
print("The door is too heavy to open with your bare hands.")
door()
if door_choice == "2":
print("There is a red light above the door, but it seems to have no purpose.")
print("You notice a 9 key keypad next to the door. It looks like it will accept a 3 digit code.")
keypad_code = input("Would you like to enter a code?").lower
if keypad_code == " yes":
guess = input("ENTER CODE: ")
if guess == complete_key:
print("The light turns green and you hear the sound of a mechanical lock unlocking. The door opens.")
print("YOU WIN!!!")
if guess != complete_key:
print("Wrong code.")
main_choice()
if door_choice == "3":
main_choice()
else:
print("You didn't answer")
main_choice()
if choice == "1":
print("You walk to the door")
door()
I think that it might be the last "if" statement, but I'm not positive.
You need to change choice == input("Make your choice: ") to choice = input("Make your choice: ") in your main_choice function:
def main_choice():
print("1. Examine door")
print("2. Examine painting")
print("3. Examine desk")
print("4. Examine bookshelf")
choice = input("Make your choice: ")
Otherwise the choice variable will still be None and if choice == "1": will always be False.
You should write:
choice = input("Make you choice: ")
rather than:
choice == input("Make you choice: ")
Double equals signs return a boolean rather than changing a value.

Categories