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)
Related
I am trying to pass 10 inputs(names) into a list in python but I am getting one list element only take a look!
I tried to do this, but didn't work!
my problem is just at passing the inputs into a list i tried a lot but cant seem to find a solution, please help me with this
for inputs in range(0, 10):
names=input("enter names: ")
students= []
students.append(names)
print(students)
but the output I am getting is:
['example name']
What should I do?
First you should make a list. Then get inputs 10 times and append them into the list ten times. (One name each time)
students = []
for i in range(10):
name = input("enter one name: ")
students.append(name)
print(students)
Or you can have this inline version:
students = [input("enter one name: ") for i in range(10)]
print(students)
If you want to input all the names in one input, suppose that you seperate the names with , character, as much as you want:
students = input("enter names: ").split(',')
This should help you:
students= []
for inputs in range(0, 10):
name=input("enter name: ")
students.append(name)
print(students)
you are overriding you own value of names in the for loop, and then insert it only once, after the loop, to the list. append should be in the loop
students= []
for inputs in range(0, 10):
names=input("enter names: ")
students.append(names)
print(students)
The names variable is a variable, not a list... So with every input, it replaces the text that u entered before. To fix this just instantly append them;
students= []
for inputs in range(0, 10):
students.append(input("enter name: "))
print(students)
In this code, I have a user-generated list of numbers and have to find the amount of duplicates a specific element has within that list. I am getting an error in the function. How do I fix this?
def count(list,y):
new_list = []
for j in range(0,x):
if(list[j]==y):
new_list.append(list[j])
else:
pass
print(new_list)
length = len(new_list)
print("The number {} appears {} times in the list".format(y,length))
list = []
x = int(input("Please enter the size of the list you want to create: "))
for i in range(0,x):
value = input("Please enter value of list : ")
list.append(value)
print("The list of the values you entered : {}".format(list))
y = int(input("Which element do you want to find the number? : "))
count(list,y)
There were multiple issues in your code.
In the loop in function count instead j you are using i as index.
initiation of loop index till range(0,x) => x is not defined as the variable is not assigned in this scope, instead use len of the list.
All the inputs added to the list were strings and the one that was searched was an integer.
Other suggestions:
do not use list as a variable name as it is a keyword.
Below this code I am also providing a shorter version of the function count.
def count(mylist,y):
new_mylist = []
for j in range(0,len(mylist)):
print(mylist[j])
if(mylist[j]==y):
new_mylist.append(mylist[i])
else:
pass
length = len(new_mylist)
print("The number {} appears {} times in the mylist".format(y,length))
mylist = []
x = int(input("Please enter the size of the mylist you want to create: "))
for i in range(0,x):
value = int(input("Please enter value of mylist : "))
mylist.append(value)
print("The mylist of the values you entered : {}".format(mylist))
y = int(input("Which element do you want to find the number? : "))
count(mylist,y)
Shorter version
def count(mylist,y):
length = mylist.count(y)
print("The number {} appears {} times in the mylist".format(y,length))
one issue, you're trying to acces the i'th element in list, but i is not initialized. Try replacing i with j
for j in range(0,x):
if(list[i]==y):
new_list.append(list[i])
If you don't mind me taking liberties with your code, here's an example using the Counter from collections. Note that it doesn't do exactly the same thing as your code, as Counter doesn't use indexes as you were using before.
from collections import Counter
input_counter = Counter()
while True:
value = input("Please enter a value (or nothing to finish): ")
if value == '':
break
input_counter[value] += 1
print(input_counter)
y = input("Which number do you want to count the instances of? ")
print(input_counter[y])
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)
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
This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 5 years ago.
I built a calculation and it works:
num = input("How many numbers would you like to add? ")
list = []
for x in range(num):
list.append(input('Number: '))
a = 0
for x in list:
a=a+x
print a
But when I try to make a function on of this, simply doesn't work. Can you please direct me?
list = []
def adding():
num = input("How many numbers would you like to add? ")
for x in range(num):
list.append(input('Number: '))
a = 0
for x in list:
a=a+x
print adding()
Functions without explicit returns or empty returns will return None.
>>> def foo():
... print("Hello")
...
>>> f = foo()
Hello
>>> f is None
True
If you don't want this, use a return at the end of your function to return some value.
Some other tips.
Make your function only do one thing:
Currently your function is getting input, creating a list, and summing everything. This is a lot. You'll find that if you make your functions smaller, you'll get some nice benefits. You might consider something like this:
def prompt_for_number_of_inputs():
return int(input("How many elements are there in the list? ")
def prompt_for_elements(num_elements):
return [int(input("Enter a number: ")) for _ in range(num_elements)]
def sum_elements_in_list(li):
return sum(li)
so you might use it like this:
num_elements = prompt_for_number_of_inputs()
my_list = prompt_for_elements(num_elements)
print("The sum of all the elements is {0}".format(sum_elements_in_list(my_list))
Don't shadow Python built-ins:
If you call your variables the same thing as Python builtins, you'll find yourself in trouble. See here:
>>> a = list()
>>> a
[]
>>> list = [1,2,3]
>>> a = list()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Normally list() would create an empty list (as seen above), but this is impossible because you've bound an object to the name list. Look at other builtins which could be shadowed here.
You are not returning anything.
Your indentation is incorrect.
You shouldn't use python builtins as variable names (list).
(Note: _ is often used as a disposable variable)
def adding():
num = int(raw_input("How many numbers would you like to add? "))
lst = []
for _ in range(num):
lst.append(int(raw_input('Number: ')))
a = 0
for x in lst:
a += x
return a
You don't really need the second loop as return sum(lst) would do the same thing.
Alternatively, you don't need lst at all:
def adding():
num = int(raw_input("How many numbers would you like to add? "))
a = 0
for _ in range(num):
x = int(raw_input('Number: '))
a += x
return a
I changed your variable name for the list as it shadows the built-in name and added the return statement. Works as you intended it to.
sumlist = []
def adding():
num = input("How many numbers would you like to add? ")
for x in range(int(num)):
sumlist.append(int(input('Number: ')))
a = 0
for x in sumlist:
a=a+x
return a
print(adding())