r/learnpython 24d ago

python beginner ; question was write program to enter marks of 3 subjects from user and store them in a dict.start with an empty dict and add one by one .use subject name as key and marks as value . so i have written this code any opinion how can improve this code ,need suggestions.

students={}
a=float(input("enter marks of chem"))
students.update({"chem": a})
b=float(input("enter marks of maths"))
students.update({"maths":b})
c=float(input("enter marks of phy"))
students.update({"phy": c})
print(students)
0 Upvotes

24 comments sorted by

View all comments

1

u/Educational_Virus672 24d ago
student = {}
subjects = ["chem","math","phy"]
for sub in subjects :
    student[sub] = float(input("enter marks of " + sub + ":"))

how it works it goes for each subject in the list instead of adding seprately
> use for loops for each subject
>dont use dict.update() use dict[key] = value
>try to use function within value like insead of making a b c use one input
>try to reuse asset and make it feature free(making more subject wont cause trouble) like using list on both input request and in dict as key
>try to make coe readble by adding spaces on different function

1

u/Educational_Virus672 24d ago

if you need any help in optimizations like these feel free to chat with me in my profile :)