Beginner Python list, defining variable - python-3.x

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

Related

How do i get out of this nested loop

I have been trying to get out of this nested loop I coded....please forgive me if the code is a bit too long but the actual important part has been commented at the last but one area of the code please help.
import random
import time
import math
# main
while True:
print('Only a maximum of three players are allowed in this game. A single player plays
with cpu')
print('1. Single Player\n2. Double Players\n3. Triple players')
print("Let's Start")
player_select = input('How many players will be playing ths game?: ')
single_score = [] # keep scores of player
cpu_score = [] # keep scores of CPU
while True:
lst = ['Rock', 'Paper', 'Scissors'] # holding the random three words
if player_select == '1' or player_select.lower() == 'single player':
randomize = random.choice(lst) # create a random choice out of the list
for i in last:
print(i) # display rock paper scissors
time.sleep(1)
print(randomize)
guess = input('guess rock, paper or scissors: ') # demanding for a guess
if guess.lower() == randomize.lower(): # what should happen if guess is right
single_score.append(1) # add 1 to the single_score list
print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")
elif guess.lower() != randomize.lower():
cpu_score.append(1)
print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")
print("Press 'Enter to continue'\n1. Change number of players(p)\n2. Exit(e) ")
question = input('Enter your choice: ')
if question == '':
continue
elif question.lower() in ['change number of players', 'p'] or question == '2':
print('Lets start all over')
#how do i get out of this to the intitial while loop?
elif question.lower() in ['exit', 'e'] or question == '3':
print('Total score of Player1', sum(single_score), '\n Total score of Player CPU',
sum(cpu_score))
The best way to do this is to use boolean check in your while loop :
check1 = True
check2 = True
while check1:
...
while check2:
if some_stop_condition_for_the_iner_loop:
check2 = False
if some_stop_condition_for_the_outer_loop:
check1 = False
check2 = False
In this way you can easily control your execution flow.
You can also use the keyword break that will allow you to stop the current loop you're in, but if there is neested loop, it will only break the deeper one, so boolean check are often the best solution.

How to write a python code to append data to json list

I want to create a python script which will have user input to enter a word and its definitions (multiple definitions) and append them to a JSON file
For some word there will be only one definition but others might have multiple ones.
JSON Example:
{'acid': ['A compound capable of transferring a hydrogen ion in solution.',
'Being harsh or corrosive in tone.',
'Having an acid, sharp or tangy taste.',
'A powerful hallucinogenic drug manufactured from lysergic acid.',
'Having a pH less than 7, or being sour, or having the strength to '
'neutralize alkalis, or turning a litmus paper red.'],
'acoustic filter': ['A device employed to reject sound in a particular range '
'of frequencies while passing sound in another range of '
'frequencies.'],
'acoustic insulation': ['The process of preventing the transmission of sound '
'by surrounding with a nonconducting material.']}
Code:
import json
while True:
Word = input('Enter Word:')
Definition1 = input('Definition 1: ')
Definition2 = input('Definition 2: ')
Definition3 = input('Definition 3: ')
Definition4 = input('Definition 4: ')
Definition5 = input('Definition 5: ')
Definition6 = input('Definition 6: ')
with open("files/data.json", "r+") as data:
information = {Word, Definition1, Definition2, Definition3, Definition4, Definition5}
data.write(json.dumps(information))
data.close()
I would advice the structure like this:
import json
words_dict = {}
while True:
tmp_list_of_definitions = []
word = input('Enter Word:')
if word in words_dict:
print('You already entered definitions for such word!')
answer = input('Is the procedure over? [y/n]')
if answer == 'y':
break
continue
def_counter = 0
print('In case you want to stop entering the definitions print "stop"')
while True:
definition = input('Definition {}: '.format(def_counter))
def_counter += 1
if definition == 'stop':
break
tmp_list_of_definitions.append(definition)
words_dict[word] = tmp_list_of_definitions
answer = input('Is the procedure over? [y/n]')
if answer == 'y':
break
And you don't have to use close when using with open().
Hope this helps,
import json
if __name__ == '__main__':
information = dict()
while True:
key = input("Enter word or 'q' to quit:")
if key is 'q':
break
definition_list = list()
while True:
definition = input("Enter definition or 'n' to next word:")
if definition is 'n':
break
definition_list.append(definition)
information[key] = definition_list
with open("data.json", "r+") as data:
data.write(json.dumps(information))
exit(0)

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)

Cant get my elif functions right

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.

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