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

如何为已调用的函数赋值变量?Python Blackjack开发问题

解决方案

你遇到的核心问题是当前sign_in()函数直接在内部启动了后续流程(调用play_choice_user),没有返回用户信息,导致上层无法获取信用额度而不得不重复调用函数。可以通过让sign_in()返回用户登录信息,并调整调用逻辑来解决,具体修改如下:

1. 修改sign_in()函数,返回用户信息

将sign_in()改为验证成功后返回包含信用额度的登录信息,而非直接调用后续函数:

def sign_in():
    while True:
        username = input('please input your username: ')
        password = input('please enter your password: ')
        # 用with语句安全打开文件,避免资源泄漏
        with open('blackjack.txt', 'r') as f:
            for line in f.readlines():
                # 去除换行符后拆分数据
                login_info = line.strip().split('-')
                if username == login_info[0] and password == login_info[1]:
                    print(f'Welcome back, {username}')
                    print(f'You have {login_info[3]} credits in your account!')
                    return login_info  # 返回完整用户信息
            # 未匹配到账号时提示
            print('Invalid username or password, please try again.')

2. 调整from_menu()函数,接收并传递用户信息

修改from_menu(),接收sign_in()的返回值,再将用户信息传递给play_choice_user:

def from_menu(menu_choice):
    if menu_choice == '1':
        user_login_info = sign_in()
        # 登录成功才进入后续选择
        if user_login_info:
            play_choice_user(user_login_info)
    else:
        register()

3. 完善菜单函数(补充缺失的menu()定义)

你现有代码中调用了menu()但未定义,将开头的菜单逻辑封装为返回选择的函数:

def menu():
    print('Welcome to the blackjack table, \nif you have an account please sign in, if you are new please register\n1. Sign in.\n2.Register')
    while True:
        menu_choice = input('Choice: ')
        if menu_choice in ['1', '2']:
            return menu_choice
        else:
            print('Please enter only 1 or 2')

4. 修正play()函数的参数问题

你当前调用play(user_credits, card_value)时,play()定义的参数是play(user_credits, card_value, card_number, card_suit),参数不匹配会报错,需要调整为一致:

# 示例:如果card_value等参数是在play内部生成,可修改函数定义
def play(user_credits):
    while True:
        user_hand_value = 0
        try:
            player_bet = int(input('please enter a starting bet: '))
        except ValueError:
            print('Please enter a valid number.')
            continue
        if player_bet > user_credits:
            print('You don\'t have enough credits!')
            continue
        new_user_credits = user_credits - player_bet
        # 这里补充生成card_number、card_suit、card_value的逻辑
        card_number = 'Ace'
        card_suit = 'Hearts'
        card_value = 11
        print(f'you have been given a card: {card_number} of {card_suit}')
        user_hand_value = card_value
        # 后续游戏逻辑...
        break

流程说明

  1. menu()返回用户选择的登录/注册选项
  2. from_menu()根据选项调用sign_in(),接收返回的用户信息
  3. play_choice_user()从用户信息中提取信用额度,调用play()时传入
  4. 全程只调用一次sign_in(),无需重复执行登录验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:18:13