如果用户输入了'tea'
或't'
作为选择,我如何将变量beverage.lower()
定义为'tea'
?因为
if beverage.lower()=='t'or beverage.lower()=='tea':
beverage.lower()=='tea'
line对整个程序本身绝对没有任何影响?
while True:
beverage=raw_input("What is your preferred beverage: coffee, or tea?")
if beverage.lower() not in ('coffee','tea','t','c'):
if beverage.lower()=='t'or beverage.lower()=='tea':
beverage.lower()=='tea'
elif beverage.lower()=='c'or beverage.lower()=='coffee':
beverage.lower()=='coffee'
print("Sorry! I didn't quite catch that. Please try again! (Note that you can use the letter 'c' or the letter 't' to denote coffee or tea respectively!)")
continue
else:
print("Ah! Fantastic choice!")
break
同样,我将如何将输入的beverage.lower()
用户定义为另一个变量?
答案 0 :(得分:5)
您的代码在流控制(if
块)和值分配(==
和=
)中遇到各种问题。经过一些更改后,就在这里。
并尽量不要混合使用4个空格的制表符和8个空格的制表符。始终坚持使用
while True:
beverage = input("What is your preferred beverage: coffee, or tea?").lower() # much efficient to .lower() only once
if beverage in ('coffee','tea','t','c'): # Change this to 'in'
if beverage == 't' or beverage == 'tea':
beverage = 'tea' # value assignments are done with = not ==
elif beverage == 'c' or beverage == 'coffee':
beverage = 'coffee' # value assignments are done with = not ==
print('Ah! Fantastic choice!')
print('You have chosen {}'.format(beverage))
else:
print("Sorry! I didn't quite catch that. Please try again! (Note that you can use the letter 'c' or the letter 't' to denote coffee or tea respectively!)")
O / P:
What is your preferred beverage: coffee, or tea?c
Ah! Fantastic choice!
You have chosen coffee
What is your preferred beverage: coffee, or tea?t
Ah! Fantastic choice!
You have chosen tea
What is your preferred beverage: coffee, or tea?x
Sorry! I didn't quite catch that. Please try again! (Note that you can use the letter 'c' or the letter 't' to denote coffee or tea respectively!)
答案 1 :(得分:3)
只需使用变量来赋值:
if beverage.lower()=='t'or beverage.lower()=='tea':
beverage = 'tea'
分配另一个变量:
input_var = None
beverage=raw_input("What is your preferred beverage: coffee, or tea?")
if beverage.lower()=='t'or beverage.lower()=='tea':
input_var = 'tea'
print 'Input value: ', input_var
答案 2 :(得分:0)
如果要修改变量beverage=beverage.lower()
的值,可以使用语句beverage
。
从您的问题中我相信那是您的疑问。
答案 3 :(得分:0)
if beverage.lower()=='t'or beverage.lower()=='tea':
beverage.lower()=='tea'
以上声明无效,因为您已经这样写。 如果没有输入('coffee','tea','t','c'),则绝对没有机会进入上述代码。
您需要将if beverage.lower() not in ('coffee','tea','t','c'):
替换为
if beverage.lower() in ('coffee','tea','t','c'):
此外,您还需要在if条件中将beverage.lower()=='tea'
替换为beverage.lower()='tea'
答案 4 :(得分:0)
在分配值“ tea”或“ t”时,您犯了一个小错误。 它应该像- Drink ='tea'而不是drink.lower()=='tea'