Progressing to next menu option in python - python

I have a question regarding menus and how to make a "progress to Option __ " option (please note, I am very new to Python, so this may be a very easy fix and I just haven't searched for the right thing). In my current code, I have the ability for users to choose one of 4 options with activities in them. A part of options C and D use data from option B (but are able to be visible to the user without doing Option B, just as an information hub of sorts, rather than calculating). I have made up some code to show what I am talking about below:
def printMenu ():
print("Activity List")
print("A: Standalone Activity - What is the weather like")
print("B: Events")
print("C: Times")
print("D: Olympic Standards")
print("X: Exit")
return input("Please choose a selection: ").upper()
def main():
choice = printMenu()
choice
def program(selection):
if selection == "A":
print("The weather is not important, as I am a computer")
elif selection == "B":
eventInfo = input("What is your best event and distance: ")
def sportMenu():
print("1. Return to Main Menu")
print("2. Choose another sport")
print("3. Continue to Part C: Countries")
print("ENTER. Close application")
sportMenu()
sportsMenu = input("Please select an option: ")
if sportsMenu == "1":
main()
elif sportsMenu == "2":
sports()
elif sportsMenu == "3":
times()
else:
exit()
elif selection == "C":
# information for users who selected option C originally
print("Talking about World Record times in certain events")
# if they selected B and chose an event, this is where they would be sent to
print("You have selected the event: ", eventInfo)
timeInfo = input("Please enter your best time (MM:SS.ss): ")
# same menu as above, sending to main, section B to choose a different event, section D for comparison, or exit program
...
elif section == "D":
# information for users who selected option C originally
print("Talking about top competitor's times in certain events and how younger athletes aspire to reach them, and the benefits of comparing times")
# if they selected B and chose an event, and input a time at C this is where they would be sent to
print("Your time of", timeInfo, "for", eventInfo, "has been compared to the World Record time of ____")
# an external file of all World Record times is then referred to, and compared to the user's input in timeInfo
# menus as above, main, going back to B, or C for different events or times respectively, or exit program
elif selection == "X":
exit()
else:
print("Try again, please ensure the letter is shown in the menu")
selection = printMenu()
while selection != 'X':
program(selection)
print()
selection = printMenu()
I am wondering if there is a way for users to input answers in option B, and skip directly to the section of code saying # if they selected B and chose an event, this is where they would be sent to, with information they input in section B (stored in eventInfo I would imagine)? I assume it would be the same process from C to D, and I am almost there, but obviously without those options being defined prior to wanting to jump to them, I get the error. Any help will be greatly appreciated! Thanks

Related

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!

Python main function loop with a menu function is not working?

I am currently a college student taking a python class. Our assignment is to create this program with functions. The main function calls the menu and then we write a loop in the main function to access the other functions based on the user response in the menu function.
I can't seem to get my loop to work. When I select a menu option nothing happens. For now, I just have print statements to test the calling of the functions. I want to make sure this works before I write the functions.
If anyone has an example of what the loop should look like to call the functions it would help me a lot.
def GetChoice():
#Function to present the user menu and get their choice
#local variables
UserChoice = str()
#Display menu and get choice
print()
print("Select one of the options listed below: ")
print("\tP\t==\tPrint Data")
print("\tA\t==\tGet Averages")
print("\tAZ\t==\tAverage Per Zone")
print("\tAL\t==\tAbove Levels by Zone")
print("\tBL\t==\tBelow Levels")
print("\tQ\t==\tQuit")
print()
UserChoice = input("Enter choice: ")
print()
UserChoice = UserChoice.upper()
return UserChoice
def PrintData():
print("test, test, test")
def AverageLevels():
print("test, test, test")
def AveragePerZone():
print("test, test, test")
def AboveLevels():
print("test, test, test")
def BelowLevels():
print("test, test, test")
def main():
Choice = str()
#call GetChoice function
GetChoice()
#Loop until user quits
if Choice == 'P':
PrintData()
elif Choice == 'A':
AverageLevels()
elif Choice == 'AZ':
AveragePerZone()
elif Choice == 'AL':
AboveLevels()
elif Choice == 'BL':
BelowLevels()
main()
The loop should start with the following:
while True:
Choice = GetChoice()
And the if conditions for the menu should follow at the same indent.
If you want to add an option to quit the program, add another elif statement as below:
elif Choice == "Q":
break
This will exit the loop and thus end the program.
(Excuse the many edits - using mobile)
You need to assign your Choice variable like so,
Choice = GetChoice()
Also, note that you can also delete line like this one,
UserChoice = str()
In python, you do not need to explicitly specify variables type.
And finally another small suggestion is to compare Choice.upper() to the values in the bottom of your code. This way, if someone enters 'p' it will still call PrintData()
You need to assign the return value of your GetChoice() function to the name Choice:
Choice = GetChoice()

Creating a "Flashcard" vocabulary program

I'd like to make a program in Python 3 that would be essentially vocabulary flashcards. I'd be able to list the terms, add a term, or display a random definition to try and accurately guess. Once guessed accurately, I would be given the option for another definition to guess. Alternatively, I'd like to just be able to display a random key:value pair, and to continue viewing pairs until I enter EXIT.
I have made most of the program using a dictionary, but am not sure how to go about with entering the proper command to enter the key for the definition displayed. If anyone could provide suggestions, I'd appreciate it! Also I got some sort of error message when entering this code in and had to do a bunch of indentations, not sure what I did wrong there.
import random
terms = {"1" : "def 1", #Dictionary of 'terms' and 'definitions'
"2" : "def 2",
"3" : "def 3"}
menu = None
while menu != "4":
print("""
DIGITAL FLASHCARDS!
1 - List Terms
2 - Add Term
3 - Guess Random Definition
4 - Exit
""")
menu = input("\t\t\tEnter Menu option: ")
if menu == "1": # List Terms
print("\n")
for term in terms:
print("\t\t\t", term)
input("\n\tPress 'Enter' to return to Main Menu.\n")
elif menu == "2": # Add Term
term = input("\n\tEnter the new term: ").upper()
if term not in terms:
definition = input("\tWhat is the definition? ")
terms[term] = definition
print("\n\t" + term, "has been added.")
else:
print("\n\tThat term already exists!")
input("\n\tPress 'Enter' to return to Main Menu.\n")
elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
print("\n\t\t\tType 'Exit' to return to Menu\n")
choice = random.choice(list(terms.values()))
print("\n\t" + choice + "\n")
guess = None
while guess != "EXIT":
guess = str(input("\tWhat is the term? ")).upper()
display a random definition to try and accurately guess. Once guessed accurately, I would be given the option for another definition to guess
Use terms.items() to get key and value at the same time.
Define the process of generating a new definition question into a function generate_question() to avoid duplicity.
elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
print("\n\t\t\tType 'Exit' to return to Menu\n")
def generate_question():
term, definition = random.choice(list(terms.items()))
print("\n\t" + definition + "\n")
return term
term = generate_question()
guess = None
while guess != "EXIT":
guess = input("\tWhat is the term? ").upper()
if guess == term:
print("Correct!")
if input("\tAnother definition?(y/n)").upper() in ["Y", "YES"]:
term = generate_question()
else:
break
Alternatively, I'd like to just be able to display a random key:value pair, and to continue viewing pairs until I enter EXIT.
elif menu == "4": # Random display a term-definition pair.
print("\n\t\t\tType 'Exit' to return to Menu\n")
exit = None
while exit != "EXIT":
term, definition = random.choice(list(terms.items()))
print(term + ":", definition)
exit = input("").upper() # Press enter to continue.
Remember to modify the beginning part:
while menu != "5":
print("""
DIGITAL FLASHCARDS!
1 - List Terms
2 - Add Term
3 - Guess Random Definition
4 - View term-definition pairs
5 - Exit
""")

why does it say "level" is not defined

I am making trying to make a text base game and I want to make a level selection
print ("You and your crew are pinned in the remains of a church on the top floor, with two wounded. Being fired at by German machine guns, matters will soon only get worse as you see German reinforcements on their way. Find a way to escape with your 9 man crew with minimal casualties.")
#Start up Menu
print ("Before you start the game ensure that you are playing in fullscreen to enhance your gaming experience")
print("")
print ("")
time.sleep(1)
print ("Menu")
print ('Instructions: In this game you will be given a series of paths. Using your best judgment you will choose the best path by using the "1" or "2" number keys, followed by pressing the "enter" button')
print ('If the wrong path is selected, there will be consequences of either death, or a lower final score.')
print ('Death will end the game, and you will be forced to start from the beginning of the level.')
time.sleep(1)
print ('If you will like to restart, press "r"')
print ('If you will like to quit, press "q"')
print ('If you want to play level 1, press "a"')
print ('If you want to play level 2, press "s"')
print ('you cannot restart or quit at this time')
print ('')
print ('')
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
over here, why does it say "level is not defined? and how can I fix it so the program works?
levelselection()
if level == "1":
print ("good job!")
First of all , level is a local variable to your function levelselection .
After that you are returning level variable but not saving it to some other variable.
Do like this -
levelselected = levelselection()
if levelselected == "1":
print ("good job!")
I would suggest you to read about python variables scope, this is a good source.
Explanation:
As level is initialized within the function levelselection you won't have access to the variable outside the function.
Solution:
1.You can fix this with defining level in a global scope.
2.Also, you can return level from the function as you did, but you will need to catch this return value, for example:
level = levelselection()
if level == "1":
print ("good job!")
you forgot to indent the return level. So in your current code, the return doesn't belong to the levelselection()function.
Try this:
def levelselection():
level=""
while level != "1" and level != "2":
level = input("Please select a level to play: ")
return level
level = levelselection()
if level == "1":
print("good job!")

Python Nested List - Changing and replacing individual items

I am completing a simple programming exercise (I am still new) where I am creating a character profile by allocating 30 points to 4 different character attributes. Program features are: show current profile, create a new profile, or change existing profile. First and second feature work fine, but there is problem with the last: the program is meant to unpack the nested list item (attribute + allocated score), ask for a new score, take the difference between the old and new and change the number of available points in the pool accordingly. Finally, add a new entry to the list (attribute + newly allocated score) at position 0 and then delete the entry at position 1, which should be the old entry for this attribute. Loop through the list, and done. However, once you execute the code you will see it won't work. Please see below the complete code:
options = ["Strength", "Health", "Wisdom", "Dexterity"]
profile = []
points = 30
choice = None
while choice != "0":
print(
"""
CHARACTER CREATOR PROGRAM
0 - Exit
1 - See current profile
2 - Build new profile
3 - Amend existing profile
"""
)
choice = input("Please choose an option: ")
print()
if choice == "0":
print("Good bye.")
elif choice == "1":
for item in profile:
print(item)
input("\nPress the enter key to continue.")
elif choice == "2":
print("You can now equip your character with attributes for your adventures.")
print("You have",points,"points to spent.")
print("Now configure your character: \n")
#Run the point allocation loop
for item in options:
point_aloc = int(input("Please enter points for " + str(item) + ":"))
if point_aloc <= points:
entry = item, point_aloc
profile.append(entry)
points = points - point_aloc
print("\nYour current choice looks like this: ")
print(profile)
input("\nPress the enter key to continue.")
else:
print("Sorry, you can only allocate", points," more points!")
print("\nYour current choice looks like this: ")
print(profile)
input("\nPress the enter key to continue.")
print("\nWell done, you have configured your character as follows: ")
for item in profile:
print(item)
input("Press the enter key to continue.")
elif choice == "3":
print("This is your current character profile:\n")
for item in profile:
print(item)
print("\nYou can change the point allocation for each attribute.")
for item in profile:
point_new = int(input("Please enter new points for " + str(item) + ":"))
attribute, points_aloc = item
diff = points_aloc - point_new
if diff >0:
points += diff
print("Your point allocation has changed by", -diff,"points.")
print(diff,"points have just been added to the pool.")
print("The pool now contains", points,"points.")
entry = item, point_new
profile.insert(0, entry)
del profile[1]
input("Press the enter key to continue.\n")
elif diff <0 and points - diff >=0:
points += diff
print("Your point allocation has changed by", -diff,"points.")
print(-diff,"points have just been taken from the pool.")
print("The pool now contains", points,"points.")
entry = item, point_new
profile.insert(0, entry)
del profile[1]
input("Press the enter key to continue.\n")
elif diff <0 and points - diff <=0:
print("Sorry, but you don't have enough points in the pool!")
input("Press the enter key to continue.\n")
else:
print("Sorry, but this is not a valid choice!")
input("Press the enter key to continue.\n")
input("\n\nPress the enter key to exit.")
Note: You need to create the profile first to run the changes.
Thanks in advance for your help!!
As the comments to your question indicate, you haven't asked your question in the best way. However, I see what's wrong with it. I could show you how to fix your current code, but the truth is that the best way to fix it is to rewrite it completely. As you do so, you should adopt the following strategies:
Break your code up into parts. In this case, I would advise you to create several different functions. One could be called main_loop, and would contain the logic for looping through the menu. It wouldn't contain any of the code for updating or displaying profiles. Instead, it would call other functions, display_profile, build_profile, and amend_profile. Those functions would accept variables such as options, profile, and points, and would return values such as options and points. This will enormously simplify your code, and make it much easier to test and debug. Here's an example of what main_loop might look like:
def main_loop():
options = ["Strength", "Health", "Wisdom", "Dexterity"]
profile = []
points = 30
choice = None
while choice != "0":
print(menu_string) #define menu_string elsewhere
choice = input("Please choose an option: ")
print()
if choice == "0":
print("Good bye.")
elif choice == "1":
display_profile(profile)
elif choice == "2":
profile, points = build_profile(options, profile, points)
elif choice == "3":
profile, points = amend_profile(profile, points)
else:
print("Sorry, but this is not a valid choice!")
input("Press the enter key to continue.\n")
input("\n\nPress the enter key to exit.")
See how much nicer this is? Now all you have to do is define the other functions. Something like...
def build_profile(options, profile, points):
# insert logic here
return profile, points
Another advantage to this approach is that now you can test these functions individually, without having to run the whole program.
Use the correct idioms for list modification. Modifying a list while iterating over it takes special care, and in some cases (such as when you change the length of the list by removing or adding items you've already iterated over) it won't work at all. There are ways to do what you try to do to profile, but for a beginning programmer I would recommend something much simpler: just create a new list! Then return that list. So in your amend_profile function, do something like this:
def amend_profile(profile, points):
# other code ...
new_profile = []
for item in profile:
attribute, points_aloc = item
# other code ...
new_proflie.append(entry)
# other code ...
return new_profile, points
Note also that this is where one of your main bugs is; you create an entry containing (item, point_new) instead of (attribute, point_new), so your new tuple has an item tuple inside it, instead of a lone attribute string as expected.

Categories