为什么它总是以“恭喜!你赢了一只木兔!”来回归?
似乎x
和y
值不会改变。
def which_prize(Points):
y=1
if 0<= Points >=50 :
x="wooden rabbit"
elif 151<= Points >=180 :
x="wafer-thin mint"
elif 181<= Points >=200 :
x="penguin"
else:
y=0
re="Congratulations! You have won a {}!".format(x)
if y==0 :
re= "Oh dear, no prize this time."
return re
#print(which_prize(51))
print(which_prize(151))
print(which_prize(181))
print(which_prize(200))
print(which_prize(18000))
答案 0 :(得分:1)
对于大于或等于50的每个if
,第一个Point
块都为真。
if 0 <= Points >= 50:
一个工作示例:
def which_prize(Points):
y = 1
x = ''
if 0 <= Points <= 50:
x = "wooden rabbit"
elif 151 <= Points <= 180:
x = "wafer-thin mint"
elif 181 <= Points <= 200:
x = "penguin"
else:
y = 0
re = "Congratulations! You have won a {}!".format(x)
if y == 0:
re = "Oh dear, no prize this time."
return re
print(which_prize(51))
print(which_prize(151))
print(which_prize(181))
print(which_prize(200))
print(which_prize(18000))
将打印:
Oh dear, no prize this time.
Congratulations! You have won a wafer-thin mint!
Congratulations! You have won a penguin!
Congratulations! You have won a penguin!
Oh dear, no prize this time.
答案 1 :(得分:0)
def which_prize(points):
prize = None
if 0 <= points <= 50:
prize = "a wooden rabbit"
elif 151 <= points <= 180:
prize = "a wafer-thin mint"
elif 181 <= points <= 200:
prize = "a penguin"
if prize:
return "Congratulations! You have won " + prize + "!"
else:
return "Oh dear, no prize this time."
print(which_prize(51))
print(which_prize(151))
print(which_prize(181))
print(which_prize(200))
print(which_prize(18000))
答案 2 :(得分:0)
这里有更好的解决方案:
points = 199
if points <= 50:
result = "Congratulations! You won a wooden rabbit!"
elif points <= 150:
result = "Oh dear, no prize this time."
elif points <= 180:
result = "Congratulations! You won a wafer-thin mint!"
else:
result = "Congratulations! You won a penguin!"
print(result)
输出:
Congratulations! You won a penguin!