简体   繁体   English

将 break 和 else 与 for 循环结合使用的问题

[英]Problem with the use of break and else in conjunction with a for loop

in the book Kiusalaas, J. (2013).在 Kiusalaas, J. (2013) 一书中。 Numerical methods in engineering with Python 3. Cambridge University Press. Python 3 工程中的数值方法。剑桥大学出版社。 page 10 the author has this line of code which does not work for me:第 10 页作者有这行代码对我不起作用:

list = ['Jack', 'Jill', 'Tim', 'Dave']
name = eval(input('Type a name: '))  # Python input prompt
for i in range(len(list)):
    if list[i] == name:
        print(name,'is number',i + 1,'on the list')
        break
else:
    print(name,'is not on the list')

I have this error: NameError: name "Tim" is not defined我有这个错误: NameError: name "Tim" is not defined

I'm working locally using VS and a Virtual environment by anaconda我在本地使用 VS 和 anaconda 的虚拟环境工作

Remove eval :删除eval

list = ['Jack', 'Jill', 'Tim', 'Dave']
name = input('Type a name: ')
for i in range(len(list)):
    if list[i] == name:
        print(name,'is number',i + 1,'on the list')
        break
else:
    print(name,'is not on the list')

# Type a name: Tim
# Tim is number 3 on the list

As indicated by others, and in the other answer, the problem is the use of eval() .正如其他人所指出的,在另一个答案中,问题在于eval()的使用。

Your original code works if, instead of Tim , you try to enter 'Tim' (after fixing the quotes), because Python will evaluate that into a string, which matches the value in the list.如果您尝试输入'Tim'而不是Tim ,则您的原始代码有效(在修复引号之后),因为 Python 会将其计算为一个字符串,该字符串与列表中的值匹配。

However, this is exceedingly bad practice and should not be used unless there is really good reason to do so and the user of your script understands they are expected and able to enter working Python code.但是,这是非常糟糕的做法,除非有充分的理由这样做,并且脚本的用户理解他们是预期的并且能够输入工作 Python 代码,否则不应使用这种做法。

The book goes on without much explanation of this, and seems to use it as a device to explain more about types.这本书没有太多解释,似乎用它作为解释更多关于类型的工具。 Also, the typographic use of quotes like these 'Input a: ' instead of the regular ones like these 'Input a: ' shows that the author does not have the reader's interest at heart.此外,像'Input a: '这样的引号而不是像'Input a: '这样的常规引号的印刷使用表明作者并没有把读者的兴趣放在心上。

The real answer has to be: get a better book and warn others about using "Kiusalaas, J. (2013). Numerical methods in engineering with Python 3. Cambridge University Press"真正的答案必须是:买一本更好的书并警告其他人不要使用 “Kiusalaas, J. (2013)。Python 3 工程中的数值方法。剑桥大学出版社”

Perhaps it's fine for numerical methods, but it's lousy for teaching Python.也许它对于数值方法很好,但是对于 Python 的教学就很糟糕了。

Note: perhaps the June 2014 online edition is better, but I'd spend my money on something else.注意:也许 2014 年 6 月的在线版更好,但我会把钱花在别的东西上。 Besides, who teaches programming in 2022 on a modern language with an 8-9 years old book?此外,谁在 2022 年用一本 8-9 岁的书教授现代语言的编程?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM