2 回答

TA貢獻1826條經驗 獲得超6個贊
class PrintVowels():
def __init__(self):
self.vowels = []
def get_vowels(self):
while True:
print("Enter a sentence: ")
inp = input()
self.vowels.extend([i for i in inp.lower() if i in 'aeiou'])
print("Do you want to input more?")
inp2 = input()
if inp2.lower() == 'no':
break
return self.vowels
ob1 = PrintVowels()
print (ob1.get_vowels())
#output['e', 'o', 'o', 'e', 'o', 'o']

TA貢獻1865條經驗 獲得超7個贊
既然你提到用戶輸入應該只是yes/noor YES/NO,我還添加了一些使用輸入和驗證它的方法。
def validate_input(inp2):
if inp2 == 'yes' or inp2 == 'YES' or inp2 == 'no' or inp2 == 'NO':
return True
else:
return False
def take_input(self):
print("Enter a sentence: ")
inp = input()
self.vowels.extend([i for i in inp.lower() if i in 'aeiou'])
class PrintVowels():
def __init__(self):
self.vowels = []
def get_vowels(self):
take_input(self)
while True:
print("Do you want to input more?")
inp2 = input()
valid_inp = validate_input(inp2)
if valid_inp:
if inp2.lower() == 'no':
break
else:
take_input(self)
else:
print("Error: Please try again with a valid input!")
continue
return self.vowels
ob1 = PrintVowels()
print (ob1.get_vowels())
輸出:
Enter a sentence:
my name is Mike
Do you want to input more?
blahhhhWHAAT
Error: Please try again with a valid input!
Do you want to input more?
oops
Error: Please try again with a valid input!
Do you want to input more?
yes
Enter a sentence:
I am from China
Do you want to input more?
Huhhhh
Error: Please try again with a valid input!
Do you want to input more?
NO
['a', 'e', 'i', 'i', 'e', 'i', 'a', 'o', 'i', 'a']
添加回答
舉報