0

So my code is basically simulating the at bats of a baseball player (Joe DiMaggio) in each game. This is the code so far

import random
i = random.randint(1, 100)
j = random.randint(1, 100)
k = random.randint(1, 100)
l = random.randint(1, 100)
while True:
    if i <= 32:
        i = 1
    else:
        i = 0
    if k <= 32:
        k = 1
    else:
        k = 0
    if j <= 32:
        j = 1
    else:
        j = 0
    if l <= 32:
        l = 1
    else:
        l = 0
    m = i+j+k+l
    print("He went", m, "-4")

I'm wondering if it would work with all of the different IF and ELSE statements. As well, when I try to run this, it highlights the m in the print statement with the error: Invalid Syntax.

Any help on how to fix this? Edit: The syntax error has been fixed, but now it only adds them up for the first time, the rest of the prints are all 4-4.

2 Answers 2

3

You need to fix your print statment:

print("He went", m, "-4")

or use string concatenation:

print("He went" + str(m) + "-4")

or string formatting:

print("He went {} -4".format(m))

Your code will then go into an infine loop recalculating the same value for m over and over again, as random values are not recalculated each time. i, j, k and l are static, they do not reference a function call they reference the return value of one call to random.randint() each.

You can simplify your code using a loop, which does recalculate m based on new random values each time:

m = sum(1 for i in range(4) if random.random() < 0.32)
Sign up to request clarification or add additional context in comments.

5 Comments

That fixed the syntax, but theres a new problem!
So would the m = sum(1 for i in range(4) if random.random() < 0.32 replace all the if and else statements?
Yes, it would, and the random.randint() calls too.
@user2557303: My sum does exactly what your code did; pick 1 32% of the time, 0 68% of the time, for each of four runs.
@user2557303: I use a float value in the range [0.0-1.0) (so 0 inclusive and 1.0 exclusive) instead of a integer value in the range [1-100], but the mathematics is the same. We are just cutting out a lot of unneeded extra code to turn the random.random() value into an integer range choice.
1

You have to use the concatenation operator.

print("He went " + str(m) + "-4")

Thus you are concatenating the output as a single string before you print it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.