我是编程的新手,所以我正在尝试一些东西来看看我是否真正理解。我能够使这个“程序”不区分大小写,但确实很差(因为我必须为相同的答案设置3个变量,只是使其不区分大小写)。我怎样才能使这段代码更好?
fav_color = "Red"
fav_color2 = "RED"
fav_color3 = "red"
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
x = input("What's Carlos' favorite color? ")
guess_count += 1
if x == fav_color:
print("You win!")
break
if x == fav_color2:
print("You win!")
break
if x == fav_color3:
print("You win!")
break
答案 0 :(得分:-1)
使用.lower()
字符串方法将输入返回的字符串转换为小写。
也就是说,
fav_color = 'red'
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = input('What's Carlos' favorite color? ').lower()
guess_count += 1
if guess == fav_color:
print("You win!")
break
仅是让您了解.lower()
方法的工作方式,我将提供一些示例:
>>> 'Hello'.lower()
'hello'
>>> 'hello'.lower()
'hello'
>>> 'HELLO'.lower()
'hello'
>>> 'HeLLo HOW aRe YOu ToDAY?'.lower()
'hello how are you today?'
答案 1 :(得分:-1)
使用str.lower()
(或upper()
)
fav_color = "Red"
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
x = input("What's Carlos' favorite color? ")
guess_count += 1
if x.lower() == fav_color.lower():
print("You win!")
break