我目前正在为我的程序使用此代码,但我需要程序在用户未输入输入时停止。除了我不知道该怎么做。请帮忙。三江源!
line = input("Enter a word: ")
vowels = 0
for word in line:
if word == 'a':
vowels += 1 #more than or equal to 1
if word == 'e':
vowels += 1
if word == 'i':
vowels += 1
if word == 'o':
vowels += 1
if word == 'u':
vowels += 1
print (line, "contains", vowels, "vowels ." )
答案 0 :(得分:4)
我可以建议:
import sys
line = input("enter a word: ").strip()
if not line:
sys.exit(0)
vowels = set('aeiouAEIOU')
numVowels = 0
for char in line:
if char in vowels:
numVowels += 1
print(line, "contains", numVowels, "vowels." )
这是一个更简洁的版本:
import sys
line = input("enter a word: ").strip()
if not line:
sys.exit(0)
vowels = set('aeiouAEIOU')
numVowels = sum(1 for char in line if char in vowels)
print(line, "contains", numVowels, "vowels." )
答案 1 :(得分:0)
while True:
line = raw_input('enter a word: ')
if not line:
break
vowels = 0
for word in line:
if word == 'a':
vowels += 1
if word == 'e':
vowels += 1
print (line, 'contains', vowels, 'vowels.')
答案 2 :(得分:0)
以下是另一种方法:
#!/usr/bin/python
vowel = set('aeiou')
while True:
line = input("enter a word: ")
if not line.strip():
break
else:
count = len([x for x in line if x in vowel])
print('%s: contains: %d vowels' % (line, count))
print('Exiting.')
输出:
[what_you_got]:[~/script/python]:$ python f.py
enter a word: oh my god
oh my god: contains: 2 vowels
enter a word: really are u kidding me
really are u kidding me: contains: 8 vowels
enter a word:
Exiting.
[what_you_got]:[~/script/python]:$