无法理解 *(星号)在 Python 变量赋值中的作用

Trouble understanding what * (asterisk) does in Python variable-assignment

我是编程新手,目前正在学习 Zelle 的 "Python Programming: An Introduction to Computer Science,2nd ed"。

在做书中的一个练习时,我在理解作者提供的解决方案时遇到了一些困难。 练习基本上是做一个程序,给一定范围的分数打分。

问题如下: "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."

这是我自己的练习源代码:

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.")

它工作得很好,根据我的搜索,是解决此类问题的标准方法。

那么,笔者的解决方案如下:

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])

我发现它更加简洁,因为整个 if-elif-else 块可以仅用 2 行来更简洁地表达。 但是,我在尝试理解他的代码的第二行时遇到了麻烦: 成绩 = 60*"F"+10*"D"+10*"C"+10*"B"+11*"A" 这条线究竟是如何工作的?在这样的变量赋值的情况下,* 有什么作用?

对不起,如果已经有一个类似的问题回答了我的查询,但我能找到的最接近的是关于 * 在参数中的作用。 如果是这样的话,我很乐意 link 被引导到那里。

感谢您的帮助!

这实际上与变量赋值无关。在Python中,可以将一个字符串乘以一个非负整数;效果是将字符串重复适当的次数。所以,例如,5*"A"+2*"B" 是 "AAAAABB".

(所以在您正在查看的实际代码中,您有 60 个 "F"s -- 所以当 0 <= score < 60 时 grades[score] 将是 "F" --然后是 10 "D"s —— 所以当 60 <= score < 70 时 grades[score] 将是 "D" —— 依此类推。)

与赋值无关。 3*"F" 就是 "FFF",就这么简单。 "FFF"+"DDD""FFFDDD"grades 因此是一个包含 101 个字符的字符串(60 个 F,10 个 D... 0100 之间的每个分数一个),您只需使用 [=17 选择正确的一个=].

星号 * 将连接前面字符串的 X 个版本,其中 X 由以下数字定义。 + 将连接前后字符串

>>> "x"*2
'xx'
>>> "x"*2+"y"*2
'xxyy'
>>>