How to write inline if statement for print in Python?
Answers
The print() function prints the specified message to the screen, or other standard output device.
The message can be a string, or any other object, the object will be converted into a string before written to the screen.
Syntax
print(object(s), separator=separator, end=end, file=file, flush=flush)
Parameter Values
In order to print an if statement in one line, we will have to use the '*'.
___________________________________________
The asterisk prints all the elements in one line and complies the print function. Even if it prints everything in online, we can always separate it with some other character or separate it with new line everytime.
___________________________________________
In order to compile them, in print(), we will either have to use () or []. I prefer the square brackets but both of them would work.
Here is how the base should look like:
print(*[ #your code goes in here ])
_____________________________________________
Now let's say that we have a list with the first 10 whole numbers and we want to print all the number above 6 from the list. But, it has to be in one line:
Here is how the format should look:
print(*[what you need to print, condition])
______________________________________________
CODE:
Numbers = [1,2,3,4,5,6,7,8,9,10]
print(*[x for x in Numbers if x > 5])
OUTPUT:
6 7 8 9 10
____________________________________________
If we want a comma separating them:
Numbers = [1,2,3,4,5,6,7,8,9,10]
print(*[x for x in Numbers if x > 5],sep = ',')
OUTPUT:
6,7,8,9,10
_____________________________________________