-2

I have tried placing the for loop without an indent as well as placing the function at the top of the code

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()
Adam Koch
  • 9
  • 2

2 Answers2

2

Because indentation matters and return ... leaves the function you are in.

Remove the indentation of your for loop so it belongs to your main code and not into your function )where it never would be executed because after return).

Also change for i in range (1, num_roll): to for i in range (1, num_roll+1): - the upper limit of range is exclusive so range(1,4) will give you 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))

I fixed the indentation to 4 spaces, see pep 008 guideline


Doku:


Output for 5:

          1         5         5
          2         1         2
          3         3         2
          4         2         6
          5         6         4
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    Instead of temp variables `d1, d2 = roll_2_dice()`, you can just call `print('{0:>10}{1:>10}{2:>10}'.format(i, *roll_2_dice()))`. – dyz May 05 '19 at 10:30
1

There are several problems in your code:

  • Indentation problem

  • You defined roll_2_dice function but never used it in your program.

  • If you wanna roll your dice num_roll times you need to use the range function as 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))
jukebox
  • 453
  • 2
  • 8
  • 24