[英]If/elif/else statements
我的程序/項目是關於詢問用戶他是否足夠高可以乘坐過山車並提供“是”或“否”答案的陳述。 我的問題是,如果用戶輸入的不是是或否,我希望它說:“請輸入是或否。” 我的代碼一直有效,直到我嘗試插入該語句。 如何插入該語句而不會出現錯誤。
rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
print('Please exit the ride!')
elif rc1 == 'yes':
rc2 = int(input('How tall are you? '))
if rc2 <= 119:
print('You are not tall enough for this ride!')
else:
print('Enter and enjoy the ride!')
只是一些快速的事情。 就像上面一樣,while 循環是 go 不斷提示用戶的好方法,直到您以所需格式輸入並且您的 rc2 變量在 if 語句中定義並且不可用於比較,因此需要提前定義它適用於您的第二個條件。 像這樣的東西:
rc1 = input('Are you tall enough to ride this roller coaster? ')
rc2 = 0
while str.lower(rc1) not in ('yes', 'no'):
print('Please answer yes or no')
rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
print('Please exit the ride!')
elif rc1 == 'yes':
rc2 = int(input('How tall are you? '))
if rc2 <= 119:
print('You are not tall enough for this ride!')
else:
print('Enter and enjoy the ride!')
我添加了一個 while 循環,看起來如下所示:
answer = None
rc2 = None
while answer not in ("yes", "no"):
answer = input('Are you tall enough to ride this roller coaster? ')
if answer == "yes":
rc2 = int(input('How tall are you? '))
elif answer == "no":
print('Please exit the ride!')
else:
print("Please enter yes or no.")
if rc2 <= 119:
print('You are not tall enough for this ride!')
else:
print('Enter and enjoy the ride!')
這是我的解決方案:
rc1 = input('Are you tall enough to ride this roller coaster? ')
rc2 = None
if rc1 == 'no':
print('Please exit the ride!')
elif rc1 == 'yes':
rc2 = int(input('How tall are you? '))
if rc2 != None:
if rc2 <= 119:
print('You are not tall enough for this ride!')
else:
print('Enter and enjoy the ride!')
或者
rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
print('Please exit the ride!')
elif rc1 == 'yes':
rc2 = int(input('How tall are you? '))
if rc2 <= 119:
print('You are not tall enough for this ride!')
else:
print('Enter and enjoy the ride!')
您必須在開始時初始化rc2
變量。 您收到錯誤的原因是程序正在檢查rc2
是否小於或等於 119,而它甚至不知道變量是什么。 rc2
僅在rc1
等於 yes 時存在。 為了以后使用它, rc2
必須存在,無論條件如何。
我還得到了一個快速清潔的解決方案,比我應該擁有的更多。 感謝您的幫助
rc1 = input('Are you tall enough to ride this roller coaster? ')
while rc1 not in ('yes', 'no'):
print('Please enter yes or no.' )
rc1 = input('Are you tall enough to ride this roller coaster? ')
if rc1 == 'no':
print('Please exit the ride!')
elif rc1 == 'yes':
rc2 = int(input('How tall are you? '))
if rc2 <= 119:
print('You are not tall enough for this ride!')
else:
print('Enter and enjoy the ride!')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.