You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码无法兼容大小写Y/y输入实现相同输出如何解决?

问题原因

你编写的判断逻辑存在方向错误:

  • 代码中photo == ("y").upper()的执行逻辑是先将固定字符串"y"转为大写"Y",再和用户输入的photo值做相等判断,相当于仅匹配用户输入大写Y的场景,输入小写y自然无法满足判断条件,所以会进入else分支输出错误结果。

修复方案

将用户输入的photo值统一转为大写(或小写)后再做判断,即可同时匹配大小写输入:
将原判断语句

if photo == ("y").upper():

修改为:

if photo.upper() == "Y":

完整修正代码(仅修复核心匹配问题)

print("Welcome to the rollercoaster!")
age = int(input("What is your age? ")) # 此处顺便修正了原代码中you'r的拼写错误
height = int(input("What is your height in cm? "))
photo = input("Would you like a photo? please type Y or N ")
if height >= 120:
  print("you can get on this ride!")
  if age <= 12:
    if photo.upper() == "Y":
      print("that will be an extra £3.00 for the photo and £5.00 for the ride, the total now comes to £8.00.")
    else:
      print ("The ticket price is £5.00") 
  elif age < 18:
    print ("The ticket price is £7.00")
  else:
    print ("The ticket price is £8.00")
else:
  print("you are not tall enough to ride this ride")

可选扩展:全年龄段支持photo费用计算

如果需要让12岁以上的用户也能选择是否购买照片,可调整逻辑把photo判断提到年龄判断之后统一处理:

print("Welcome to the rollercoaster!")
age = int(input("What is your age? "))
height = int(input("What is your height in cm? "))
photo = input("Would you like a photo? please type Y or N ")
if height >= 120:
  print("you can get on this ride!")
  # 先计算基础票价
  if age <= 12:
    price = 5
  elif age < 18:
    price = 7
  else:
    price = 8
  # 再判断是否需要加照片费用
  if photo.upper() == "Y":
    print(f"that will be an extra £3.00 for the photo and £{price}.00 for the ride, the total now comes to £{price + 3}.00.")
  else:
    print(f"The ticket price is £{price}.00")
else:
  print("you are not tall enough to ride this ride")

内容的提问来源于stack exchange,提问作者Nod786

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:39:05