-2

Can we use if-else keywords inside print()? For example: print(if age<=18:) or something like that.

alex
  • 10,900
  • 15
  • 70
  • 100
Unseen
  • 1
  • 1
    Do you want to conditionally call `print` or have whatever is printed be conditional? Please add some examples with your expected output for each case. – Jeppe Jul 17 '22 at 12:10
  • can you please explain a bit more cause i am newbie to python? – Unseen Jul 17 '22 at 12:11
  • ohh if you mean you need more examples then here they are – Unseen Jul 17 '22 at 12:12
  • Do you want to print something over a condition or the printed text having different things over different conditions? – adityanithariya Jul 17 '22 at 12:12
  • `num1=int(input("Enter 1st No.")) num2=int(input("Enter 2nd No.")) print( if num1<=10: print("Congo"))` i want to do something like that – Unseen Jul 17 '22 at 12:13
  • You want to print Congo when num1 is greater than 10? – adityanithariya Jul 17 '22 at 12:14
  • Edit your question and put the examples there. The two answers below show you the two possibilities. Either you only print, if some condition is met - or - you print, but whatever is printed is determined by a condition. In the latter you will always print something. – Jeppe Jul 17 '22 at 12:15
  • The `print-statement` tag makes no sense in Python 3. `print` hasn't been a statement at all since Python 2; it's a function now. – Charles Duffy Jul 17 '22 at 12:16
  • @CharlesDuffy This is a Python 3 question, but the dup target is a Python 2 question. (The answer's _basically_ the same, so I get why you dup-closed; just making sure you're aware.) – wizzwizz4 Jul 17 '22 at 12:18

3 Answers3

0

You can use expressions like so:

print("A Minor" if age < 18 else "An Adult")

You can't "not" run the print at all from inside the print.

For more info you can view this answer. Keep in mind that it's a little outdated and print() is a function in Python 3.

Bharel
  • 23,672
  • 5
  • 40
  • 80
0

you can simply write

if age<=18: print(age)
Haksell
  • 116
  • 4
  • like that's not what i am willing to accomplish. that was just an example. the thing i want to do is I am building a calculator and i have used 2 variables, and i am willing to use if condition in that like if user wants.......... Nevermind i just realised what i was trying to do doesnt make any sense – Unseen Jul 17 '22 at 12:20
0

You can write if outside the print:

if age <= 18:
    print(...)

This can be shortened to a single-line, though that can make for confusing code:

if age <= 18: print(...)

There's also an expression form of if, called a ternary expression. It requires an else, though.

print("young" if age <= 18 else "old")

You could also print the bool expression directly:

>>> age = 16
>>> print(age <= 18)
True
wizzwizz4
  • 6,140
  • 2
  • 26
  • 62