Raghav
Raghav

Reputation: 19

Meaning of a statement

I want to understand the meaning of the following line in the code mentioned below: (As in how to read that line?)

print('#%*s' % (a, '#') if a else '')

From this code:

lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
    print('#%*s' % (a, '#') if a else '')

Upvotes: 0

Views: 78

Answers (2)

Óscar López
Óscar López

Reputation: 236014

This is a conditional expression:

'#%*s' % (a, '#') if a else ''

Read it like this: if the variable a is not null and not empty format it, else the expression evaluates to the empty string ''. Now for the format part (which uses the old % syntax):

'#%*s' % (a, '#')

It says: print an #, then a number of spaces and finally one last # character. The * gets substituted with the value of a and then the format string is applied to the # character For example, if a = 5 the above expression will evaluate to this:

'#%5s' % '#'

Which we can print and see the result:

print('#%5s' % '#')
#    #

Notice that the % syntax is deprecated, in modern Python the recommendation is to use str.format or even better, f-strings for Python 3.6+.

Upvotes: 2

Kampi
Kampi

Reputation: 1891

You can see some string formatting examples here. So your formatting does something like:

Format the output (your #) as a string and place an additional # at the end of the line. Fill the line with so many spaces that the line has a total length of a. If a is zero and so the if statement is FALSE print and empty line.

Enter number of lines for pattern: 9

##
# #
#  #
#   #
#    #
#     #
#      #
#       #

A modern solution for the same output would be looking like this:

lines = int(input("Enter number of lines for pattern: "))
for a in range(lines):
   print(("{:" + str(a) + "}{}").format("#", "#") if a else "")

Upvotes: 0

Related Questions