How to make a print() function that could print and argument OR another

3394 views python
6

I want to make the print statement randomly pick between 2 arguments, I tried using the OR within the brackets and I also tried using the OR outside the brackets with a new print() function --> (print() or print()), both of these methods print both the arguments at once, I tried to look for a different solution but I expected to use the random module for that problem, is there a way to use the OR within the print function itself?

if guess < number:
    print("This is a little bit low, try a bigger number" or "Number is too low")

if guess > number:
    print("This is kinda high try a smaller number" or "Try a smaller number")

answered question

1 Answer

6

or doesn't randomly select one of the arguments. It evaluates to the first truthful value (or the last value evaluated). If you want a random message, you can make an expression that chooses one using the ternary-if operator

from random import random
print("a message" if random() < 0.5 else "another message")

Better yet, the random module provides a choice function, which randomly chooses one element of a list.

from random import choice
messages = ['a message', 'another message', 'yet another']
print(choice(messages))

posted this

Have an answer?

JD

Please login first before posting an answer.