I'm new to programming and am currently working through "Python Programming: An Introduction to Computer Science,2nd ed" by Zelle.
While working on one of the exercises in the book,I encountered some trouble understanding a solution provided by the author. The exercise is basically to make a program that gives a letter grade for a certain range of points.
The question is as follows: "A certain CS professor gives 100-points exams that are graded on the scale 90-100:A, 80-89:B, 70-79:C, 60-698:D, <60:F. Write a program that accepts an exam score as input and prints out the corresponding grade."
Here is my own source code for the exercise:
score = float(input("Enter your quiz score: "))
if score >= 90:
print("You got an A.")
elif score >= 80:
print("You got a B.")
elif score >= 70:
print("You got a C.")
elif score >= 60:
print("You got a D.")
else:
print("You got a F.")
And it works perfectly well and from my searches,is a standard solution to such a problem.
Then,the author's solution is as follows:
score = eval(input("Enter the score (out of 100): "))
grades = 60*"F"+10*"D"+10*"C"+10*"B"+11*"A"
print("The grade is", grades[score])
Which I found to be so much neater as the entire if-elif-else chunk could be much more succinctly expressed with only 2 lines. However,I'm finding trouble trying to understand the 2nd line of his code: grades = 60*"F"+10*"D"+10*"C"+10*"B"+11*"A" How does this line work exactly and what does the * do in the case of a variable assignment such as this?
Pardon me if there's already a similar question to this that answers my query,but the closest I could find was about what * does in parameters. I would gladly appreciate a link to be directed there if that's that case.
Thanks for the help!
evalis unnecessary, and while building a 101-character string isn't a problem, the solution doesn't scale well if applied to similar problems where the string would be longer.