将随机数添加到变量中

时间:2016-08-20 15:30:43

标签: python random

我正在寻找像这样的输出

Computer Choice: 5
Total: 5
Continue? Yes or No
Computer Choice:2
Total: 7

每次创建随机数时都会累加。这是我试图开始工作的部分:

 if player_bet <= Player.total_money_amount:

    import random
    computer_choice = random.randint(1, 5) # Creates random number
    computer_total =+ computer_choice # Does not work. Also used += same result
    print('Computer choice: ', computer_choice)
                print('Total: ', computer_total)

      player_yes_or_no = input('Continue? Yes or No')
      if player_yes_or_no == 'Yes':
      pass

当前输出

Computer Choice: 5
Total: 5
Continue? Yes or No
Computer Choice: 2
Total: 2 

正如您所看到的那样,它不会添加创建的随机int。 如果我这样做+ =它会给出错误

编辑:我在

时获得相同的输出
 computer_total = 0
 computer_total += computer_choice

3 个答案:

答案 0 :(得分:0)

=+更改为+=。您目前拥有它的方式是将变量computer_total重新分配给computer_choice的值,而不是添加它们。另外,请确保在开始循环之前初始化computer_total

答案 1 :(得分:0)

请检查以下代码

#Added intilization.
import random
computer_choice = 0
computer_total = 0
for i in range(5): #Just added to make it running. You can add you checkings here

    computer_choice = random.randint(1, 5) 
    computer_total += computer_choice 
    print('Computer choice: ', computer_choice)
    print('Total: ', computer_total)
    #Changed input to raw_input
    player_yes_or_no = str(raw_input("Computer Choice - Yes or No ? "))
    if player_yes_or_no == 'Yes':
        next

输出:

C:\Users\dinesh_pundkar\Desktop>python demo.Py
('Computer choice: ', 2)
('Total: ', 2)
Computer Choice - Yes or No ? Yes
('Computer choice: ', 5)
('Total: ', 7)
Computer Choice - Yes or No ? Yes
('Computer choice: ', 2)
('Total: ', 9)
Computer Choice - Yes or No ? Yes
('Computer choice: ', 2)
('Total: ', 11)
Computer Choice - Yes or No ? Yes
('Computer choice: ', 2)
('Total: ', 13)

答案 2 :(得分:0)

您需要首先在循环外定义var sleep = time => new Promise(resolve => setTimeout(resolve, time)) var poll = (promiseFn, time) => promiseFn().then( sleep(time).then(() => poll(promiseFn, time))) // Greet the World every second poll(() => new Promise(() => console.log('Hello World!')), 1000) 才能使其正常工作:

computer_total

我把代码放在一个无限循环中进行测试。 请注意,我在循环外部导入随机,因此每次循环运行时都不会不必要地重新导入它。我还在import random computer_total= 0 while True: computer_choice = random.randint(1, 5) # Creates random number computer_total += computer_choice print('Computer choice: ', computer_choice) print('Total: ', computer_total) player_yes_or_no = input('Continue? Yes or No\n') if player_yes_or_no == 'Yes': pass 来电结束时添加了换行符。