Creating new lists from user inputs (Cicles) - Python - python

quarter1 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
quarter2 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
pick_q = int(raw_input("Pick a quarter: "))
if pick_q == 1:
assignment = 0
courses = int(raw_input("How many courses would you like to enroll? "))
print quarter1
while assignment < courses:
course = int(raw_input("Please select the course you'd like to enroll into(1-5): "))
newlist = []
chosen_assignment = quarter1[course]
newlist.append(chosen_assignment)
assignment += 1
print newlist
So I'm trying to make this program where a student can enroll to different courses within an specific quarter. I only put in 2 quarter as an example.
The problem I'm having is that I want to create a new list from the courses the student chooses, for example if he wishes Course1, 2 and 3 then a new list should be able to print "You have enrolled to [Course1,Course2, Course3]"
However when I run this and try to print the newlist it comes up when only the last pick the user entered in this case [Course3] and not with the other previous picks.
It doesn't necessarily have to print a list, but the user should be able to choose from the original list and gather this information to create new list. I put in a zero starting the list so that the user can pick a number from the list index 1-5. I'm new at python and trying to figure this thing out. Thank you in advance!!
Any other recommendations are really appreciated!!

Basically the newlist variable is being initialized again and again inside the loop. You simply need to declare it outside the loop.
quarter1 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-ourse5"]
quarter2 = [0, "1-Course1", "2-Course2", "3-Course3", "4-Course4", "5-Course5"]
newlist = [] # Declare it outside
pick_q = int(raw_input("Pick a quarter: "))
if pick_q == 1:
assignment = 0
courses = int(raw_input("How many courses would you like to enroll? "))
print quarter1
while assignment < courses:
course = int(raw_input("Please select the course you'd like to enroll into(1-5): "))
chosen_assignment = quarter1[course]
newlist.append(chosen_assignment)
assignment += 1
print newlist

Related

Can't figure out how to assign a number to a element in a list in python

I am a relatively new programmer and I can not figure out how to make variables for certain elements in a list. I am trying to do this so I can ask for a certain number and then the console will print a certain element of the list. This is a something I have to do for practice before I can move on to the next level of python. This programming is done through a site called codesters.
Here are the directions I was given to make this program:
There is a list of 5 foods (use any name).
Print to the console each food by using an index variable to
access each element in the list. (HINT: For loop)
Ask the user for a food number (location in the list), then print out that
food. (E.g. The list are A, B, C, D, E and food number 1 is A)
And this is the code I have so far:
mylist = ["cherry","cake", "rice", "bannana", "strawberry"]
for x in mylist:
print(x)
mylist.append(input("Please enter a food number:"))
Thanks for any help.
It looks like you're trying to iterate through the index of your list. Do so using range:
mylist = ["cherry","cake", "rice", "bannana", "strawberry"]
for i in range(len(mylist)):
print(mylist[i])
Similarly, you can ask a user for input and print a specific index:
while True:
# Ask for input
idx = input('Which food do you want to see?')
# only allow numbers
if not idx or not idx.isnumeric():
print('Please enter a valid number')
continue
# convert to int
idx = int(idx)
# more validation – only accept numbers in valid range
if idx<0 or idx>=len(mylist):
print(f'Please enter a number between 0 and {len(mylist)-1}')
continue
# otherwise
print(f'Your food is: {mylist[idx]}')
break
As noted by #ybressler-simon, the instructions refer to an index variable, because items in a list can be accessed by their position within the list, and a variable that picks out an item by position is often called an index.
>>> mylist = ['hotdish', 'lutefisk']
>>> mylist[0]
'hotdish'
>>> mylist[1]
'lutefisk'
>>> x = 0
>>> mylist[x]
'hotdish'
Use the len() function to get the number of items in a list, its length.
>>> len(mylist)
2
Use the range() function to produce a sequence of numbers counting up from 0.
>>> list(range(2))
[0, 1]
Then put the parts together and you're all set!
mylist = ["cherry","cake", "rice", "bannana", "strawberry"]
for count, value in enumerate(mylist, start=1):
print('{} - {}'.format(count, value))
choice = int(input("Please enter a food number: "))
print(mylist[choice-1])
Will result:
1 - cherry
2 - cake
3 - rice
4 - bannana
5 - strawberry
Please enter a food number: 5
strawberry

What is this "studentrecord"?

I based my code on Duncan Betts' codes for my assignment but I don't understand it and it seems like it has been 3 years since he last logged on so I can't ask him.
Can you please explain where did the "studentrecord" code come from? What is it?
num = int(input("How many students?: "))
physics_students = [[input("Input student name: "),float(input("Input grade: "))] for studentrecord in range(num)]
physics_students.sort(key=lambda studentrecord: float(studentrecord[1]))
lowest_grade = physics_students[0][1]
ind = 0
while physics_students[ind][1] == lowest_grade:
ind += 1
second_lowest_grade = physics_students[ind][1]
second_lowest_students = []
while physics_students[ind][1] == second_lowest_grade:
second_lowest_students.append(physics_students[ind][0])
ind += 1
if ind == num:
break
second_lowest_students.sort()
print(*second_lowest_students, sep="\n")
Thank you so much for your help!
The two occurrences of studentrecord refer to 2 different things
In the list comprehension, studentrecord is used to hold each element of the range range(num). It's basically an index, but it's never used anyways.
Edit: I don't think the list comprehension should call it studentrecord because the elements of that range are indices and not lists representing a student's name and grade. It's a little confusing, and the variable should probably be renamed to something like i or _.
That list comprehension is like doing this:
physics_students = []
for studentrecord in range(num):
physics_students.append([input("Input student name: "),float(input("Input grade: "))])
or this:
physics_students = []
for studentrecord in range(num):
physics_students[studentrecord] = [input("Input student name: "),float(input("Input grade: "))]
In the lambda expression, studentrecord is the name of the parameter to your anonymous function. It's like saying this:
def my_lambda(studentrecord):
return float(studentrecord[1]
physics_students.sort(key=my_lambda)

How to record inputs when using "For Loop"

I'm trying to ask the user to input how many classes they have (x), ask "What are your grades in those classes?" x amount of times, and record all of the inputted grades to use later.
I tried to assign the question to a variable and ask to print the variable, but I get only the last inputted number. I don't want to print the numbers, I want to store them for later so I can add them together. I was just using the print function to see how my numbers would be stored if assigning the variable actually worked. How would I record all the inputted numbers to later add and calculate GPA?
numofclasses = int(input("How many honors classes do you have?: "))
for i in range(numofclasses):
grades = str(input("Enter the unweighted grade from one class "))
print(grades)
I want to get all the inputted numbers recorded, but by using the print option I only get the last inputted number recorded.
The thing you want to use is a list, which is used to container which holds a sequence of datatypes, like integer, characters, etc,
Think of it this way, if you want to use 3 variables in python what would you generally do
a = 1
b = 2
c = 3
This works fine, but what if the number of variables is 50, or 100, how many variables will you keep defining, hence you would need a container to store these, which is where a list comes in. So we would just do
li = [1,2,3]
And access these variables via indexes, which start from 0
a[0] #1
a[1] #2
a[2] #3
Keeping this in mind, we would do!
numofclasses = int(input("How many honors classes do you have?: "))
#List to save all grades, defined by assigning variable to []
all_grades = []
for i in range(numofclasses):
#Take grades from the user
grades = input("Enter the unweighted grade from one class ")
#Append the grades to the list, using list.append function
all_grades.append(grades)
#Loop through the list to print it
for item in all_grades:
print(item)
#Print all grades in a single line by joining all items of list in a string
s = " ".join(all_grades)
print(s)
And the output will look like
How many honors classes do you have?: 3
Enter the unweighted grade from one class A
Enter the unweighted grade from one class B
Enter the unweighted grade from one class C
#All grades in different lines
A
B
C
#All grades in single line
A B C
It seems to me there are a couple options that may be suitable.
Printing the input each iteration:
numofclasses = int(input("How many honors classes do you have?: "))
for i in range(numofclasses):
grades = str(input("Enter the unweighted grade from one class "))
print(grades) # move print to inside of loop
Storing the values in a list for printing later:
numofclasses = int(input("How many honors classes do you have?: "))
grades = []
for i in range(numofclasses):
grades.append(str(input("Enter the unweighted grade from one class ")))
print(grades) # will look like ["A", "B", "C", "B"]
Here is how yo do it:
class_dict = {}
numOfClasses = input("How many classes do you take? Enter here : ")
for i in range(int(numOfClasses)):
class_dict["class" + str(i +1)] = input("Enter your grade for class " + str(i +1) + ": ")
print(class_dict)
The above should do it.

How to have a sequence variable within a for loop

def main():
for row in range (7):
assignment = int(1)
if row == 1:
for assignment_number in range(0,8):
assignment_number+1
for i in range(0,7):
assignment_mark = float(input(("Please enter your mark for assginment" assignment_number,": "))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
main()
So this is my code above,
I'm basically trying to work out how I could say for each input variable "Please enter your mark for assignment x (from 1 up to 7).
Which will loop, so once they enter it for assignment 1, it then asks the same question for assignment 2.
I hope this makes some sense. I'm new to programming in general and this just happens to also be my first post on stack! Be gentle (:
Thanks!
There are a few problems with your code:
assignment_number+1 without assigning it to a variable does nothing, and even if you did, that value would be lost after the loop. If you want to offset the numbers by one, you can just use range(1, 8) or do +1 when you actually need that value of that variable
in your second loop, your loop variable is i, but you are using assignment_number from the previous loop, which still has the value from the last execution, 7
you have to store the values for assignments_mark and assignment_weight somewhere, e.g. in two lists, a list of tuples, or a dict of tuples; since assignment numbers start with 1 and not 0, I'd recommend a dict
You can try something like this, storing the marks and weights for the assignments in a dictionary:
assignments = {}
for i in range(7):
assignment_mark = float(input("Please enter your mark for assginment %d: " % (i+1)))
assignment_weight = float(input("Please enter the total weight percentage for the assignment: "))
assignments[i+1] = (assignment_mark, assignment_weight)
print(assignments)
Let the loop do the counting, then use string formatting.
And you only need a single loop to collect each pair of events
from collections import namedtuple
Assignment = namedtuple("Assignment", "mark weight")
assignments = []
for idx in range(7):
print("Please enter data for assignment {}".format(idx+1))
mark = float(input("mark: "))
weight = float(input("weight:"))
assignments.append(Assignment(mark, weight))
print(assignments)

Gradebook: Python

I'm stuck on writing this program. These are the instructions that were given to us.
As per the guidelines at the top of the assignment you may NOT import any modules. This
includes the statistics module.
The user should be displayed with a list of options from 1 to 5
If the user chooses 1 they should be prompted to enter a student's name and grade
If the student does not appear in the grade book, the student and the grade should be
added to the grade book
If the student is already in the grade book their grade should be changed to the value
given
If the user chooses 2 they should be prompted to enter a student's name.
That student should be removed from the grade book
If the student is not in the grade book then the grade book should not be modified
but also no error should be displayed.
If the user chooses 3 the names and grades of all students should be displayed in
alphabetical order
If the user chooses 4 the following statistics for the course should be displayed: Mean,
Median, and Mode
The median is the middle number in a list of sorted numbers
The mode is the value that appears most often
If more there are 2 or more more numbers that appear most often then you may display any of them.
If the user chooses 5 the program should terminate
If any other option is chosen the program should tell the user that it does not recognize
the option and ask the user for another choice.
All inputs besides the command choice will be valid.
You do not have to match the exact number of spaces I have in my output when
displaying grades and course statistics but there needs to be at least 1 space.
Hint: Break the problem down into small functions that each tackle one part of the
problem. For example have one function for inserting a student into the grade book, another for calculating the mean, etc.
This is what I have so far and there are a few errors:
def menuprint():
print('1. Add/modify student grade.\n')
print('2. Delete student grade\n')
print('3. Print student grades\n')
print('4. Display the course statistics\n')
print('5. Quit\n')
menuprint()
choice = 0
students = []
grades = []
def addmodify():
name_points = input('Enter name and points: ')
nameGrade_list = name_points.split()
name = nameGrade_list[0]
points = nameGrade_list[1]
students.append(name)
grades.append([points])
def stat():
for i in range(0,len(students)):
print("NAME:", students[i])
print ("GRADES:", grades [i])
def mean(list):
sum = 0
floatNums = [float(x) for x in list]
return sum(floatNums) / len(list)
while choice !=5:
choice = int(input('Your choice: '))
if choice == 1:
addmodify()
print('Enter name and points:')
elif choice == 2:
name = input('Enter name to delete:')
students.remove(name)
elif choice == 3:
gradelist()
print ('SS')
elif choice == 4:
print('Mean', mean(grades))
def mean(num_list):
sum = 0
floatNums = [float(x) for x in num_list]
return sum(floatNums) / len(num_list)
should fix it. list is a keyword and cannot be used anywhere in your code as a variable.

Categories