Home > Net >  Problem with the use of break and else in conjunction with a for loop
Problem with the use of break and else in conjunction with a for loop

Time:06-25

in the book Kiusalaas, J. (2013). Numerical methods in engineering with Python 3. Cambridge University Press. page 10 the author has this line of code which does not work for me:

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

I'm working locally using VS and a Virtual environment by anaconda

CodePudding user response:

Remove 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

CodePudding user response:

As indicated by others, and in the other answer, the problem is the use of 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.

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.

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.

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"

Perhaps it's fine for numerical methods, but it's lousy for teaching Python.

Note: perhaps the June 2014 online edition is better, but I'd spend my money on something else. Besides, who teaches programming in 2022 on a modern language with an 8-9 years old book?

  • Related