I am working on an assignment, the goal is this...
create a program for a school tournament where participants can enter a tournament, then points are alocated to the team based on where they place in the event. there will be events such as (dodgeball, football, math, english) but i will work on these at a later date
at the moment i am trying to construct some code that will asign a point to a team, which is working. and then print the leaderboard(list of teams) this does not work
the leaderboard() function is not working and i do not know why not, please help me
class Team:
def __init__(self, num, name, size, score):
self.num = num
self.name = name
self.size = size
self.score = score
def add_victory(self):
self.score += 1
def __repr__(self):
return f'Team Number: {self.num} |-| Team Name: {self.name} |-| Member Count: {self.size} |-| Team Score: {self.score}'
def NewTournament():
teams = []
TeamCounter=int(input('How many Teams will be in the tournament? '))
print('')
for i in range(TeamCounter):
NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
MemberCount=int(input('How Many Members in Team? '))
print('')
teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )
def Score(teams):
winner = input('Which Team Won the Event? ')
for team in teams:
if team.name == winner:
team.add_victory()
break
print('Updated Leaderboard')
def Leaderboard():
for t in teams: #does not work, does nothing
print(t)
def Menu():
MenuLoop=1
while MenuLoop==1:
print('1.Create Tournament')
print('2.Update Existing Tournament')
print('3.View Leaderboard')
print('4.Exit')
MenuOption=input('')
if MenuOption=='1':
print('Creating Tournament')
NewTournament()#runs the new tournament function
MenuLoop-=1
Menu()
elif MenuOption=='2':
print('Updating Tournament')
MenuLoop-=1
EventName=input('Which Event Was Completed? ')
winner=input('Which Team Won the Event? ')
print('Event Winner:', winner, '||', 'Event:',EventName)
print('Is this correct? Y/N')
Check=input('')
if Check=='y':
print('Updating Leaderboard')
Score(teams)
Menu()
elif MenuOption=='3':
MenuLoop-=1
Leaderboard()
elif MenuOption=='4':
print('Exiting Program...')
else:
print('Error, please choose an option from the list below.')#keeps looping if user is not choosing a correct number from list
#start of program
teams = []
print('░██╗░░░░░░░██╗███████╗██╗░░░░░░█████╗░░█████╗░███╗░░░███╗███████╗')
print('░██║░░██╗░░██║██╔════╝██║░░░░░██╔══██╗██╔══██╗████╗░████║██╔════╝')
print('░╚██╗████╗██╔╝█████╗░░██║░░░░░██║░░╚═╝██║░░██║██╔████╔██║█████╗░░')
print('░░████╔═████║░██╔══╝░░██║░░░░░██║░░██╗██║░░██║██║╚██╔╝██║██╔══╝░░')
print('░░╚██╔╝░╚██╔╝░███████╗███████╗╚█████╔╝╚█████╔╝██║░╚═╝░██║███████╗')
print('░░░╚═╝░░░╚═╝░░╚══════╝╚══════╝░╚════╝░░╚════╝░╚═╝░░░░░╚═╝╚══════╝')#welcome user
print('')
Username=input('Enter Username: ')
Password=input('Enter Password: ')
if Username =='Admin' and Password == 'Admin':#very basic login system for security of school
print('Logging in...')
print('User Verified')
Menu()
else:
print('User Does Not Exist.')#stops pupils gaining unauthorised access
please understand i am still very new to python so the layout may be a mess or complicated or may not even make any sense to you, i am trying to make sense of it for you
Your issue comes from how you are storing your teams. At the bottom you initialize global teams list as teams = []. Then later in NewTournament you create a new teams list which clashes with the global one:
def NewTournament():
teams = []
TeamCounter=int(input('How many Teams will be in the tournament? '))
print('')
for i in range(TeamCounter):
NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
MemberCount=int(input('How Many Members in Team? '))
print('')
teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )
Because of this when you append the new Team to teams the change does not change the global teams which you use when listing the leader board. The simplest solution is to just remove the local teams variable:
def NewTournament():
TeamCounter=int(input('How many Teams will be in the tournament? '))
print('')
for i in range(TeamCounter):
NameOfTeam=input(f'Please Enter Team {i+1} Name: ')
MemberCount=int(input('How Many Members in Team? '))
print('')
teams.append( Team( i+1, NameOfTeam, MemberCount, 0) )/
A better fix would be to create a new Tournament class which can store the state of the tournament (the list of teams) more clearly, and remove your need to have top level methods which rely on global variables which is rarely a great idea.
Related
I am new to programming and am trying to create a program that will ask the user questions then store them in an instance to be used for matchmaking but I am having trouble being certain that the inputs are being properly stored. This is what I currently have.
ask_name = input("What is your name? ")
print(f"Hello {ask_name}!")
class Member:
"""A place to store member interest info"""
def __init__(self, book_list, movie_list, game_list):
"""Initialize book, movie, and game interest attributes"""
self.book_list = book_list
self.movie_list = movie_list
self.game_list = game_list
member_0 = Member([''],[''],[''])
active = True
while active:
books = input(f"What are your favorite books? Send one at a time. \n\t Send 'movies' when finished. ")
if books == 'movies':
active = False
else:
answer = input(f" Is {books} one of your favorite books?\n\tSend 'yes' if it is. Send 'no' if it is not. ")
if answer == 'yes':
print(f"{books} has been added to favorite books.")
member_0.book_list.append({books})
print(f"{member_0.book_list}")
active = True
while active:
movies = input(f"What are your favorite movies? Send one at a time.\n\tSend 'games' when finished. ")
if movies == 'games':
active = False
else:
answer = input(f" Is {movies} one of your favorite movies?\n\tSend 'yes' if it is. Send 'no' if it is not. ")
if answer == 'yes':
print(f"{movies} has been added to favorite movies.")
member_0.movie_list.append({movies})
print(f"{member_0.movie_list}")
active = True
while active:
games = input(f"What are your favorite video games? Send one at a time.\n\tSend 'done' when finished. ")
if games == 'done':
active = False
else:
answer = input(f" Is {games} one of your favorite games?\n\tSend 'yes' if it is. Send 'no' if it is not. ")
if answer == 'yes':
print(f"{games} has been added to favorite video games.")
member_0.game_list.append({games})
print(f"{member_0.game_list}")
I'd suggest keeping your lists in a dictionary rather than as three different variables, and writing a function that will let you build any given list, so you don't have to copy+paste all of that code for each one:
class Member:
"""A place to store member interest info"""
def __init__(self, name):
self.name = name
self.favorites = {}
def ask_favorites(self, things, done):
if things not in self.favorites:
self.favorites[things] = []
while True:
print(f"What are your favorite {things}? Send one at a time.")
thing = input(f"\tSend '{done}' when finished. ")
if thing == done:
return
print(f" Is {thing} one of your favorite {things}?")
if input("\tSend 'yes' if it is. Send 'no' if it is not. ") != 'yes':
continue
self.favorites[things].append(thing)
print(f"{thing} has been added to favorite {things}.")
print(self.favorites[things])
def print_favorites(self):
print(f"These are a few of {self.name}'s favorite things:")
for things, faves in self.favorites.items():
print(f"Favorite {things}: {', '.join(faves)}")
ask_name = input("What is your name? ")
print(f"Hello {ask_name}!")
member_0 = Member(ask_name)
member_0.ask_favorites("books", "movies")
member_0.ask_favorites("movies", "games")
member_0.ask_favorites("games", "done")
member_0.print_favorites()
I am trying to allow a member to leave the Team if they so wish. By doing this, the system will delete them and their user ID will become available to the next person who wishes to join the team. I am receiving an error with my code. Can someone please advise what I am doing wrong and how this can be achieved?
I would like my add members and remove members to update all the time, based on user input and the needs of the members. I hope this makes sense!
For example: If 'Carl' decided to leave, he would be removed and the next member to join would be assigned the membership ID '2'
Below is my code:
all_users = []
class Team(object):
members = []
user_id = 0
def __init__(self, first, last, address):
self.user_id = Team.user_id
self.first = first
self.last = last
self.address = address
self.email = first + '.' + last + '#python.com'
Team.user_id += 1
Team.members.append(self)
def __str__(self):
print()
return 'Membership ID: {}\nFirst Name: {}\nSurname: {}\nLocation: {}\nEmail: {}\n'.format(self.user_id,
self.first, self.last,
self.address,
self.email)
print()
#staticmethod
def all_members():
for user in all_users:
print(user)
#staticmethod
def add_member():
print()
print("Welcome to the team!")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
all_users.append(Team(first_name, second_name, address))
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
unique_id = input("Finally, what is your User ID?\n")
if unique_id in all_users:
del unique_id
all_users(User(first_name, second_name, address))
def main():
user_1 = Team('Chris', 'Parker', 'London')
user_2 = Team('Carl', 'Lane', 'Chelsea')
all_users.extend([user_1, user_2])
continue_program = True
while continue_program:
print("1. View all members")
print("2. Want to join the team?")
print("3. Need to leave the team?")
print("3. Quit")
try:
choice = int(input("Please pick one of the above options "))
if choice == 1:
Team.all_members()
elif choice == 2:
Team.add_member()
elif choice == 3:
Team.remove_member()
elif choice == 4:
continue_program = False
print()
print("Come back soon! ")
print()
else:
print("Invalid choice, please enter a number between 1-3")
main()
except ValueError:
print()
print("Please try again, enter a number between 1 - 3")
print()
if __name__ == "__main__":
main()
The remove_member method is wrong for several reasons. The line del unique_id will not remove the value from all_users, which is just a list of Team Members. And you shouldn't have to ask the user for all of this information - just the ID (or the name) would be enough.
What I suggest is:
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
unique_id = input("what is your User ID?\n")
unique_id = int(unique_id)
for i, user in enumerate(all_users):
if user.user_id == unique_id:
all_users.remove(i)
break
If it is important that the user ids are reused, you can keep a list of user ids that are available again. When creating a new member, you can first check that list, and use an old id if there is one.
You can also choose not to reuse the user ids of removed users. An id doesn't really have a meaning and not reusing it makes it simpeler for you.
Finally, you might want to restructure your code:
Team(first_name, second_name, address)
This doesn't make sense: a team with a first name, last name and adress! Better would be to have two classes:
team = Team()
user = User(first_name, second_name, address)
team.add_member(user)
team.remove_member(user)
Some other tips:
# This won't work, because all_users contains Team instances, not numbers. So the user will never be found.
if unique_id in all_users:
# This won't do anything: `del` only removes the access to the variable (might free up memory in heavy applications). It doesn't remove the user from all_users
del unique_id
I'm trying to create a text-based adventure game and all is going well until I encountered a problem with assigning points to attributes. I've been using this website to help with the process but realized that it might be in Python 2. Here's all that I've done so far code:
#Date started: 3/13/2018
#Description: text-based adventure game
import random
import time
def display_intro():
print('It is the end of a 100-year war between good and evil that had \n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n' +
'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n' +
'wed and had you. \n')
time.sleep(3)
def get_gender(gen=None):
while gen == None: # input validation
gen = input('\nYour mother had a [Boy or Girl]: ')
return gen
def get_name(name = None):
while name == None:
name = input("\nAnd they named you: ")
return name
def main():
display_intro()
gender_num = get_gender()
charater_name = get_name()
print("You entered {} {}.".format(gender_num, charater_name))
if __name__ == "__main__":
main()
character_name = get_name()
# Assignning points Main
my_character = {'name': character_name, 'strength': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
#This is a sequence establises base stats.
def start_stat():
print("\nThis is the most important part of the intro\n")
time.sleep(3)
print("This decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category:
Strength, Health, Wisdom, or Dexterity.\n")
def add_charater_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much?"))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
else:
print("That attribute doesn't exist!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_charater_points()
else:
display_intro()
gender_num = get_gender()
charater_name = get_name()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_charater_points()
elif choice == "2":
pass
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
And here's what happens when I run it:
It is the end of a 100-year war between good and evil that had
killed more than 80% of the total human population.
The man who will soon be your father was a brave adventurer who fought for
the good and was made famous for his heroism.
One day that brave adventurer meet a beautiful woman who he later wed and
had you.
Your mother had a [Boy or Girl]: boy
And they named you: Name
You entered boy Name.
And they named you: Name
Are you sure you want to continue?
yes
This is the most important part of the intro
This decides your future stats and potentially future gameplay.
You have 20 points to put in any of the following category: Strength,
Health, Wisdom, or Dexterity.
Which attribute do you want to assign it to? strength
By how much? 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice: 3
name : Name
strength : 0
wisdom : 0
dexterity : 0
points : 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice:
Oh, and prompt for the name of the play goes again twice for some reason. Also, what does the my_character.keys() under def add_charater_points() mean? Since I just started to learn to code python, if there are any other tips you guys can give me it would be greatly appreciated.
The last two lines of this snippet
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
add the character points to the attribute, and immediately subtract them again. I think you might mean
my_character['points'] -= amount
Your repeated prompt is probably because you have a whole lot of code that logically seems to belong in function main() but is coded to run after main() finishes.
This is the function defined in class "Roster"
class Roster:
def __init__(self, name, phone, jersy):
self.name = name
self.phone = phone
self.jersy = jersy
def setName(self, name):
self.name = name
def setPhone(self, phone):
self.phone = phone
def setnumber(self, jersy):
self.number = jersy
def getName(self):
return self.name
def getPhone(self):
return self.phone
def getNumber(self):
return self.jersy
def displayMenu(self):
print ("==========Selection Menu==========")
print ("1. Display the Roster")
print ("2. Add a Player to the Roster")
print ("3. Remove a Player from the Roster")
print ("4. Change a Player Name displayed in the Roster")
print ("5. Load the Roster")
print ("6. Save the Roster")
print ("7. Quit")
print ()
return int (input ("Selection>>> "))
def displayRoster(self):
print ("****Team Roster****")
print ("Player's Name:", self.name)
print ("Player's Telephone number:", self.phone)
print ("Player's Jersey number:", self.jersy)
This is the code:( I understand that you don't have to "Import" a class into itself so there is no Import call)
Players = {}
def addPlayer(Players):
newName = input ("Add a player's Name: ")
newPhone = input ("Phone number: ")
newNumber = input ("Jersey number: ")
Players[newName] = newName, newPhone, newNumber
return Players
def removePlayer(Players):
removeName = input ("What name would you like to remove? ")
if removeName in Players:
del Players[removeName]
else:
print ("Name was not found!")
return Players
def editPlayer(Players):
oldName = input ("What name would you like to change? ")
if oldName in Players:
newName = input ("What is the new name? ")
newPhone = input ("Phone number: ")
newNumber = input ("Jersey number: ")
Players[newName] = newName, newPhone, newNumber
del Players[oldName]
print ("***", oldName, "has been changed to", newName)
else:
print ("Name was not found!")
return Players
def saveRoster(Players):
print("Saving data...")
outFile = open("D:\Documents\Grantham\Python Projects\Python Week Six\Roster.txt", "wt")
for x in Players.keys():
name = Roster.getName(Players)
phone = Roster.getPhone(Players)
jersy = Roster.getNumber(Players)
outFile.write("name+","+phone+","+jersy+","\n")
print("Data saved.")
outFile.close()
return Players
def loadRoster():
Players = {}
filename = input("Filename to load: ")
inFile = open(Filename(Players), "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, jersy = inLine.split(",")
Players[name] = RosterClass.Players(name, phone, jersy)
print("Data Loaded Successfully.")
inFile.close()
return Players
print ("Welcome to the Team Manager")
menuSelection = Roster.displayMenu ('Players')
while menuSelection != 7:
if menuSelection == 1:
myRoster.displayRoster (Players)
elif menuSelection == 2:
Players = addPlayer (Players)
elif menuSelection == 3:
Players = removePlayer (Players)
elif menuSelection == 4:
Players = editPlayer (Players)
elif menuSelection==5:
loadRoster(Players)
elif menuSelection==6:
saveRoster(Players)
menuSelection = Roster.displayMenu (Players)
print ("Exiting Program...")
I keep getting this error:
Traceback (most recent call last):
File ".idea/Adv Team Roster.py", line 108, in <module>
Roster.displayRoster ('Players')
File ".idea/Adv Team Roster.py", line 39, in displayRoster
print ("Player's Name:", self.name)
AttributeError: 'str' object has no attribute 'name'
I'm also having problems with the save/load routine but that's another post.
Your code has a number of conceptual problems that you need to solve before you can start trying to run it and start asking for help with compiler errors. Here are three, to get you started.
(1) Your Roster class is designed to be instantiated, but you never create an instance. Whenever you write a class, among the early questions you should ask yourself are, "What code will create instances of this class? Under what circumstances? How will that code get the data it needs to create an instance? What will that code do with the instance right after it has created the instance?"
(2) Your Roster class is misnamed, which is probably confusing you. A roster is a list of players. Your Roster is data about a single player. I recommend renaming Roster to Player, creating some data structure (like your current Players) called roster to hold a bunch of players, and then following the consequences of that change.
(3) Once you have a clear idea of what rosters and players are, you can ask questions like, "Where will I store rosters and players? How will I pass them around to different parts of my code? What functionality should be associated with a roster? with a player? with the top level of my code? with other entities that I haven't thought about yet?"
After all that thinking, you might come the conclusion that displayPlayer should be a function on the Player class and that you therefore need to rename displayRoster to displayPlayer. Since you will have created instances of Player, perhaps one called myplayer (that's just an example name), you will now be able to say myplayer.displayPlayer(), and Python will run the displayPlayer code with self automatically set to the myplayer instance. At that point the compiler error you are complaining about will disappear, not because you "fixed" it, but because it naturally goes away once you are thinking clearly about your system.
And in general, that is the way to think about compiler errors: If it's not immediately obvious how to fix it, then it's probably a sign that you aren't thinking clearly about your system, so you need to take a step back and think about higher-level problems than the specific error.
I am trying to create a simple database on python that:
- Add a record, delete a record, report on the database
(I am very new to this program and programming in general)
*NOTE: I am aware there are programs like SQL but my professor wants us to create a a database simply with what we learned in class *
I am having serious trouble on being able to store: ID, Class Name, and Class instructor
into one record of "Classes". I have been able to display the class ID and class name but I'm not sure how to add an instructor's name.
This is what I have currently:
def print_menu():
print('1. Print Class Records')
print('2. Add a Class')
print()
classes = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
menu_choice = int(input("Type in a number (1-5): "))
if menu_choice == 1:
print("Class Reports:")
for x in classes.keys():
print("Class ID: ", x, "\tClass Name:", classes[x], "\tClass Instructor:",)
print()
elif menu_choice == 2:
print("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = className
elif menu_choice != 5:
print_menu()
I feel that I will be able to do the rest of the professor's requirements for this project but I have been stuck on this part for days with no response from my professor
I would highly appreciate quick responses as this assignment is due tonight at 11:59 and I am reaching out for help here as a last resort.
Thank you!
In your case, what you can do is, insert the ID as a key for each class and then insert a dictionary as it's value. What I mean by this is that each key on the classes dict, points to another dictionary as its value.
elif menu_choice == 2:
print ("Add ClassID, Class Name, and Instructor Name")
classID = input("ID: ")
className = input("Class Name: ")
classInst = input("Class Instructor: ")
classes[classID] = {"className" : className, "classInst" : classInst}
and printing the values as
print("Class ID: ", x , "\tClass Name:" , classes[x]["className"] , "\tClass Instructor:" , classes[x]["classInst"])