Stuck on a Python Zybook Challenge Problem - python

Prompt: Complete Creation (3.20)
Copy your solution from Creation (3.20) to here but delete the print statements (I PASTED THIS BELOW)
Make an empty list. The list will be used to store Student namedtuples
Add Kenneth and Maegan to the list
Create a funtion makeStudent(studentlist) where studentlist is your list of Student namedtuples
The function should do the following:
Take user input for each of the fields of the namedtuple
Create a Student namedtuple using the input
Add the Student to studentlist
Call makeStudent 3 times
Print student_list
Print Students whose list positions are odd in student_list
Hello! Can anyone help clarify what to do for step 5(Lab 3.2.1). The instructions are very ambiguous and unclear
Copy posted my code from 3.2.0
2.Deleted my print statements
3/4: #made an empty list and added "Kenneth" and "Maegan" to the list. Let me know if this is wrong and if the prompt is actually telling me to directly insert the names into the list.
student_list = list()
student_list.append('Kenneth')
student_list.append('Maegan')
Really confused about what to do. No hints were given either. I tried to do a def makeStudent(studentlist):
but was really confused about how I should write out the rest of the function. I experimented with doing a single line as well to gain all the inputs.
The function should do the following:
Take user input for each of the fields of the namedtuple (I tried doing it line by line input, and even one line)
Create a Student namedtuple using the input(How would I paste my input in the namedtuple? Same one as the one in code 3.20?)
Add the Student to studentlist(student_list.append(Student or 'Student'))
then I guess do that 3x. Use of return function.
print student_list
Then do List Sequence Slicing, I assume: lst[:] for example
My code is below
from collections import namedtuple
Student = namedtuple("Student", ["name","major","year","id","gpa"])
Student1 = Student("Kenneth", major="Computer Science", year=6, id=987654321, gpa=3.8)
Student2 = Student("Maegan", major="Neuroscience", year=4, id=123456789, gpa=3.4)
# make list
student_list = list()
student_list.append('Kenneth')
student_list.append('Maegan')
# add Kenneth and Maegan to the list
# make function
# print list / list with odd names

From what I understood, it's asking you to do the following. However, in the final part, I didn't see where it was asking for odd numbered names, so I just printed out the whole list.
from collections import namedtuple
Student = namedtuple("Student", ["name","major","year","id","gpa"])
Student1 = Student("Kenneth", major="Computer Science", year=6, id=987654321, gpa=3.8)
Student2 = Student("Maegan", major="Neuroscience", year=4, id=123456789, gpa=3.4)
# make list
student_list = list()
# add Kenneth and Maegan to the list
student_list.append(Student1)
student_list.append(Student2)
# make function
def makeStudent(studentlist):
name = input("Enter name: ")
major = input("Enter major: ")
year = input("Enter year: ")
id_ = input("Enter id: ")
gpa = input("Enter gpa: ")
new_student = Student(name, major=major, year=year, id=id_, gpa=gpa)
studentlist.append(new_student)
# call makeStudent 3 times
for _ in range(3):
makeStudent(student_list)
# print list
print(student_list)
When you run the script, if you enter the following values:
Enter name: John
Enter major: EE
Enter year: 1999
Enter id: 123
Enter gpa: 4
Enter name: Pete
Enter major: CS
Enter year: 2000
Enter id: 234
Enter gpa: 3
Enter name: Sam
Enter major: IE
Enter year: 2001
Enter id: 345
Enter gpa: 2
the final list would be printed out like so:
[Student(name='Kenneth', major='Computer Science', year=6, id=987654321, gpa=3.8),
Student(name='Maegan', major='Neuroscience', year=4, id=123456789, gpa=3.4),
Student(name='John', major='EE', year='1999', id='123', gpa='4'),
Student(name='Pete', major='CS', year='2000', id='234', gpa='3'),
Student(name='Sam', major='IE', year='2001', id='345', gpa='2')]

Related

how to bubble-sort or build multi-dimensional arrays in python?

I'm not sure how to phrase the question so instead I will copy/paste the prompt from my homework and hopefully that will make my question clear. I am very new to python and am almost totally lost in how to complete this task. The task is as follows:
I am stuck on part B.
a. Three Strikes Bowling Lanes hosts an annual tournament for 12 teams Design a program that accepts each team's name and total score for the tournament and stores them in parallel arrays. Display the names of top three teams.
b. Modify the bowling tournament program so that, instead of the team's total score, the program accepts the score of each of the four team members. Display the names of the five top scorers in the tournament as well as their team names
Here is what I have so far for part A, though I still cant get it to sort by the highest score while displaying the correct team name.
scores = range(0,12)
names = range(0,12)
teamScore = []
teamName = []
for names in names:
name = input("Please enter the team name: ")
teamName.append(name)
print("\n" + "Please enter the team scores here: ")
for scores in scores:
score = input("Please enter the team score: ")
teamScore.append(score)
result = sorted(zip((teamName, teamScore)))
print(result)
Welcome to the SO community!
This is obviously not a complete answer bit should help you make some progress.
count = 3 # Pretend there are only 3 teams for ease in debugging
names = [] # The team names (we don't need long names in a simple program)
for i in range(count): # Do this for each of "count" teams.
name = input("Please enter the team name: ") # Get the name
names.append(name) # Add it at the end of the names list.
print(names)
Session output:
Please enter the team name: The Bulldogs
Please enter the team name: Strikers
Please enter the team name: Out of this world
['The Bulldogs', 'Strikers', 'Out of this world']
Try improving this as much as you can and come back with any questions.

How do you let user pick the range for for loop?

I have to make this program:
Write a program that allows a teacher to input how many students are in his/ her class, then allow them to enter in a name and mark for each student in the class using a for loop. Please note you do not need to record all of the names for later use, this is beyond the scope of the course * so just ask them each name, have it save the names over top of each other in ONE name variable.
i.e.)
INSIDE OF A LOOP
name = input (“Please enter student name: “)
Calculate the average mark for the entire class – this will require you to use totaling.
Output the class average at the end of the program, and ask if they would like to enter marks for another class. If they say yes, re-loop the program, if no, stop the program there.
So I started writing the program and it looks like this
studentamount = int(input("Please enter how many students are in your class: "))
for count in range():
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark"))
I ran into the following problem: how would I allow the set of code under the for loop to loop for each student? I was thinking I could just enter in the studentamount variable as the range but I can't since python does not allow you to enter in a variable as a range.
How would I get the for loop to loop for the amount of students typed in? e.g. if 20 students for student amount was typed in, I would want the for loop to loop 20 times. Your help and knowledge is much appreciated.
Read the user input, convert it to int and pass it as a parameter to range:
studentamount = input("Please enter how many students ...: ") # this is a str
studentamount = int(studentamount) # cast to int ...
for count in range(studentamount): # ... because that's what range expects
# ...
Python does not allow you to enter in a variable as a range.
Python does allow you to enter variables as a range, but they must be numbers. Input () reads input in as string, so you need to cast it.
So, this is correct:
```Python
studentamount = int(input("Please enter how many students are in your class: "))
for count in range(studentamount):
name = input ("Please enter student name: ")
mark = int(input("Please enter the student's mark)
```
P.S a try - except clause would be useful here to catch people entering a non-integer data in [TypeError]
P.S.P.S #schwobaseggl 's example is good too, it is possibly more pythonistic to use the nested function studentamount = int(input("Text") than
studentamount = input("Text")
studentamount = int(studentamount)
You can store each student name and mark in a dictionary or tuple and store each dictionary (or tuple) into a list, see code sample (at the end enter "no" to exit or any other value to re-loop the program):
response = None
while response != 'no':
student_count = int(input('Please enter the number of students: '))
students = []
mark_sum = 0
print('There are {} student(s).'.format(student_count))
for student_index in range(student_count):
student_order = student_index + 1
student_name = input('Please enter the name of student number {}: '.format(student_order))
student_mark = float(input('Please enter the mark of student number {}: '.format(student_order)))
students.append({'name': student_name, 'mark': student_mark})
mark_sum += student_mark
print('The average mark for {} student(s) is: {}'.format(student_count, mark_sum / student_count))
response = input('Do you want to enter marks for another class [yes][no]: ')

Prompt to enter a name and then output the name that was entered along a score

I am writing a program for my intro CS class but I am a little stuck.
I have a designated list of names that correspond to a list of scores.
I am supposed to prompt the user to enter a name and then the program is supposed to output the name that was entered along with the corresponding score.
As I have it written now the program is printing the first name and score in the set regardless of the input. I have been stuck on this for a while, any help would be greatly appreciated!
Here is what I have right now:
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan'];
scores=['88','92','95','84','85','92','89'];
input("Please enter student's name:")
for i in range (0,7):
print (input(names[i] + scores[i]));
the program is supposed to output the name that was entered
That'll be hard considering you aren't capturing the input() return value.
Try this (as an example)
name = input("Please enter student's name:")
print(name)
Then, you next task is to check (in your loop) when name == <a name in the list>
Hint: You can use these for your loop rather than range(0,7)
for student in names:
or, even better, see zip lists in python
for (student, score) in zip(names, scores):
Using the zip function, you can combine the two lists together in an easy to use 1-to-1 group of tuples.
names=['Jim','Sarah','Jason','Lynne','Ginny','Joe','Susan']
scores=['88','92','95','84','85','92','89']
data = zip(names, scores) # <- ('Jim', '88'), ('Sarah', '92'), ...
stud = input('Enter the student's name: ')
for (student, score) in data:
if (stud == student):
print('{} -> {}'.format(student, score))
Better to use Python dictionaries for that:
student_scores = {'Jim': 88, 'Sarah': 92, 'Jason': 95}
and so on...
Then you can call for each of them like so;
name = input("Please enter student's name: ")
print(name + 'has a score of ' + student_scores[name])

(Python) How can I let a user open a text file and then change an integer / number

I've asked a similar question but to no avail.
I am a novice programming student and I've only been taught some basic techniques. Part of a task is to create a recipe program which I've mostly done, there is just one part preventing me from finishing.
I am supposed to allow a user to call a previously created text file (I've done this bit), then after this the contents of this file should be displayed for them to see (I've also done this bit), however the user should be able to recalculate the servings and therefore change the quantity of the ingredients. So if the user entered: "I want 2 servings" and the original quantity for 1 serving was 100g it should now output 200g.
It is really frustrating me and my teacher expects this work tomorrow. Below is what I am supposed to allow the user to do.
The user should be able to retrieve the recipe and have the ingredients recalculated for a different number of people.
• The program should ask the user to input the number of people.
• The program should output:
• the recipe name
• the new number of people
• the revised quantities with units for this number of people.
I will post my actual code below to show what I have done so far, which is to allow a user to view and make a new recipe. But the revised quantities bit is missing.
I apologise if the code is messy or unorganised, I am new to this.
Code so far:
#!/usr/bin/env python
import time
def start():
while True:
user_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")
if user_input == "N":
print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
time.sleep(1.5)
new_recipe()
elif user_input == "V":
print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
time.sleep(1.5)
exist_recipe()
elif user_input == "E":
print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
time.sleep(1.5)
modify_recipe()
elif user_input == "quit":
return
else:
print("\nThat is not a valid command, please try again with the commands allowed ")
def new_recipe():
new_recipe = input("Please enter the name of the new recipe you wish to add! ")
recipe_data = open(new_recipe, 'w')
ingredients = input("Enter the number of ingredients ")
servings = input("Enter the servings required for this recipe ")
for n in range (1,int(ingredients)+1):
ingredient = input("Enter the name of the ingredient ")
recipe_data.write("\nIngrendient # " +str(n)+": \n")
print("\n")
recipe_data.write(ingredient)
recipe_data.write("\n")
quantities = input("Enter the quantity needed for this ingredient ")
print("\n")
recipe_data.write(quantities)
recipe_data.write("\n")
unit = input("Please enter the unit for this quantity (i.e. g, kg) ")
recipe_data.write(unit)
print("\n")
for n in range (1,int(ingredients)+1):
steps = input("\nEnter step " + str(n)+ ": ")
print("\n")
recipe_data.write("\nStep " +str(n) + " is to: \n")
recipe_data.write("\n")
recipe_data.write(steps)
recipe_data.close()
def exist_recipe():
choice_exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
exist_recipe = open(choice_exist, "r+")
print("\nThis recipe makes " + choice_exist)
print(exist_recipe.read())
time.sleep(1)
def modify_recipe():
choice_exist = input("\nOkay, it looks like you want to modify a recipe. Please enter the name of this recipe ")
exist_recipe = open(choice_exist, "r+")
servrequire = int(input("Please enter how many servings you would like "))
start()
EDIT:
Below is an example creation of a text file (recipe) and it's output (the file is called bread.txt) Note the outputs are a bit messy, I will fix that once I can get the core of the program to work.
Creating a recipe
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
N
Okay, it looks like you want to create a new recipe. Give me a moment...
Please enter the name of the new recipe you wish to add! bread.txt
Enter the number of ingredients 3
Enter the servings required for this recipe 1
Enter the name of the ingredient flour
Enter the quantity needed for this ingredient 300
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient salt
Enter the quantity needed for this ingredient 50
Please enter the unit for this quantity (i.e. g, kg) g
Enter the name of the ingredient water
Enter the quantity needed for this ingredient 1
Please enter the unit for this quantity (i.e. g, kg) l
Enter step 1: pour all ingredients into a bowl
Enter step 2: mix together
Enter step 3: put in a bread tin and bake
Viewing a recipe
What would you like to do?
1) - Enter N to enter a new recipe.
2 - Enter V to view an exisiting recipe,
3 - Enter E - to edit a recipe to your liking.
4 - Or enter quit to halt the program
V
Okay, Let's proceed to let you view an existing recipe stored on the computer
Okay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. bread.txt
This recipe makes bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
And here is the output if you enter V:
This recipe makes bread.txt
Ingrendient # 1:
flour
300
g
Ingrendient # 2:
salt
50
g
Ingrendient # 3:
water
1
l
Step 1 is to:
pour all ingredients into a bowl
Step 2 is to:
mix together
Step 3 is to:
put in a bread tin and bake
I look forward to your replies.
It looks like your recipe files look like this:
Ingrendient # N:
{INGREDIENT}
{AMOUNT}
{METRIC}
...
(After N ingredients...)
Step N:
{INSTRUCTIONS}
So basically you want to read four lines at a time, discard the first, then assign the rest to something useful.
with open(path_to_recipe) as infile:
ingredients = []
while True:
try:
sentinel = next(infile) # skip a line
if sentinel.startswith("Step"):
# we're past the ingredients, so
break
name = next(infile)
amount = next(infile)
metric = next(infile)
except StopIteration:
# you've reached the end of the file
break
ingredients.append({'name':name, 'amount':float(amount), 'metric':metric})
# use a dictionary for easier access
When we exit the with block, ingredients will be a list of dictionaries that can be used as follows:
for ingredient in ingredients:
scaled_volume = ingredient['amount'] * scale # double portions? etc...
print(scaled_volume, ingredient['metric'], " ", ingredient['name'])
# # RESULT IS:
300g flour
50g salt
1l water
You should be able to leverage all that to finish your assignment!

Trying to calculate highest marks with name in python

grade=[]
names=[]
highest=0
cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
print('case',case)
number=int(input('Enter number of students: '))
for numbers in range (1,number+1):
name=str(input('Enter name of student: '))
names.append(name)
mark=float(input('Enter mark of student:'))
grade.append(mark)
print('Case',case,'result')
print('name',list[list.index(max(grade))])
average=(sum(grade)/number)
print('average',average)
print('highest',max(grade))
print('name',names[grade.index(max(grade))])
I want to print name of the student with the highest mark. I have not learned anything other than list, while and for. NO dictionary ..nothing. I was wondering how can i do this?
ALSO i am getting this error!!! builtins.AttributeError: 'str' object has no attribute 'append'. HELP. thank you! :D
for number in range (1,number+1):
Don't reuse variable names for different things, call one of them numbers and the other number:
numbers=int(input('Enter number of students: '))
for number in range (1,numbers+1):
You made name a list in the beginning:
name=[]
but here you assign a single input to it:
name=str(input('Enter name of student: '))
The you append the new name to itself:
name.append(name)
which is not possible, because name is after the input no longer a list but a string. Again using different variable names for different things would help. Call the array names and the single input name:
names = []
#...
name=str(input('Enter name of student: '))
names.append(name)
And here:
print('name',list[list.index(max(grade))])
list is a build-in type, not one of your variables, so what you are trying to do is index a type, not a specific list. If you want to call index on a specific list you do so by using the variable name of that list. grade.index(...) will find the specific position matching the passed grade in grade and then you can use this position to get the corresponding name, because you know, that the name is at the same position in names:
print('name',names[grade.index(max(grade))])
Here is a somewhat more elaborated version; working through it should give you a better feel for the language.
from collections import namedtuple
import sys
# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
inp, rng = raw_input, xrange # Python 2.x
else:
inp, rng = input, range # Python 3.x
def type_getter(type):
"""
Build a function to prompt for input of required type
"""
def fn(prompt):
while True:
try:
return type(inp(prompt))
except ValueError:
pass # couldn't parse as the desired type - try again
fn.__doc__ = "\n Prompt for input and return as {}.\n".format(type.__name__)
return fn
get_int = type_getter(int)
get_float = type_getter(float)
# Student record datatype
Student = namedtuple('Student', ['name', 'mark'])
def get_students():
"""
Prompt for student names and marks;
return as list of Student
"""
students = []
while True:
name = inp("Enter name (or nothing to quit): ").strip()
if name:
mark = get_float("Enter {}'s mark: ".format(name))
students.append(Student(name, mark))
else:
return students
def main():
cases = get_int("How many cases are there? ")
for case in rng(1, cases+1):
print("\nCase {}:".format(case))
# get student data
students = get_students()
# perform calculations
avg = sum((student.mark for student in students), 0.) / len(students)
best_student = max(students, key=lambda x: x.mark)
# report the results
print(
"\nCase {} average was {:0.1f}%"
"\nBest student was {} with {:0.1f}%"
.format(case, avg, best_student.name, best_student.mark)
)
if __name__=="__main__":
main()
which runs like:
How many cases are there? 1
Case 1:
Enter name (or nothing to quit): A
Enter A's mark: 10.
Enter name (or nothing to quit): B
Enter B's mark: 20.
Enter name (or nothing to quit):
Case 1 average was 15.0%
Best student was B with 20.0%

Categories

Resources