我尝试将for循环放在没有缩进的位置,并将函数放在代码的顶部
import random
num_roll_str = input('How many time you want to roll the dice? ')
num_roll = int(num_roll_str)
def roll_2_dice():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
return dice1, dice2
for i in range (1, num_roll):
print('{0:>10}{1:>10}{2:>10}'.format(i, dice1, dice2))
roll_2_dice()
答案 0 :(得分:1)
因为缩进很重要,并且return ...
保留了您所要使用的功能。
删除for循环的缩进,使其属于您的主代码而不是属于您的函数的 ),因为它在之后 return
)。
也将for i in range (1, num_roll):
更改为for i in range (1, num_roll+1):
-range
的上限是专有的,因此range(1,4)
会给您1,2,3:
import random
num_roll_str = input('How many time you want to roll the dice? ')
num_roll = int(num_roll_str)
def roll_2_dice():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
return dice1, dice2 # return is THE END, noting happens after it
for i in range (1, num_roll+1):
d1, d2 = roll_2_dice() # call your function and print it
print('{0:>10}{1:>10}{2:>10}'.format(i, d1, d2))
我将缩进固定为4个空格,请参见pep 008 guideline
Doku:
5的输出:
1 5 5
2 1 2
3 3 2
4 2 6
5 6 4
答案 1 :(得分:1)
您的代码中存在几个问题:
缩进问题
您定义了roll_2_dice
函数,但从未在程序中使用过。
如果您想掷骰子num_roll times
,则需要将range函数用作range(1,num_roll+1)
。
import random
num_roll_str = input('How many time you want to roll the dice? ')
num_roll = int(num_roll_str)
def roll_2_dice():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
return dice1, dice2
for i in range (1, num_roll+1):
dice1,dice2 = roll_2_dice()
print('{0:>10}{1:>10}{2:>10}'.format(i, dice1, dice2))