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

Python函数内stop变量无法跨作用域调用致计算失败求助

问题根源
  • 变量作用域限制:stop、adultnumb、childnumb都是passinfo()函数内的局部变量,Python中局部变量无法被函数外部的代码直接访问,所以你写在函数外的if-elif分支根本拿不到这些值。
  • 代码结构错误:票价计算的逻辑块直接放在全局作用域,既没有嵌套到passinfo()内部,也没有通过函数返回值获取所需变量,导致逻辑完全脱节。
  • 拼写错误:第三个分支里的childnum是笔误,应该是childnumb。
修复方案

下面是完整修正后的代码,采用「函数返回变量+外部计算」的方式,让逻辑更清晰:

修正后的代码

wash_to_balt_adult = 20
wash_to_balt_child = 10
wash_to_philly_adult = 25
wash_to_philly_child = 10
wash_to_ny_adult = 30
wash_to_ny_child = 15

def welcome():
    print("Welcome to Kevin's Travel Service!")

def myname():
    print('Written by: Kevin B')
    print('Written on date: Feb 26,2023')

def stops_prices():
    # Prompt user on where they are stopping at
    print("\nThe stops for the bus stops at are Baltimore, Philiadelphia, and New York.\n")
    print(f'The price from Washington to Baltimore is: ${wash_to_balt_adult} for adults, ${wash_to_balt_child} for children.\n')
    print(f'The price from Washington to Philiadelphia is: ${wash_to_philly_adult} for adults, ${wash_to_philly_child} for children.\n')
    print(f'The price from Washington to New York is: ${wash_to_ny_adult} for adults, ${wash_to_ny_child} for children.\n')

def passinfo():
    validname = False
    adultnumb = 0
    childnumb = 0

    # Prompt user on where they are departing bus to
    stop = int(input("\n\nWhere are you getting off the bus at? Please enter 1 for Baltimore, 2 for Philadelphia, or 3 for New York, <Enter> to exit:\t"))

    # Validate stop
    while not validname:
        if stop < 1 or stop > 3:
            stop = int(input("Invalid number. Please enter 1 for Baltimore, 2 for Philadelphia, or 3 for New York: "))
        else:
            validname = True

    adultnumb = int(input("How many adults? "))
    adultnames = []
    for number in range(adultnumb):
        print("\nAdult", number+1)
        name = input("What is the passenger's name? ")
        adultnames.append(name)

    childnumb = int(input("\nHow many children? "))
    childnames = []
    for number in range(childnumb):
        print("\nChild", number+1)
        name = input("What is the passenger's name? ")
        childnames.append(name)
      
    print ('\n# of Adults: ',adultnumb,'\n# of Children: ',childnumb,'\nWhich Stop: ',stop,'\nName of Adults: ',adultnames,'\nName of Children: ',childnames,'\n')
    
    # 返回需要的变量给外部使用
    return stop, adultnumb, childnumb

# 主逻辑执行
welcome()
print('\n')
myname()
print('\n')
# 调用passinfo并接收返回的变量
stop, adultnumb, childnumb = passinfo()

# 票价计算逻辑
if stop == 1:
    adultprice = adultnumb * wash_to_balt_adult
    childprice = childnumb * wash_to_balt_child
elif stop == 2:
    adultprice = adultnumb * wash_to_philly_adult
    childprice = childnumb * wash_to_philly_child
elif stop == 3:
    adultprice = adultnumb * wash_to_ny_adult
    childprice = childnumb * wash_to_ny_child

totalprice = adultprice + childprice
print(f"\nAdult Total: ${adultprice}")
print(f"Child Total: ${childprice}")
print(f"Overall Total: ${totalprice}")

关键改动说明

  1. 修复作用域问题:让passinfo()返回stop、adultnumb、childnumb三个变量,在调用函数时接收这些值,外部计算逻辑就能正常访问。
  2. 优化代码结构:把票价计算逻辑放在函数调用之后,与用户输入逻辑解耦,更易维护。
  3. 修正拼写错误:将childnum改为childnumb,避免运行报错。
  4. 简化输出格式:用f-string替代字符串拼接,让价格打印代码更简洁。
  5. 移除无用代码:删掉了未实际使用的main()函数,简化代码结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:55:21