Python Text Random

Asked 2 years ago, Updated 2 years ago, 16 views

import random

def one():

    print ("Mango")

candy = [one(), "Apple"]

for _ in range(3):

  choice = random.choice(candidate)

  print(choice)

I wrote it like this.

Mango

apple 

NULL

Or

Mango

NULL

NULL

Mango keeps popping up first and NULL pops up, so I wonder why!

I don't know the reason because I'm going to text randomly. I'd appreciate it if you could teach me.

python

2022-09-20 22:00

1 Answers

If you "run" this code, you'll get a "mango" out of nowhere, and nothing happens after that.

def one():
    print ("Mango")
candy = [one(), "Apple"]

How does that happen? From here, Python.Let's read the source from exe's point of view.

That's why it seems like "mango keeps popping up first."

What you want will be a return statement. If a function/method is supposed to K return, K is calculated only when the function is called and returned as the only return value. So it's convenient to assign that return value to a variable value, to put it into an element in an array, or to print().

Take a good look at the following code to see if it works as expected and what is crucially different from your code.

import random

def one():
    Return. "Mango"

candy = [one(), "Apple"]
for _ in range(3):
    choice = random.choice(candidate)
    print(choice)


2022-09-20 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.