Cant get my elif functions right - python-3.x

menu_item = MainMenu = ["Display Team Roster", "Add Member", "Remove Member", "Edit Member", "Exit Program"]
while menu_item != 9:
print("Welcome to the Team Manager!")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member")
print("9. Exit Program.")
menu_item = int(input("Selection:"))
elifmenu_item == 1
print(current)
current = 0
while len(MainMenu) > 0:
current < len(MainMenu)
print(current, ".", MainMenu[current])
current = current + 1
elifmenu_item == 2
name = input("Enter new member's name:")
MainMenu.append(name)
elifmenu_item == 3
del_name = input("Enter member name to be removed:")
del_name in MainMenu
item_number = MainMenu.index(del_name)
del MainMenu[1]
elifmenu_item == 4
old_name = input("Enter the name of the member you want to edit:")
old_name in MainMenu
item_number = MainMenu.index(old_name)
new_name = input("Enter the new name of the member:")
MainMenu[1] = new_name
else:
print("Goodbye")
Write a modularized program that will utilize a main menu to control the program’s functions and a list to store the members of your team. The following functions that your program needs to include:
•Print the current member list.
•Add a new member.
•Remove a member.
•Modify an existing member.
•Exit the program

elif is not a function, it is language element just like while, if.
It has to be used together with if (just like else), example:
if a == '1':
print('1')
elif a == '2':
print('2')
else:
print('other')
In your case you have elifmenu_item == 1 which is wrong, you should have a space after elif and you should start with an if, only subsequent cases use elif.

Related

create lists with different index in python

I am trying to create a list using a loop, but I want the group to have the same index. Using append, it merges them together. What am I doing wrong?
L=[]
l=[]
def information():
i=0
while i <= 3:
if i==0:
first_name = str(input('First Name : '))
l.append(first_name)
i += 1
elif i==1:
last_name = str(input('Second Name : '))
l.append(last_name)
i += 2
elif i > 2:
wish = str(input('If you wish to continue Press Y/y or Press N/n:'))
if wish == 'y' or wish == 'Y':
L.append(l)
start()
elif wish != 'y' or wish != 'Y':
break
def start():
information()
start()
print('l', l)
print('L ', L)
My desired output is:
[['sachin', 'tendulkar'],['sachin', 'tendulkar'],['sachin', 'tendulkar']]
and I am getting this instead:
['sachin', 'tendulkar','sachin', 'tendulkar']
A little different than what you had going but this might work
Names = []
def information():
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
while ((wish == 'y') or (wish == 'Y')):
fname = str(input('First Name: '))
lname = str(input('Last Name: '))
Names.append([fname, lname])
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
information()
print (Names)

What is the correct way to format my code?

I have been trying to resolve my script with no results. I can't get
the load data to display. It is saving in members.txt and can read
it manually if opened. If someone can give any other advice on the
script as a whole it would be greatly appreciated.
I have reasearced greatly changed script around still have no luck.
import os if 'file' in vars():
wk_dir = os.path.dirname(os.path.realpath('file')) else:
print('We are running the script interactively')
class playerCLass(object):
name = ""
phone = ""
number = 0
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setnumber(self, number):
self.number = number
def getname(self):
return self.name
def getphone(self):
return self.phone
def getnumber(self):
return self.number
def display_data(self):
print("")
print("Member information: ")
print("Name:", self.name)
print("Phone number:", self.phone)
print("Jersey number:", self.number)
def displayMenu():
print("===========Menu Selections===========")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
print("")
return int(input("<<Selection>> "))
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(players):
print(x)
x = x + 1
def addPlayer(players):
newName = input("Type in member's name to be added to the roster:")
newPhone = input("Type in the member's phone number:")
newNumber = int(input("Type in the member's jersey number:"))
players[newName] = playerCLass(newName, newPhone, newNumber)
return players
def removePlayer(players):
name = input("Enter member's name to be removed:")
if name in players:
del players[name]
else:
print("member's name not found in list: ")
return players
def editPlayer(players):
oldName = input("Enter the name you want to edit: ")
if oldName in players:
newName = input("Enter a new name: ")
newPhone = input("Enter new phone number: ")
newNumber = int(input("Enter new jersey number: "))
players[oldName] = playerCLass(newName, newPhone, newNumber)
else:
print("No such name in memory: ")
return players
def saveData():
filename = input("Filename to save: ")
print("Saving data...")
outFile = open(filename, "wt")
for x in players.keys():
name = players[int(x)].getname()
phone = players[int(x)].getphone()
number = str(players[x].getnumber())
outFile.write(name + "," + phone + "," + number + "\n")
print("Data saved.")
outFile.close()
def loadData():
players = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, number = inLine.split(",")
players[name] = (name, phone, number)
print("Data Loaded Successfully.")
inFile.close()
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
print()
while menuSelection != 9:
if menuSelection == 1:
printPlayer(players)
elif menuSelection == 2:
players = addPlayer(players)
elif menuSelection == 3:
players = removePlayer(players)
elif menuSelection == 4:
players = editPlayer(players)
elif menuSelection == 5:
saveData()
elif menuSelection == 6:
loadData()
menuSelection = displayMenu()
print("Exiting Program...")
If your issue is specifically not getting printPlayer to work you can do
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
#Iterate through dictionary of player name and player object and call
#display data on each of them
else:
for name, player in players.items():
print(player.display_data())
If you then run the code and input according to the statements you wrote, you should get something like this.
Welcome to the Team Manager
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
No current members in memory.
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 2
Type in member's name to be added to the roster:Joe
Type in the member's phone number:123
Type in the member's jersey number:456
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
Member information:
Name: Joe
Phone number: 123
Jersey number: 456
None
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>>

Beginner Python list, defining variable

So I originally completed this task with nothing but a few if, elif statements. But it was requested that I break the work of those statements out into a separate functions as an additional exercise. I need to acquire names to add to a list and have the ability to edit or remove the names. But Im struggling to have the functions return their output to the list.
Here is what I have so far
print("Roster Management")
def addplayer():
name=input("Enter new player name: ")
roster = [name]
list(roster)
roster.append(name)
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name)
def editplayer():
oldname = input('Enter name you want to edit: ')
newname = input('Enter new name: ')
[x.replace(oldname, newname) for x in roster]
while 1==1:
print('---------- Main Menu ------------')
print("Choose from the following options")
print('1. Display Team Roster')
print('2. Add Member')
print('3. Remove Member')
print('4. Edit Member')
print('9. Exit Program')
print(" ")
selection = input("Enter Selection: ")
if selection == '1':
for x in roster:
print(roster)
elif selection == '2':
addplayer()
elif selection == '3':
removeplayer()
elif selection == '4':
editplayer()
elif selection == '9':
print("Closing program...")
break`enter code here`
There're few things that are wrong with your code:
#1
roster = [name] # this creates a new list with a single element in it instead of appending to some existing list
list(roster) # you're trying to convert a list to a list, so not needed
roster.append(name) # you should've some local/global roaster to append to
#2
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name) # again, you should've some local/global roaster to append to
#in case of local you should return the list for further usage, in case of global you can simply remove
#3
[x.replace(oldname, newname) for x in roster]
# again you're neither updating any existing list/ nor returned anything
# also check if `x==oldname` then replace with new name
#4
for x in roster:
print(roster) # x is what you should be printing, not the whole list (roaster)
So, your updated code with these changes would be something like this:
roster = []
def addplayer():
name=input("Enter new player name: ")
roster.append(name)
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name)
def editplayer():
global roster
oldname = input('Enter name you want to edit: ')
newname = input('Enter new name: ')
roster = [newname if x == oldname else oldname for x in roster]
print("Roster Management")
while 1==1:
print('---------- Main Menu ------------')
print("Choose from the following options")
print('1. Display Team Roster')
print('2. Add Member')
print('3. Remove Member')
print('4. Edit Member')
print('9. Exit Program')
print(" ")
selection = input("Enter Selection: ")
if selection == '1':
for x in roster:
print(x)
elif selection == '2':
addplayer()
elif selection == '3':
removeplayer()
elif selection == '4':
editplayer()
elif selection == '9':
print("Closing program...")
break
Add
return list
at the end of your definition because right now the definition doesn't know what it is supposed to return. Also in your, if statement you should have
print(def())
instead of just
def()
Hope this helps

How do I print a variable within a class' if statement?

I'm trying to print a variable in Python using the following code:
from time import sleep
import random
class Hero:
def __init__(self,name):
self.name = name
if name == "rock":
self.health = 50
self.attack = 10
elif name == "paper":
self.health = 70
self.attack = 7
elif name == "scissors":
self.health = 100
self.attack = 5
def dmg(self, other):
other.ehealth -= self.attack
start = 1
while start == 1:
name = input("Pick a class [rock/paper/scissors]")
if name != "rock" or "paper" or "scissors":
print ("That player does not exist. Try again.")
start = 1
else:
start = 1
player = Hero(name)
enemyName = ["erock", "epaper", "escissors"]
ename = random.choice(enemyName)
print ("Your character is", name, "which comes with", self.health, "health, and", self.attack, "attack.")
print("")
sleep(1)
print ("Your enemy is", ename, "which comes with", ehealth, "health, and", eattack, "attack.")
I can't figure out a way to access and print the variable "self.health" under the "Hero" class. I can access "name" just fine. Maybe it's the fact that it's under an if statement? Can someone help me out?
self is just a parameter name used inside the methods. Don't use it outside the method.
To access the variables refer to them using the object name (player) like this
player.health
The name variable you are printing "works" because it's not from the object. You should use the same notation to access that too:
player.name

Return to main function in python

Working on Python 3.4.3
Let's say I have created three fuctions:
def choosing(mylist=[]):
print("We will have to make a list of choices")
appending(mylist)
done = False
while(done == "False"):
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(mylist)))
done = True
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
appending(mylist)
done = False
elif(action == "Delete"):
removing(mylist)
done = False
def appending(mylist1 = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
mylist1.append(c)
print("You have inserted {} choices".format(len(mylist1)))
print("Please verify them below: ")
for x in range(0, len(mylist1)):
print(mylist1[x])
def removing(mylist2 = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
mylist2.remove(r)
print("{} successfully removed!".format(r))
Now problem is I can't just call choices() in append or remove function as choices() function will call append again and again infinitely.
So how do I get back in choices after appending or removing data in list?
As suggested by tobias_k, you should add the contents of choices() into a while loop.
I also found
some other problems:
False does not equal "False", so your while loop never runs.
You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and removing_list, so it's clearer.
You also shouldn't use False to define a while loop - instead, make a variable, then set it to True. When you have to stop, set it to False.
Here is the code with those problems fixed:
def appending(appending_list = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
appending_list.append(c)
print("You have inserted {} choices".format(len(appending_list)))
print("Please verify them below: ")
for x in range(0, len(appending_list)):
print(appending_list[x])
return appending_list
def removing(removing_list = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
removing_list.remove(r)
print("{} successfully removed!".format(r))
return removing_list
print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(choosing_list)))
list_incomplete = False
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
choosing_list = appending(choosing_list)
elif(action == "Delete"):
choosing_list = removing(choosing_list)
Let me know if there's any problems with this code.

Resources