NameError: name 'now' is not defined [duplicate]

假装没事ソ 提交于 2019-12-10 19:54:25

问题


From this source code:

def numVowels(string):
    string = string.lower()
    count = 0
    for i in range(len(string)):
        if string[i] == "a" or string[i] == "e" or string[i] == "i" or \
            string[i] == "o" or string[i] == "u":
            count += 1
    return count

print ("Enter a statement: ")
strng = input()
print ("The number of vowels is: " + str(numVowels(strng)) + ".")

I am getting the following error when I run it:

Enter a statement:
now

Traceback (most recent call last):
  File "C:\Users\stevengfowler\exercise.py", line 11, in <module>
    strng = input()
  File "<string>", line 1, in <module>
NameError: name 'now' is not defined

==================================================

回答1:


Use raw_input() instead of input().

In Python 2, the latter tries to eval() the input, which is what's causing the exception.

In Python 3, there is no raw_input(); input() would work just fine (it doesn't eval()).




回答2:


use raw_input() for python2 and input() in python3. in python2, input() is the same as saying eval(raw_input())

if you're running this on the command line, try $python3 file.py instead of $python file.py additionally in this for i in range(len(strong)): I believe strong should say string

but this code can be simplified quite a bit

def num_vowels(string):
    s = s.lower()
    count = 0
    for c in s: # for each character in the string (rather than indexing)
        if c in ('a', 'e', 'i', 'o', 'u'):
            # if the character is in the set of vowels (rather than a bunch
            # of 'or's)
            count += 1
    return count

strng = input("Enter a statement:")
print("The number of vowels is:", num_vowels(strng), ".")

replacing the '+' with ',' means you don't have to explicitly cast the return of the function to a string

if you'd prefer to use python2, change the bottom part to:

strng = raw_input("Enter a statement: ")
print "The number of vowels is:", num_vowels(strng), "."


来源:https://stackoverflow.com/questions/15190632/nameerror-name-now-is-not-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!