如何调试 Python 代码以理解答案?



我试图学习python,不幸的是,看到这段代码,我无法弄清楚为什么结果是33!!

调试是什么?有人告诉我,帮助你找到答案,但我不知道如何找到答案。

这是我当前的代码

x = "c"
y = 3
if "x" in "computer science":
y = y + 5
else:
y = y + 10
if x in "computer science":
y = y + 20
else:
y = y + 40
print (y)

在第三行中,您键入了"x"而不是x,这意味着您正在"计算机科学"中查找一个x字符串,该字符串不存在,因此您的代码将 10 添加到y而不是 5

容易 第一个条件if "x" in "computer science":是在字符串"computer science"中查找字符串"x"。 请注意 x 周围的引号。 这意味着它是一个字符串文字,而不是变量 x。

这意味着执行else代码块,将10添加到y的值(在此之前为 3)。

y的价值现在已int(13)

然后,第二个条件if x in "computer science"在字符串文字"computer science"中查找变量x的值。 由于变量x的值是字符串文字"c",并且在"计算机科学"中有三个"c":条件计算为 True 并执行第一个代码块。

第一个代码块将y的值加 20,这是int(13)。 因此,y最终3 + 10 + 20(33)

y初始化为3。第一个if语句检查字符x是否在字符串computer science中,它不在,所以我们在y中添加10y现在等于 13。在第二个if语句中检查变量的值是否x哪个是c,这是在字符串computer science,所以我们在y中添加20

因此,y33.

这是原因,在你的第一个if语句中

x = "c" #x is a variable containing a string 'c'
y = 3
if "x" in "computer science":
# in this if statement the condition checked if the string x is in "computer science" it didn't check the variable x, just a string 'x' so this statement below will not be executed since the condition is not satisfied
y = y + 5
else: # but this one will be executed since it is the else statement and the if statement is not satisfied which will overwrite the value of y from 3 to 13
y = y + 10
so now the value of y=13
#in your second if statement
if x in "computer science":
#you checked if the variable x is in computer science which basically is true because its is the same as asking 'is 'c' in computer science' so the statement mellow will be executed which will overwrite the value of y from 13 to 33 so when you print y you will get 3
y = y + 20
else:
y = y + 40

-> 如果"计算机科学"中的"x":这意味着如果子字符串"x"(这里用双引号引起来,所以它将被视为字符串)在字符串"计算机科学"中,然后执行 if 块代码。由于"x"不在"计算机科学"中,因此将执行以下其他块:

else:
y = y + 10

因此在此之后 y = 13

-> 现在另一个 if 块将再次检查其条件

if x in "computer science":
y = y + 20
else:
y = y + 40

在这里,在这个代码块中,x被视为存储"c"的变量,并且由于在"计算机科学"中有"c"(在第一个字符位置),if块代码将被执行更新值y = 13到y = 13 + 20 = 33

-> 简单来说,调试意味着识别和删除代码中的错误。 您可以参考此链接以获取有关调试 https://en.wikipedia.org/wiki/Debugging

的详细信息

你已经有了详细的解释(只需要你的大脑)。 WRT/调试工具等,至少有两个可以帮助您跟踪代码执行(这是重点)。

第一个非常简单,它被命名为"打印"。您所要做的就是添加一些print()以找出哪些部分被执行(以及从推论中哪些部分没有执行)以及您的变量在这些点具有哪些值:

x = "c"
y = 3
print('start : x = "{}", y = {}'.format(x, y))
if "x" in "computer science":
y = y + 5
print('"x" in "computer science" - now y = {}'.format(y))
else:
y = y + 10
print('"x" not in "computer science" - now y = {}'.format(y))
if x in "computer science":
y = y + 20
print('x ( = "{}") in "computer science" - now y = {}'.format(x, y))
else:
y = y + 40
print('x ( = "{}") not in "computer science" - now y = {}'.format(x, y))
print (y)

执行时将显示:

start : x = "c", y = 3
"x" not in "computer science" - now y = 13
x ( = "c") in "computer science" - now y = 33
33

另一个工具被命名为步骤调试器,它稍微复杂一些(但功能更强大)。Python附带一个(命令行)步骤调试器,它可能不像GUI那样"性感",但需要零安装,零配置,并且保证在所有环境中工作。(注意,我不打算在这里解释如何使用它,因为它已经记录在案......

if "x" in "computer science":
if x in "computer science":

X与"X"不同

相关内容

最新更新