3

このソースコードから:

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

実行すると、次のエラーが表示されます。

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

==================================================
4

2 に答える 2

13

raw_input()の代わりに使用しinput()ます。

Python 2 では、後者が入力を試みeval()ます。これが例外の原因です。

Python 3 にはraw_input();はありません。input()うまく動作します(そうではありませんeval())。

于 2013-03-03T20:45:28.320 に答える
0

raw_input()python2 および python3 で使用しinput()ます。python2では、input()言っているのと同じですeval(raw_input())

コマンドラインでこれを実行している場合は、これを 追加する$python3 file.py代わりに試してください$python file.pyfor i in range(len(strong)):strongstring

しかし、このコードはかなり単純化できます

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

「+」を「,」に置き換えると、関数の戻り値を明示的に文字列にキャストする必要がなくなります

python2 を使用したい場合は、下部を次のように変更します。

strng = raw_input("Enter a statement: ")
print "The number of vowels is:", num_vowels(strng), "."
于 2013-03-03T20:54:29.563 に答える