My program is supposed to record information for athletes in a race. When I select the option to add a score for an athlete, it calls the input_scores function, but then it won't get out of it? Also, for option "b", I want it to display the message that there's no record available if the list athlete_results is empty. I hope I've explained things ok, I am new to programming so any help is appreciated!
menu = """Choose an option:
'a' = Input score
'b' = Display results
'c' = quit
>
"""
athlete_results = []
choice = input(menu).strip().lower()
def input_scores():
name = input("Name: ").strip().title()
country = input("Country: ").strip().title()
time = input("Time: ").strip()
athlete_results.append({
"Name": name,
"Country": country,
"Time:": time
})
def display_results():
for athlete in athlete_results:
name, country, time = athlete_results.values
print(f"{name}| {country}| {time}s")
while True:
if choice == 'a':
input_scores()
elif choice == 'b':
if athlete_results:
display_results()
elif choice == 'c':
break
else:
print("Invalid option!!!")
Move the line
choice = input(menu).strip().lower()
to a line directly after while True:
while True:
choice = input(menu).strip().lower()
in order to have a chance to change the option or quit.
Related
I am having trouble with some undefined variables in my code for a school assignment using nested loops and functions. Also, if you happen to spot any other errors please lmk.
Code:
shopping_lists = [
['toothpaste', 'q-tips', 'milk'],
['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']
]
customer_input = ''
#prints shopping lists
print(shopping_lists)
print ('')
print("Press '1' to update an item, '2' to view an item, or '3' to view a list")
customer_input = input("What do you want to do? ")
if customer_input == '1':
def update_list(List, Item, newItem):
list = int(input('What list would you like to update? Answer using 1, 2, or 3. ')-1)
print (shopping_lists[list])
itm = int(input('What item would you like to view? ')-1)
print (shopping_lists[list][itm])
newItm = input('What would you like to change the item to? ')
shopping_lists[list][itm] = newItm
update_list(list, itm, newItm)
def view_item():
pass
def view_list():
pass
#While loop
while 'stop' not in customer_input:
update_list(list, itm, newItm)
I would rearrange your execution flow as follows.
shopping_lists = [
['toothpaste', 'q-tips', 'milk'],
['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']
]
def handle_action(action):
if action == '1':
update_list()
elif action == '2':
view_item()
elif action == '3':
view_list()
else:
pass
# What if an unrecognized action is used?
def update_list():
list_number = int(input('What list would you like to update? Answer using 1, 2, or 3. ')) - 1
print(shopping_lists[list_number])
itm = int(input('What item would you like to view? ')) - 1
print(shopping_lists[list_number][itm])
newItm = input('What would you like to change the item to? ')
shopping_lists[list_number][itm] = newItm
def view_item():
pass
def view_list():
pass
#While loop
customer_input = ''
while customer_input != 'stop':
print(shopping_lists)
print("Press 1 to update an item, 2 to view an item, or 3 to view a list")
customer_input = input("What do you want to do? ")
handle_action(customer_input)
Notice the difference on the usage of stop as a break word for the loop. And the handle_action function to control a switch of what you are doing.
I also renamed list to list_number because list is a type name in python.
I'm trying to check if any of the students are on probation and if they are, display which student please assist with the error code, the code is meant to check if anyone has violated probation, it also displays an error code, the except is normally key error, but when I was trying to figure out the problem i changed it to keyboard interrupt
if students[Student].is_on_probation:
KeyError: 0
students = {}
try:
while True:
from Student import Student
students['1'] = Student("Jim", "Business", 3.1, False)
viewing = False
viewingchange = input("Would you like to view something: ").lower()
if viewingchange == "y":
viewing = True
elif viewingchange == "yes":
viewing = True
else:
viewing = False
add = input("Would you like to add someone: ")
if add.lower() == "yes" or "y":
adder = str(input("Who would you like to add: "))
major = str(input("What is their major: "))
gpa = float(input("GPA: "))
is_on_probation = bool(input("is on probation: "))
students[str(len(students)+1)] = Student(adder, major, gpa, is_on_probation)
def checking():
if viewing:
checker = input("Would you like to view all students or student a/s: ")
if checker.lower() == "a":
print(students)
checkfor = input("Check for: ")
if checkfor.lower() == "probation":
for Student in range(len(students)):
print("works")
if students[Student].is_on_probation:
print("yeppp")
else:
pass
checkerdouble = False
elif checker.lower() == "s":
searchquery2 = input("And which attribute would you like to search: ")
test = input("Student ID: ")
dude = students[test]
if searchquery2.lower() == "Name".lower():
print(dude.name)
elif searchquery2.lower() == "Major".lower():
print(dude.major)
elif searchquery2.lower() == "GPA".lower():
print(dude.gpa)
elif searchquery2.lower() == "is on probation" or "iop" or "probation".lower():
print(dude.is_on_probation)
checkerdouble = True
checking()
except KeyboardInterrupt:
print("Error code: " + "45345593M3940249525")
Your students dictionary uses string representations of numbers that start at str(1). So the loop should do the same. I think it would be better to just use int keys.
for student_id in map(str, range(1, len(students)):
if students[student_id].is_on_probation:
print(student_id)
This would work but it relies on the dictionary keys being dense. I would prefer to do:
for student_id in sorted(students, key=int):
if students[student_id].is_on_probation:
print(student_id)
Some might object to the indexing, as one can do:
for student_id, student in sorted(students.items(), key=lambda v: int(v[0])):
if student.is_on_probation:
print(student_id)
I am writing a code for student record... This is what i've tried
def std1():
stud=input('Enter Student name')
crs=[]
crst=int(input('How many courses you want to enter'))
for i in range(crst):
EnterCourse = input('Course')
crs.append(str(EnterCourse))
stdrec1=(stud,crs)
return main()
def std2():
stud=input('Enter Student name')
crs=[]
crst=int(input('How many courses you want to enter'))
for i in range(crst):
EnterCourse = input('Course')
crs.append(str(EnterCourse))
stdrec2=(stud,crs)
def main():
print("""
Welcome to the Student Database
[1] = Enter Student Record
[2] = Enter Second Student Record
[3] = Enter Third Student Record
[4] = Print the record
""")
action = input('What Would you like to do today? (Enter number to Continue) ')
if action == '1':
std1()
elif action == '2':
print('2')
elif action == '3':
print('3')
elif action == '4':
print(#all the list together)
else:
print('Error! Wrong Menu Selected | Calling the FBI now')
How can i make all the tuples print together when the option 4 is selected which are currently inside their own function and in case user hasn't work on a 2nd option for example. it will print like this
First student --- Name , [courses]
2nd student ----- You haven\t't entered anything
Do you want to enter Y or N
Y will return that function and N will stop the function.
and after input data in each option how will it return the main function again so user can re-select the options
I am making a simple text-based RPG in Python. Currently I have two methods for most rooms, one for when they first enter and one if they return. Is there a way that I can make sure that they haven't been in that room before without another method?
For example, if I had a method named tomb() i create another method called tombAlready() that contains the same code except for the introduction text to the room.
So if I had
slow_type("\n\nTomb\n\n")
slow_type("There is an altar in the middle of the room, with passages leading down and west.")
choice = None
while choice == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "d":
catacombs()
elif userInput == "n":
altar()
elif userInput == "w":
throneroom()
else:
slow_type("You cannot perform this action.")
Then tombAlready() would have the same code except for slow_type("There is an altar in the middle of the room, with passages leading down and west.")
What you want is state associated with a function. Use an object with a method:
class Room:
def __init__(self, description):
self._description = description
self._visited = False
def visit(self):
if not self._visited:
print(self._description)
self._visited = True
Then you can have a Room object for each room:
catacombs = Room('There is a low, arched passageway. You have to stoop.')
tomb = Room('There is an altar in the middle of the room, with passages leading down and west.')
throneroom = Room('There is a large chair. It looks inviting.')
You can visit a room twice but it only prints its description once:
>>> catacombs.visit()
There is a low, arched passageway. You have to stoop.
>>> catacombs.visit()
A beginner's problem, here it goes:
I'm writing a program which keeps records of a game of darts. The user types in the players and their respective scores. It's possible to do a query about a player's scores and ask the program for the best overall score between all the players. I have the following functions:
add_score
return_players_score
return_best_score
exit_program
main
In main(), we begin by creating a new empty dictionary (say, players = {}). Then we ask the user to input a number that takes him/her to the function of choice (1: add_score etc.).
Now, once we're in add_score and have added a key:value pair (player:score), we need to go back to inputting the number taking to the function of choice. I implemented it simply by writing main() to the end of add_score.
That, however, takes us to the beginning, where there's players = {} and thus whatever data we input in add_score gets wiped out. This then affects other functions and the program remains useless as long as it forgets everything right away. How to solve this?
I'd paste the actual code but it's not in English and it's an assignment anyway...
Thanks.
Rather than calling main() from each of your other functions, you should just return (or run off the end of the function, which is equivalent to return None). Since you need the main function to run things repeatedly, you should use a loop.
def main():
players = {}
while True: # loop forever (until a break)
choice = input("what do you want to do (1-4)")
if choice == "1":
add_score(players)
elif choice == "2":
return_players_score(players)
#...
elif choice == "4":
break # break out of the loop to quit
else:
print("I didn't understand that.")
If you have a loop that does something like the following..
example:
while True:
players = {}
some code adding to players
This loop will always reset players to {}
However, if you do:
players = {}
while something:
some code adding to players
then players is not being reset at the start of each iteration through the loop
But your question is not clear
If you have something like this:
def add_score(dicccionary):
#do something with diccionary
main()
def main():
dicccionary = {}
while something:
option = input("option")
if option == 1:
addscore(dicccionary)
else:
#otherfunction
main()
your reset problem can be solve like:
dicccionary = {} #global variable
def add_score():
#do something with diccionary
main()
def main():
option = input("option")
if option == 1:
addscore()
else:
#otherfunction
main()
By the way, you shouldn't make it this way, try something as:
dicccionary = {} #global variable
def add_score():
#do something with diccionary
def main():
while somecondition:
option = input("option")
if option == 1:
addscore()
else:
#otherfunction
main()
If I was doing it for real then I would go for something like:
import sys
class ScoreKeeper(object):
def init(self):
self.scores = {}
def add_score(self, player, score):
self.scores[player] = score
def _print_player_score(self, player, score):
print 'player:', player, 'score:', score
def print_scores(self):
for player, score in self.scores.items():
self._print_player_score(player, score)
def best_score(self):
best, player = 0, "no player"
for player, score in self.scores.items():
if score > best:
best, player = score, player
self._print_player_score(player, best)
if __name__ == '__main__':
scorer = ScoreKeeper()
quit = lambda: sys.exit()
choices = quit, scorer.add_score, scorer.print_scores, scorer.best_score
def help():
print 'Enter choice:'
for index, c in enumerate(choices):
print '%d) %s' % (index, c.__name__)
def get_integer(prompt):
res = raw_input(prompt)
try:
return int(res)
except:
print 'an integer is required'
return get_integer(prompt)
def get_choice():
choice = get_integer('choice? ')
if not 0 <= choice < len(choices):
help()
return get_input()
return choice
help()
choice = get_choice()
while(choice):
args = []
if choices[choice] == scorer.add_score:
args.append(raw_input('player name? '))
args.append(get_integer('score? '))
choices[choice](*args)
choice = get_choice()
quit()