ally1637
ally1637

Reputation: 1

How to return properly?

I am having trouble returning the answer properly.

Is the return roll_dice(x) syntax correct, or do I need to replace x with something else in the parentheses?

I am a beginner and would like some help with this problem:

My code:

import numpy as np

def roll_dice(x):
    totmoney = 0

    for a in range(x):
        throw_one = np.random.randint(6)
        throw_two = np.random.randint(6)

        if throw_one % 2 != 0 or throw_two % 2 != 0:
            totmoney += throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney
        else:
            totmoney -= throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney

        return roll_dice(x)

Upvotes: 0

Views: 81

Answers (1)

EvensF
EvensF

Reputation: 1610

Without doing too much modifications, I think what you wanted to do is:

import random

def roll_dice(x):
    totmoney = 0
    result_matrix = []

    for a in range(x):
        throw_one = random.randint(1, 6)
        throw_two = random.randint(1, 6)

        if throw_one % 2 != 0 or throw_two % 2 != 0:
            totmoney += throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney
        else:
            totmoney -= throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney

        result_matrix.append([throw_one, throw_two, totmoney])

    return result_matrix

example = roll_dice(2)
print example

(I have used the random module because I don't have numpy installed)

You create the matrix one row at a time each time you go through the loop and at the end this matrix is what you return.

But I would add some additional modifications:

import random

def roll_dice(x):
    totmoney = 0
    result_matrix = []

    for a in range(x):
        throws = [random.randint(1, 6), random.randint(1, 6)]

        if throws[0] % 2 != 0 or throws[1] % 2 != 0:
            totmoney += sum(throws)
        else:
            totmoney -= sum(throws)

        print throws[0],"|",throws[1],"|",totmoney

        result_matrix.append([throws[0], throws[1], totmoney])

    return result_matrix

example = roll_dice(2)
print example

Here's what I have put in place:

  • I have put your two throws into a list named throws
  • I have used the sum function to add these two throws
  • I have put your print statement outside of your if statement

We could go much further, but I'm getting tired and I don't want to confuse you with more advanced stuff.

Upvotes: 1

Related Questions