Python 当我的程序运行时,为什么输入后输出停止,即为什么我的代码没有完全运行
我尝试过在没有缩进的情况下放置for循环,以及在代码顶部放置函数Python 当我的程序运行时,为什么输入后输出停止,即为什么我的代码没有完全运行,python,Python,我尝试过在没有缩进的情况下放置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 f
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()
因为缩进很重要,和
返回…
离开了您所使用的函数
删除for循环的缩进,使其属于主代码,而不是函数),因为在返回之后,它将永远不会执行
同时将范围内i(1,num\u roll)的更改为范围内i(1,num\u roll+1)的。
-范围的上限是独占的,因此范围(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个空格,参见
Doku:
5年的产出:
1 5 5
2 1 2
3 3 2
4 2 6
5 6 4
您的代码中有几个问题:
- 压痕问题
- 您定义了
roll\u dice
函数,但从未在程序中使用它
- 如果你想掷骰子
num\u roll times
你需要使用range函数作为range(1,num\u roll+1)
随机导入
num_roll_str=input('您想掷骰子多少次?')
num\u roll=int(num\u roll\u str)
def roll_2_dice():
dice1=random.randint(1,6)
dice2=random.randint(1,6)
返回骰子1,骰子2
对于范围内的i(1,num_roll+1):
骰子1,骰子2=掷骰子2
打印({0:>10}{1:>10}{2:>10})。格式(i,dice1,dice2))
您可以调用print({0:>10}{1:>10}{2:>10})。而不是临时变量d1,d2=roll_2_dice()
。format(i,*roll_2_dice())
。