This program is written with the intent of collecting Name,Age and Score using commas as delimiters. After values have been keyed in, the program will rearrange the list giving priority to Name, Age and Score respectively. However, the result has not been as expected.
from operator import itemgetter, attrgetter
store=[]
store1=[]
while True:
block = input("Enter Name, Age, Score: ")
if block:
store.append(block)
else:
break
store1=tuple(store)
print(sorted(store1, key=itemgetter(0,1,2)))
Result:
Enter Name, Age, Score: John,50,100
Enter Name, Age, Score: Jan,40,50
Enter Name, Age, Score: John,38,10
Enter Name, Age, Score:
['Jan,40,50', 'John,50,100', 'John,38,10']
As shown above, there is no problem in rearranging the name. In fact, the problem lies in the 2nd and 3rd variables when being sorted. The function itemgetter does not seem to work.
You take the input name, age, score as variable block:
block = input("Enter Name, Age, Score: ")
and you append the block as a whole to the list.
store.append(block)
This way, the entire string containing the name, age and score is considered to be one entry. Since the name appears first in the string, it only appears as if the sorting is done for the name only.
store1=tuple(store) looks unnecessary as well. Here is my how you can achieve what you want using list of tuples instead of tuple of strings :
from operator import itemgetter, attrgetter
store=[]
while True:
block = input("Enter Name, Age, Score: ")
if block:
entry = tuple(block.split(',')[:3])
store.append(entry)
else:
break
print(sorted(store, key=itemgetter(0,1,2)))
Related
Objective A mini bank simulation using only python basics list,while loop,if else.
Issues 2. Search account.
Notes I want my program to return the respective age and balance of the matching name.Thanks in advance.
print("""1. Add Account
2. Search Account"
3. Exit \n\n""")
name = []
age = []
balance = []
while True:
choice = input("What is your choice ? : ")
if choice == "1":
name.append(input("Name : "))
age.append(input("Age : "))
balance.append(input("Balance : "))
print("Account Registration Done\n\n")
if choice == "2":
y = input("What is your Account Name ? > : ")
if y in name: # i want my program to return the respective age and balance of the matching name.
print(name[0]) # Here is the issue and i don't know how to fix.Please Kindly enlighten me
print(age[0])
print(balance[0])
else:
print(
f"Your name[{y}] have't registered yet.Please register first")
if choice == "3":
break
The most recently added bank account in your code will be the bank account at the end of the lists. You can access it by name[-1], age[-1], and balance[-1]. Negative indices in Python mean searching backwards so -1 gives you the last element of a list.
To search for an account you can do:
if y in name:
found = name.index(y)
Then you can do age[found] and balance[found] to get the respective age and balance.
If you're adding new elements to the end of the list (ie .appending() them), you can list[-1] to get the last (therefore newest) element in the list.
I have just started learning python and i have been given an assignment to create a list of players and stats using different loops.
I cant work out how to create a function that searches the player list and gives an output of the players name and the players stat.
Here is the assignment:
Create an empty list called players
Use two input() statements inside a for loop to collect the name
and performance of each player (the name will be in the form of a
string and the performance as an integer from 0 – 100.) Add both
pieces of information to the list (so in the first iteration of the
loop players[0] will contain the name of the first player and
players[1] will contain their performance.) You are not required to
validate this data.
Use a while loop to display all the player information in the
following form:
Player : Performance
Use a loop type of your choice to copy the performance values from
the players list and store these items in a new list called results
Write a function that accepts the values “max” or “min” and
returns the maximum or minimum values from the results list
Write a function called find_player() that accepts a player name
and displays their name and performance from the players list, or an
error message if the player is not found.
Here is what I have so far:
print ("Enter 11 Player names and stats")
# Create player list
playerlist = []
# Create results list
results = []
# for loop setting amount of players and collecting input/appending list
for i in range(11):
player = (input("Player name: "))
playerlist.append(player)
stats = int(input("Player stats: "))
playerlist.append(stats)
# While loop printing player list
whileLoop = True
while whileLoop == True:
print (playerlist)
break
# for loop append results list, [start:stop:step]
for i in range(11):
results.append(playerlist[1::2])
break
# max in a custom function
def getMax(results):
results = (playerlist[1::2])
return max(results)
print ("Max Stat",getMax(results))
# custom function to find player
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
return (name)
for s in list:
if name in str(s):
return (s)
print (find_player(playerlist))
I have tried many different ways to create the find player function without success.
I think I am having problems because my list consists of strings and integers eg. ['john', 6, 'bill', 8]
I would like it to display the player that was searched for and the stats ['John', 6]
Any help would be greatly appreciated.
PS:
I know there is no need for all these loops but that is what the assignment seems to be asking for.
Thank you
I cut down on the fat and made a "dummy list", but your find_player function seems to work well, once you remove the first return statement! Once you return something, the function just ends.
All it needs is to also display the performance like so:
# Create player list
playerlist = ["a", 1, "b", 2, "c", 3]
# custom function to find player
def find_player(playerlist):
name = str(input("Search keyword: "))
searchIndex = 0
for s in playerlist:
try:
if name == str(s):
return ("Player: '%s' with performance %d" % (name, playerlist[searchIndex+1]))
except Exception as e:
print(e)
searchIndex += 1
print (find_player(playerlist))
>>Search keyword: a
>>Player: 'a' with performance 1
I also added a try/except in case something goes wrong.
Also: NEVER USE "LIST" AS A VARIABLE NAME!
Besides, you already have an internal name for it, so why assign it another name. You can just use playerlist inside the function.
Your code didn't work because you typed a key and immediately returned it. In order for the code to work, you must use the key to find the value. In this task, it is in the format of '' key1 ', value1,' key2 ', value2, ...]. In the function, index is a variable that stores the position of the key. And it finds the position of key through loop. It then returns list [index + 1] to return the value corresponding to the key.
playerlist = []
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
index = 0
for s in list:
if name == str(s):
return ("This keyword's value: %d" % (list[index+1]))
index+=1
print (find_player(playerlist))
I am trying to set up code to create a program that reminds me what days i have off, what days i work, and at what times i work. it will also remind me to input schedule for next work week. for now though i will be doing some code to show what i will need to do until i have some more skill.
I have tried appending the list for sch_days_off and it returns an output of 1 when i try to print how many days i have off. i believe the strings i am using the wrong type of method to add to my list to try and count how many days i have off. I have also tried the count function, but it does not seem to be what i need, and if it it maybe i am not utilizing it correctly
days_of_week = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday')
sch_days_off = []
def schedule_off():
days_off = input("Please enter your days off:").split(' ')
print(days_off)
sch_days_off.append(days_off)
print("This is how many days you have off: ")
def number_of_days_off():
print("This is how many days you have off: %d" % len(sch_days_off))
schedule_off()
What i expected to print out would be the numbers of days i was off. i usually get two-three days off so i expect it to have an output of 2-3 not just one. Regardless it still gives me '1' as an output.
Here, you append a list days_off to another list sch_days_off so sch_days_off becomes a two-dimenssional list. You print the number of list that contains sch_days_off (1).
Try this :
def schedule_off():
days_off = input("Please enter your days off:").split(' ')
print(days_off)
for day in days_off:
sch_days_off.append(day)
print("This is how many days you have off: ")
Now you are appending the list days_off as an element to the list sch_days_off, that's why the len() always return 1. If you want to add all elements of days_off to sch_days_off you need to use extend instead of append.
def schedule_off():
days_off = input("Please enter your days off:").split(' ')
print(days_off)
sch_days_off.extend(days_off)
print("This is how many days you have off: ")
I am having trouble with making a simple calculator work. There are some requirements I need to meet with it:
Need to be able to calculate the average of however many grades the user wants
Be able to calculate within the same program separate grade averages
for multiple 'users'
Give the option to exclude the lowest value entered for each person
from their individual average calculation.
I have some code, it is pretty much a mess:
def main():
Numberofstudents=eval(input("How many students will enter grades today? "))
Name=input("What is your frist and last name? ")
numberofgrades=eval(input("How many grades do you want to enter? "))
gradecount=0
studentcount=1
lowestgradelisty=[]
while studentcount<=Numberofstudents:
gradetotal=0
while gradecount<numberofgrades:
gradeforlisty=eval(input("Enter grade please: "))
gradetotal=gradetotal+gradeforlisty
gradecount=gradecount+1
Numberofstudents=Numberofstudents-1
studentcount=studentcount+1
lowestgradelisty.extend(gradeforlisty)
min(lowestgradelisty.extend(gradeforlisty))
Drop=(min(lowestgradelisty.extend(gradeforlisty))), "is your lowest grade. do you want to drop it? Enter as yes or no: "
if (Drop=="yes"):
print(Name, "The new total of your grades is", gradetotal-min(lowestgradelisty.append(gradeforlisty)/gradecount))
elif (Drop=="no"):
print("the averages of the grades enetered is", gradetotal/gradecount)
gradecount=0
studentcount=1
main()
Here's a function that does what it sounds like you wanted to ask about. It removes the smallest grade and returns the new average.
def avgExceptLowest(listofgrades):
# find minimum value
mingrade = min(listofgrades)
# remove first value matching the minimum
newgradelist = listofgrades.remove(mingrade)
# return the average of of the new list
return sum(newgradelist) / len(newgradelist)
A number of notes on your code:
The indentation of the code in your question is wrong. Fixing it may solve some of your problems if that's how it appears in your python file.
In Python the convention is to never capitalize a variable, and that's making your highlighting come out wrong.
If you code this correctly, you won't need any tracking variables like studentcount or gradecount. Check out Python's list of built-in functions and use things like len(lowestgradelisty) and loops like for i in range(0, numberofstudents): instead to keep your place as you execute.
I am working on a project where I need to implement code that will ask the user for multiple data inputs for the following fields for an employee directory: Last name, first name, employee number, and pay rate.
That's example code which presents acquiring data from user input and splitting it (by space):
user_input = input("enter last name, first name, employee number, and pay rate: ")
a = user_input.split()
print (a[0]) # last name
print (a[1]) # first name
print (a[2]) # employee number
print (a[3]) # pay rate
You can obviously use other delimiter, passing it as a first argument to a split method.