Python Statements with Examples

Instruction that a Python interpreter can execute is a statement. Difficult to grasp?

Let’s get to bottom of it! Remember a few Python codes we went through in the previous blogs? Let me help you remind those.

We started learning Python by printing this “Hello World” code.

print("Hello World")

"""
Output: 

Hello World!
"""

And recently, we saw a code to mock up a traffic signal.

signal = "Red"

if signal is "Green" :
     print("Proceed")
else :
     print("Stop")

"""
output:

Stop

"""

Simply put, we can say anything written in Python is a statement. Python statement ends with the token NEWLINE character (i.e., the way we go to a new line by pressing enter in the document)

#In the print Hello World code 

print("Hello World") #← is the statement.

"""
Output:

Hello World

"""
#In the print Hello World twice
print("Hello World") print("Hello World Again")

"""
Output:

File "<ipython-input-4-f94c7ef532ae>", line 2
    print("Hello World" end = "x") print("Hello World Again")
                          ^
SyntaxError: invalid syntax

"""

In above example, two statements in a single line is giving error because this is not right as a statement (i.e print statement). print statements should end with NEWLINE (i.e \n) which is not happening here, hence invalid syntax.

To correct this, we have to tell Python interpreter explicitly that this is end of one statement. Otherwise it will throw syntax. Semi colons are the way to tell interpreter about end of statements.

Let’s see one example!

#In the print Hello World twice

print("Hello World"); print("Hello World Again")

"""
output:

Hello World
Hello World Again

"""

the above example works because we are instructing Python to consider multiple statements by mentioning semicolon (;), which ends each individual statement. 😀

#In the print Hello World in the new line

print("Hello World");
print("Hello World Again")

"""
output:

Hello World
Hello World Again

"""

The above statement works as well. The semicolon tells Python interpreter that this is end of one statement and it goes to next line with default Newline character and executes the second statement also successfully.

signal = "Green" # ← Statement to assign value “Green” to variable call “signal”

if signal is "Green" : # ← Another statement in the NEWLINE where we are checking if the value of the signal is “Green” or not.
   print("Proceed") # ← New statement which gets executed when your if the condition is true. This means the signal is Green.
else :
   print("Stop")

"""
output:

Proceed

"""

Python code runs from a statement by statement, i.e., first signal = “Green” will run, and if that is executed without any errors (i.e. mistakes), then 2nd statement if signal is “Green” : will run like wise Python will run each statement separately till the end OR until it hits a syntax error

 

Now that we know Python statements are executed statement by statement, there are a couple of things that we need to be clear about.

  1. While it is true that every line in Python is a statement, but it is not necessary that multi-lines can’t be single statement. (We have covered this concept in this blog. Make sure to read till the end.).
  2. It is not necessary that each line can only be one python statement. See the code below:
# two statements in a single line

l = 10; b = 5  #There are two assignment statements in a single line separated by ';' , where ';' denotes the end of first statement .

# Below statement uses a different output formatting to print the Area of rectanngle 
print('Area of rectangle:', l * b)


"""
output:

# Output Area of rectangle: 50
Area of rectangle: 50

"""

Here what you see in the second line, there are two variables (l and b) with value (10, 5). These are two statements in single line. Likewise there can be multiple statements in one line also.

We will know more about variable in further blogs, need not to focus on variable as of now.

As we know now Python code runs line by line, if there is any error any statement (code) then Python program will stopping running.

print(1)
print(aa)  # Variable "aa" is not defined at this point
aa = 2


"""
output:

1
---------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-2-19ff440f6c35> in <module>
      1 print(1)
----> 2 print(aa) # Variable "aa" is not defined at this point
      3 aa = 2


NameError: name 'aa' is not defined

"""

In the above code there is an error in second line, so Python program stops running and doesn’t look for aa’s value in the third line.

Multi-Line Statements:

As it was mentioned earlier, that multi-lines can also be single Python statement. Let’s understand with few examples!

Explicit continuation

Line continuation character (“\” ) can be used to extend the statements over multiple lines. This is known as explicit continuation .

Python statements are going to lengthy most of the times and to improve readabilty of statements, a good convention is to use multi-lines.

Let’s understand it with one example! so we have to add many numbers and assign results to one variable called add.

# We are adding some number and assigned that to a variable add.


add = 5 + 5 + 10 + 10 + 20 + 20 + 20 + 30 + 30 + 30 + 30

in such cases readability is one problem that programmers face. Suppose if there are 10 more number like this. Would be a little problem, right?

To tackle that we use multi-lines to improve readability like the next code-

add =  5 + 5 +      #We are typing rest of this to next line so it is easy to read the same previous numbers.
      10 + 10 +
      20 + 20 + 20 +
      30 + 30 + 30 + 30

print(add)

"""
output:

  File "<ipython-input-1-8c26da27048b>", line 1
     add = 5 + 5 +                  
                 ^SyntaxError: invalid syntax

"""

Oops!! It is giving invalid syntax error here. Why??

The reason is python interprets things line by line and when it reaches to the end of the line it sees no number after + operator and because of this program breaks out by giving this error.

Let’s try another scenerio where we put a number after the operator, like this:

add = 5 + 5             #We are typing rest of this to next line so it is easy to read the same previous numbers.
        + 10 + 10
        + 20 + 20 + 20
        +30 + 30 + 30 + 30

print(add)

"""
output:

File "<ipython-input-2-aad9fcfff5fd>", line 2   
       + 10 + 10
       ^ IndentationError: unexpected indent

In the above case, Python interpreter is fine with first line but and moves to the second line. Now the error is, it is expecting some data before + operator.

Again it is confused and breaks out.

To take the previous issues and write longer codes in multiple lines, we use \ backward slash.

let’s try the same things again!

#added "\" at the end of first line.


add = 5 + 5 + \
        10 + 10 + 
          20 + 20 + 20 + 
            30 + 30 + 30 + 30


print(add)


"""
output:

File "<ipython-input-9-a683998927ac>", line 5
    10 + 10 +
              ^
SyntaxError: invalid syntax\

"""

Ah! Not AGAIN!!

Still not working? It is still throwing error because interpreter is good with first line as soon as it sees line continuation character. It goes to next line and is ok till the end of second line.

Here comes the problem! It is again expecting some number after + operator, it doesn’t find any number and breaks out of program with this error.

Now I hope we can resolve the problem!

#added "\" at the end of every line.

add = 5 + 5 + \
        10 + 10 + \
          20 + 20 + 20 + \
            30 + 30 + 30 + 30

print(add)

"""
output:

210

"""

Pheww!! Finally, it is working.

If you can see the above program is more readable compare to if everything was in a single line.

What exactly happens here is Python starts executing the first line and when it reach to end of first line, it sees backward slash (which is a line continuation character, it tells interpreter to go to the next line to continue. Same happens in second and third line as well.

Ultimately this is one Python statement spread across four lines of code. This is why it was mentioned that while it is true that every line in Python is a statement, but it is not necessary that multi-lines can’t be single statement.

Implicit continuation:

In the last example we saw how to write one statement in multiple lines for better readability using line continuation character. There is another way to do it.

Let’s try that on the same example!

Parentheses “( ) “ , can we used for addition of a continuation statement inside it . Anything written under it , will be considered as a single statement even though it may be placed on multiple lines.

add =  ( 5 + 5 + 
           10 + 10 + 
           20 + 20 + 20 )

print(add)

"""
output:

90

"""

In above statement we have used parentheses in the statement. When Program is being executed at beginning of the first line python interpreter sees parentheses, now python know this statement will end on closing parentheses.

This reduce our work of putting “\” at the end of every line. We can put the whole statement in parantheses.

Similiarly , list and dictonary can also be written in the similiar fashion for better readability .

“Our intent is not to go into details of lists and dictionaries for now. You can simply focus on comments of next few examples as we are just focusing on statement.”

#Below list is defined using  [ ] bracket , where every item is mentioned in a new line for better readability.

ListOfNames = [ 'Paul' ,
               'Anusha' ,
               'Murali' ,
               'Aman' ]

print("The list = ", ListOfNames)

#Below dictionary is define using { } , where every key-value pair is mentioned in a new line for better readability.

DictOfNames = { 1 : 'Paul' ,
               2 : 'Anusha' ,
               3 : 'Murali' ,
               4 : 'Aman' }

print("The Dictionary : ", DictOfNames)

"""
output:

The list =  ['Paul', 'Anusha', 'Murali', 'Aman']
The Dictionary :  {1: 'Paul', 2: 'Anusha', 3: 'Murali', 4: 'Aman'}

"""

Python Compound Statements (Block of Code)

Compound statements contain (groups of) other statements. The compound statement includes the conditional, loop, exception handling and function related statement.

We need not understand loops, conditional statements and functions as of now. We are trying to understand statements, so you can focus on the comments in the next examples.

Control Statement

  • if
  • if-else
  • if-else (nested)

Loop Statement

  • for
  • for (nested)
  • while

Function Statement

  • function

Exception Handling Statement

  • try, except

IF-ELSE

 

# The statement inside the if block is executed if the condition is True , 
# otherwise the statement inside the else block is executed .

age = 19
if (age>= 19 ):
  print("Eligible to vote")  # Current line gets executed if above condition is True
  print("Please do vote. It counts") # This statement and above statement are block of code
else :
  print("Not Eligibile") # If the if condition is false this line is executed

"""
output:

Eligible to vote

"""

 

IF-ELSE (NESTED)

 

mark = 56

if (mark > 80) : 
  print('Top') # Current line gets executed if above condition is True
elif (mark >= 40 and mark <= 80) :
  print('Average') # Current line gets executed if above condition is True
else :
  print('Fail') #if all conditions are False this line is executed

"""
output:

Average

"""

 

FOR

 

# The loop is iterated till the end item of the iterable 

ListOfNames = [ 'Paul' ,
               'Anusha' ,
               'Murali' ,
               'Aman' ]

for name in ListOfNames :
  print(name)               #it prints all the items in the list

"""
output:

Paul
Anusha
Murali
Aman

"""

 

FOR (NESTED)

 

for x in range(0,5):        # iteration statement 1 
  for y in range(x):        # iteration statement 2
    print("#"*y)

"""
output:

#

#
##

#
##
###

"""

 

FUNCTION

 

def add(n1,n2):
  return (n1+n2)  # functions returns the addition of two numbers when called

add(5,4) # function

"""
output:

9

"""