TypeError without a clue - python

student_scores = input('Input a list of student scores: ')
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
highest = 0
for scores in student_scores:
if highest < scores:
highest = scores
print(f'The highest score is {highest}')
I'm learning the basic of Python and input the code accurately that the tutorial video says, but only mine gets TypeError: 'str' object does not support item assignment on the line 3.
I checked it several times, but still have no clue why.

The input() function will invariably return a string. What you want to do is have the user input several numbers (presumably separated by a space) and get a list of integer values from that. You can do that as follows (with some explanations on my part):
student_scores_string = input('Input a list of student scores: ')
(That line will just get a string inputted by the user.)
student_scores = student_scores_string.split()
(That line will give you a list, with each item in the list being one of the values inputted by the user, with a space as a separator.)
student_scores = [int(x) for x in student_scores]
(That line will loop over the elements in the student_scores list, turn each of them into an inetger - remember, so far we have strings! - and put that into the list.)
Then you can continue with your code.

Assume that the input is in the form '25 30 23' - i.e., a string with integer tokens and whitespace delimiters
scores = input('Input a list of student scores: ')
print('The highest score is', max(map(int, scores.split())))
Output:
The highest score is 30

You need to split the input as list, cause student_scores is a string and does not support item assignment (immutable). Assuming the input separated by space:
student_scores = input('Input a list of student scores: ').split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
highest = 0
for scores in student_scores:
if highest < scores:
highest = scores
print(f'The highest score is {highest}')
To get the highest value, you can use highest = max(student_scores):
print(student_scores := [int(n) for n in input('Input a list of student scores: ').split()])
highest = max(student_scores)
print(f'The highest score is {highest}')
Or:
highest = max([int(n) for n in input('Input a list of student scores: ').split()])
print(f'The highest score is {highest}')

Related

A program that takes user input, stores it into a list, then displays data about the list

I'm trying to solve the following problem:
Write a program that allows a user to keep inputting numbers until 0 is entered. The program should store the numbers in a list, then display the following data:
The list of numbers in ascending order
The lowest number on the list
The highest number in the list
The total of the numbers in the list
The average of numbers in the list
Here's what I have so far:
count = 0
list = []
total = 0
average = 0
index = 0
while True:
userInput = int(input("Enter a number:"))
if userInput == 0:
break
for i in range(userInput):
list.append(i)
list.sort()
print(list)
min_value = min(list)
max_value = max(list)
print("the min value is", min_value)
print("the max value is", max_value)
while index < len(list):
list[index] = int(list[index])
index += 1
for j in list:
total += j
print("the total is", total)
average = total/len(list)
print("the average is", average)
The program creates a weird list, that doesn't look anything like the user input. How can I solve this issue? It would be easier if I knew the length of the list, then I could use the range function and write to the list that way, but the length of the list is up to the user :/
Here's how you can do it:
user_data = [] # Dont name variables that can clash with Python keywords
while True:
userInput = int(input("Enter a number:"))
if userInput == 0:
break
else:
user_data.append(userInput) # append the value if it is not 0
print("The list in ascending order is:", sorted(user_data)) # Ascending order of list
print("the max value is", max(user_data)) # max value of list
print("the min value is", min(user_data)) # min value of list
print("the total is", sum(user_data)) # total of list
print("The average is", sum(user_data)/len(user_data)) # average of list
What you were doing wrong?
Naming a list to a Python keyword is not a good habit. list is a keyword in Python.
Biggest mistake:for i in str(userInput): Appending string of the number instead of int. How will you get the max, min, or total with a string?
You don't need to create one more loop for appending. You can use the same while loop.
Calculating total on your own through a loop is not a bad thing. Instead, I would say a good way to learn things. But I just wanted to tell you that you can use sum() to get the total of a list.
list.sort() will sort the list and print(list.sort()) would lead to None because it just sorts the list and doesn't return anything. To print sorted list use sorted(listname)
Sample Output:
Enter a number:12
Enter a number:2
Enter a number:0
The list in ascending order is: [2, 12]
the max value is 12
the min value is 2
the total is 14
The average is 7.0
I hope you understand and work on your mistakes.

How do I get data from dictionary in python?

a= int(input("Enter number of students:"))
i=1
n = []
t = []
p = []
avg = []
while i<=a:
total=0
name = input("Enter name of student:")
n.append(name)
subjects = int(input("Enter count of subjects:"))
i=i+1
j=1
while j<=subjects:
s = int(input("Enter marks:"))
total = total + s
j=j+1
percentage = (total/(subjects*100))*100
average = total/subjects
t.append(total)
p.append(percentage)
avg.append(avg)
result = dict(zip(n,p))
print("Total marks of", name, "is", total)
print("The students:",n)
print("The total of students:",total)
print("The average of students:",avg)
print("The percentage of students:", percentage)
print("The result of students:", result)
i want to store the data which I get from this code and later on display specific data like if I search for student's name, I'll get his marks and average. how do I do this?
First get the name. Then find the index of that. Now search for the marks, average etc in the arrays. Keep in mind that this will only work when the indices are same for each student data. Imagine that the arrays are stacked on top of each other, the data for each student should be in a straight line(You have done that only here).Oh, and one more thing, they are called arrays, not dictionaries. Dictionaries are initialized with {}(curly brackets).
Here is a sample code:
n=["S1","S2"]
t=[100,70]
avg=[30,20]
#say you want to get the data of S2
i=n.index("S2")
print("Student name: "+str(n[i])+" Student total marks:"+str(t[i])+" Student average: "+str(avg[i]))

How to find the average of an array and pin it with its corresponding name with another array

I have my code set to allow the user to make a list of names for students and another list for their corresponding grades. What I cant seem to figure out is how to take the highest grade, the lowest grade, and the closest to the average then state it with the student it belongs to.
This is what I have so far
# creating statements
students = []
grades = []
print('students:',students)
print('grades:',grades)
looper1 = 0
looper2 = 0
studentappend = 0
gradeappend = 0
# list creation
while looper1 != 2:
print('please choose an option:')
print('1: add student and grade')
print('2: Finish step')
looper1 = int(input())
if looper1 ==1:
students.append(input('enter student name: '))
grades.append(int(input('enter grade:')))
print('students:',students)
print('grades:',grades)
if looper1 ==2:
break
if looper1 !=1 and looper1 !=2:
print('Invalid. enter 1 or 2')
print('students:',students)
print('grades:',grades)
print("Largest element is:", max(grades))
On the last line I have it set to say "Largest grade is: 55" for example, but I want to make it say the name the grade belongs to as well. For example "Bill has the largest grade of 55" This will apply to the lowest grade and the grade that is the closest to the average. I was hoping the max() function would print the number that would tell me where the grade I was looking for was located rather then simply stating it.
Here is a solution with modifications to make your code more streamlined:
students = []
grades = []
#gather input
looper = 1
while looper == 1:
students.append(input('enter student name: '))
grades.append(int(input('enter grade: ')))
looper = int(input('Enter 1 to add more data or another number to exit: '))
#calculate closest to mean
true_mean = sum(grades)/len(grades)
close_to_mean = 0
for i, grade in enumerate(sorted(grades)):
if grade < true_mean < sorted(grades)[i+1]:
close_to_mean = grade
print('students:',students)
print('grades:',grades)
print(f"Highest grade is: {max(grades)} and belongs to {students[grades.index(max(grades))]}.")
print(f"Lowest grade is: {min(grades)} and belongs to {students[grades.index(min(grades))]}.")
print(f"Closest to mean grade is: {close_to_mean} and belongs to {students[grades.index(close_to_mean)]}.")
You can reference the index location for the highest value in the grades list and use that index to return the corresponding student in the students list.
print(students[grades.index(max(grades))]+" has the larges grade of "+str(max(grades)))
Note that the index method returns the index of the first matching item in the list. So if two students are tied with the highest score, it will only return the one listed first.
If you aren't opposed, another approach is to use NumPy functions.
np.argmax and np.argmin give the indices of the (first occurrence of) the maximum and minimum value in an array or list.
To get the name of the student with the highest grade: students[np.argmax(grades)]
To get the name of the student with the lowest grade: students[np.argmin(grades)]
To get the name of the student with the grade closest to the average, you may need list comprehension to calculate the absolute difference between the average grade and each student's grade:
students[np.argmin(np.abs([x - np.mean(grades) for x in grades]))]
Alternatively, instead of list comprehension, you can directly cast it to a numpy array:
students[np.argmin(np.abs(np.array(grades) - np.mean(grades)))]

How do I separate the numbers from an input in order to add them?

I am trying to have the user input a series of numbers (separated by commas) to receive the total of them.
I have tried (with no luck):
values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)
values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)
If the user inputs 5.5,6,5.5 the expected output will be 17.
You're almost there.
After splitting, the values will still be strings, so you have to map them to float.
values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))
Output:
The total sum is: 17.0
Side note: Please don't name your variables list or sum, otherwise you will shadow the python built-ins!
After you split the values by comma into a list, you need to convert them from strings to numbers. You can do that with
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [float(x) for x in lst]
total = sum(lst)
print("The total sum is: ", total)
For reference, see List Comprehensions in Python.
(Also, you shouldn't use list as a variable name, since that's a function in Python.)
You have to convert the inputs to float:
numbers = input("Input some comma seprated numbers: ")
result = sum([float(n) for n in numbers.split(',')])
print(result)
You have to convert to numbers before adding them together.
For example, you could convert them all into floats:
input_str = input("Input some comma seprated numbers: ")
# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]
# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
try:
n = float(s)
number_list.append(n)
except ValueError:
pass
print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))
# empty list to store the user inputs
lst = []
# a loop that will keep taking input until the user wants
while True:
# ask for the input
value = input("Input a number: ")
# append the value to the list
lst.append(value)
# if the user wants to exit
IsExit = input("enter exit to exit")
if 'exit' in IsExit:
break
# take the sum of each element (casted to float) in the lst
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))
OUTPUT:
Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0
It's hard to know what went wrong w\o a sample of the error\output code.
I think the issue is in getting the sum of list (very bad name btw) when it's a list of strings.
please try the following
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)
This code will work when expecting integers, if you want floats then change the list comprehension.
Try not to name objects with the same name of standard objects such as list,int,str,float etc...
use below
print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

Categories

Resources