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.
Related
I have file with lines like:
1. 'abc0123,spja,40'
2. 'sed0898,spja,15'
3. 'sed0898,spja,10'
4. 'abc0123,udbs,10'
5. 'bem0334,dim,18'
6. 'bem0334,dim,0'
7. 'bem0334,spja,30'
etc. first word before comma means student login, second mean subject of exam and third means points for exam. One row represents one attempt on exam. I need return only students who passed on exams to which they tried. Doesn't matter on order by lines. In case above passed students bem0334 and sed0898. For passing student must have 15 and more points. So i started with saving lines into list of strings but i don't know how to test if students has passed on all his exams. `
def vrat_uspesne(soubor_vysledky):
f = open(soubor_vysledky, "r")
studens = []
exams = []
tmp = ""
for line in f:
spliter = line.split(',')
exams.append(line.rstrip('\n'))
student.append(spliter[0])
student = set(student)
student = list(student)
return student
You appear to have a typo in that code snippet (student vs students).
The general approach I would suggest is to map lines to data structs, then group the data by student login using a dictionary.
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)))
Just started programming in python 3 and I am trying to pull from an input() where I have placed the input() command in the first line and then further down use the output() to retrieve the input().
Here is an example:
rent = eval(input("How much does rent cost per year? $"))
Now I want to get the input I put in (10,000) and retrieve it from the input automatically using output() or another command.
print output("The family rent is", _______ , "per year."
What code would go in the ________ so I can retrieve what I put in for the input?
Thanks - newbie
the code as is :
# get user input
user_input = input("How much does rent cost per year? $")
# cast to int or whaterver you're expecting
try :
cost = int(user_input)
except :
print ("expecting a number")
# stop here maybe return
# print output
print ("The family rent is", cost , "per year.")
Use string formatting:
print('The family rent is {} per year'.format(rent))
See here for documentation of string formatting:
https://docs.python.org/3/library/string.html#format-string-syntax
First of all here is the code I have so far for my small project.
# Problem: working out a percentage of minutes
# Inputs: percentage constant, empty list [activities], total activity time
PERCENTAGE = 100
activities = []
total_minutes = int(input('What was the total mobile phone usage (minutes) '))
# Loop: take users activity inputs
while sum(activities) < total_minutes:
activity_name = input('What was the activity? ')
activity_time = int(input('How many minutes on this activity? '))
# Add the activity to the list
activities = activities + [activity_name, activity_time]
print(activities)
'''Now, what I am aiming to do is have the activity name with the time spent on the activity in the list [activities]. I want to be able to retrieve either the activity name or time individually and to also "activities.sort()" by the integer value while obviously coinciding with the correct activity name.
Please make your answer as simple as possible (for someone in his early stage of university, second module)
Thanks in advance :)'''
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.