简体   繁体   中英

50% Probability of multiple elements on Python

I'm trying to create a "football" game on python and if the user wants to pass the ball, my code is supposed to have a 50% probability of having an incomplete pass or a completion yielding between 3 and 15 yards

I know that to print the yardage, the code would look something like

import random
input("Enter r to run and p to pass")
p = print(random.randint(3,15))

but I'm not sure how to make "Incomplete" show up as a 50% probabilty

You can use the code below. As you have defined a statement to pick a random number between 3-15, you can create another statement to pick 0 or 1 (not %50 guaranteed). Also in your code, you are assigning return value of the print function to a parameter. This is definitely wrong! Print function returns nothing so assigning it to another variable is meaningless.

x = random.randint(0,1)
if x == 1:
    random.randint(3,15)
    
else:
    # incomplete pass

You could use something like this.

import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
    print(random.choice([random.randint(3,15),0]))
elif(inp == "r"):
    print("ran successfully")

This: random.choice([random.randint(3,15),0]) is the important bit. random.choice takes multiple values (in this case 2) in a list, and picks one randomly (2 values => 50% probability).

I also fixed the input output thing. To get input from the user you assign the value of input to a variable like this: example = input("Your input here: ") . If you ran that line of code, and answered with potato for instance, you'd be able to print example and get potato (or whatever the user answered) back.

If you'd like to really flesh your game out, I'd suggest looking into template strings. Those let you do wonderful things like this:

import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
    print(random.choice([f"Successfully passed the ball {random.randint(3,15)} yards","You tripped, the ball wasn't passed."]))
elif(inp == "r"):
    print("Ran successfully.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM