【问题标题】:Can I use the len(game_content) for my while condition?我可以将 len(game_content) 用于我的 while 条件吗?
【发布时间】:2021-02-17 05:30:18
【问题描述】:

我只是 python 编码的初学者。我的代码有几个问题,希望您能提供帮助。

user_input = str()
counter = 0

game_content = [{'day': 'Day 1: Let your son use the computer for 5 hours. Yes or No?',
                'answer1': 'YES', 'answer2': 'NO',
                'text1': 'An amount has been added to your bill.', 'text2': "No amount has been added to your bill",
                 'bill': '500'},
                {'day': 'Your wife wants to use the washing machine. Should you let her? Yes or No?',
                 'answer1': 'YES', 'answer2': 'NO',
                 'text1': 'An amount has been added to your bill.', 'text2': "No amount has been added to your bill",
                 'bill': '200'}
                ]

def scenarios(count):
    bill_list = []
    user_input = input(game_content[count]['day']).strip().upper()
    if user_input == game_content[count]['answer1']:
        print(game_content[count]['text1'])
        bill_list.append('bill')
        global counter
        counter += 1

    elif user_input == game_content[count]['answer2']:
        print (game_content[count]['text2'])
        counter += 1



while counter <= 1:
    scenarios(counter)

bill_list = []
print("Your bill is: ", bill_list)

问题 1 - 我无法获得 game_content 的长度,因此我可以在循环遍历集合后停止循环。我可以用什么代替列表的确切索引计数,“while counter

问题 2 - 如何在我的 bill_list 中插入“账单”以便能够在最后打印。我只是使用 bill_list.append('bill') 代码来执行此操作,但我不太确定它是如何工作的以及为什么它不起作用。

对于糟糕的编码非常抱歉,我非常愿意接受更好的版本。

【问题讨论】:

    标签: python


    【解决方案1】:

    首先,您不必初始化变量以使用= 赋值。 所以user_input = str() 没用。接下来我将保留bill_list = '' 的赋值,因为+= 的赋值需要一个非空变量(空字符串不为空)。

    1) 要在列表中进行迭代,您可能最好使用 for 循环而不是 while 和函数,这更容易:

    bill_list = ''
    for scenario in game_content:
        user_input = input(scenario['day']).strip().upper()
        if user_input == scenario['answer1']:
            print(scenario['text1'])
            bill_list += 'bill'
        elif user_input == scenario['answer2']:
            print (scenario['text2'])
    

    在这个循环中,场景将取值 game_content[0] 然后是 game_content[1]

    2 ) 你最好使用操作数 '+' 来连接字符串,而不是像上次打印中那样使用数组:

    print("Your bill is: " + bill_list)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2020-03-13
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      相关资源
      最近更新 更多