Python Object-Oriented Programming(OOP)

python oop

Python OOP

In this article we will go through the Python OOP Concepts. OOP is termed as Object Oriented Programming and it is distinguished based on various concepts such as objects, class and methods etc. There is one more type of language exists called as
Procedural Oriented Programing language(POP). You probably heard that most of
the expert started their career with C- language and this is a procedural Oriented Programming. 

There are many limitations and complexity with POP hence the new concept originated – Object Oriented Programming language(OOP) with its various useful features. OOP languages are very famous and used in almost all existing popular languages, also it is getting considered for new languages which are currently under development. 

The major need for developing such languages was to manage the ever-increasing size and complexity of programs.

Now question is, why OOP languages are so popular and why everybody liked to acquire those concepts. You will get to know in-and-out about OOPs features in this article – stay tuned!!

Python is an Object-Oriented Programming Language and here we will discuss OOPs concept by taking reference of simple python programs. Don’t worry, if you do not know Python.  It is not necessary to know python in advance to understand OOPs concept in general or OPPs with Python.

PYTHON OOP : Basic Concept

Any complex language starts with the simple concept irrespective of complexities
involved in that areas. There are few simple python OOP features but it is base of python programming models.

Python OOP features

1.  Class

2.     Object

3.     Abstraction

4.     Polymorphism

5.     Inheritance

6.     Encapsulation

Class

In simple
way, class is a grouping of data and its associated functions. Once a class has
been defined, we can create any number of objects associated with that class.

For example, Account_Number, Balance, Credit() and Debit() are the member of Class Bank. If Bank has been defined as a class, then the statement Bank-Balance , will create an object Balance belonging to the class Bank.

[table id=6 /]

Object

Object is an
instance of a class. In other words, Object is a way to access features of a
class. As described above a class contains the associated data and its function
but to access its features Objects play major role. 

Consider class
– Bank from above example and try to understand the power of object. You
already have defined class- Bank with associated data and functions to perform
credit and debit operations. The normal operation happening in bank system is
account holder debit some money from account or credit some money into account. 

Assume,
customer 1 has defined cust1 as an object of class Bank and customer 2 has
defined cust2 as an object of same class Bank.

Let’s try to credit some amount into customer 1’s account and debit some amount from customer 2’s account by accessing features of Class Bank through objects cust1 and cust2 respectively.

 
# Credit 1000 in customer-1 account
cust1.credit(1000)
# Debit 500 from customer-2 account
cust2.debit(500)

Abstraction

An abstraction is very important aspect to hide complexity or internal background
processes and represent essential features. To understand this concept more
clearly, take the same example of class Bank. 

In first two points, we have already seen credit and debit example while describing class and object. Observe those examples, you are just calling function by pointing
out correct class object with value. In this process you need not to know what is
happening inside when you are calling credit or debit functions. How and What process happening inside is hidden from you. 

This is
abstraction, where you only know the essential things to operate on banking
system without knowing the background details of actual complex calculations.

It gives flexibility
and simplicity to the users to use complex application knowing minimal required
things to operate on.

Polymorphism

In simple
words, A single function name can be used to handle different operations by
passing necessary arguments. This is something similar to a particular word
having several different meanings depending upon the context. 

For example,
you have a class shape, and you have to draw the shapes. But they draw
differently. Here, the “draw” behavior is polymorphic in the sense
and depends on the shape. So, the abstract “shape” concept does not
actually “draw”, but specific shapes (like circle or rectangle) have
a concrete implementation of the action “draw”.

PS-Function overloading is not supported in Python OOP.

Polymorphism
plays an important role in allowing objects having different internal
structures to share the same external interface. Polymorphism is extensively
used in implementing inheritance.

Inheritance

Inheritance
is the process of creating new class based on an existing class. In other words,
it is the process by which objects of one class acquired the properties of
objects of another classes. It supports the concept of hierarchical
classification.

The one whose properties are acquired is known as a base class or parent class and the new class is known as a derived class or child class.

Inheritance can be easily described with class computer. In the computer class we have defined all its accessories and features. Another class created for – Laptop by
inheriting its properties from class computer. In this case, Computer is the base or parent class and Laptop is the derived or child class.

Encapsulation

Encapsulation
is also an important feature of object-oriented programming language. The
wrapping up of data and function into a single unit (called class) known as
encapsulation. If you are creating class, you are doing encapsulation.

The data abstraction and encapsulation go hand-in-hand. An abstraction is used to hide internal details and show only functionalities, it can be only achieved through
encapsulation.

Photo Credits: Pixeles

Python Function Arguments

python function arguments

In python, you can define a generic function which can be used by passing arguments or parameters. Even we use built-in functions by passing its required arguments.

You might have seen print() function used since our first article where we have passed character string to print() function to print “Hello World” message.

Arguments

In python function topic, we have learned about how to define functions and calling it. In this article we will see what complications can encounters with python function if we don’t provide proper parameters to the function. Also, we will go through different types of function arguments.

Here is the simple example.

 
# Define python function
def Name(FirstName, LastName):
    print("First Name :", FirstName)
    print("Last Name :", LastName)
# Call python function with arguments
Name("Tekkie", "Head")

Output


>>> Name("Tekkie", "Head")
First Name : Tekkie
Last Name : Head
>>>

Observe this example carefully where we have provided all the required arguments while calling the Name() function. Let’s see what happens if we provide only one argument where we actually required two arguments.


 >>> Name("Tekkie")
Traceback (most recent call last):
  File "", line 1, in 
    Name("Tekkie")
TypeError: Name() missing 1 required positional argument: 'LastName'
>>>

Or try to call Name() function without any argument.


>>> Name()
Traceback (most recent call last):
  File "", line 1, in 
    Name()
TypeError: Name() missing 2 required positional arguments: 'FirstName' and 'LastName'

There are mainly four types of function arguments in python.

1. Python Required Arguments

In this type of argument, you need to provide same number of arguments which are necessary for that function and with its exact datatypes. 

Observe this example where addition() function expect two numeric arguments and see what happens with different test cases.

 
# Define function
def addition(a,b):
    result=a+b
    print("Addition result :", result)

Tast Cases & its Result:

addition()

TypeError: addition() missing 2 required positional arguments: ‘a’ and ‘b’

>>>

addition(10, “Character_String”)

result=a+b

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

>>>

addition(10, 20)

Addition result : 30

>>> 

2. Python Default Arguments

In this type of argument, the parameter values are exactly mapped one-to-one to the variables in the function.

Here is an example of default argument type where we have defined default value for variable – b and passing the value for variable – a. Also observe, what happens if you still provide value for variable – a which you have already defined.

 
# Define function
def addition(a,b=0):
    result=a+b
    print("Addition result :", result)

addition(10)

Addition result : 10

>>>

addition(10, 20)

Addition result : 30

>>>

In case-1, you have just provided one argument which are mapped to first variable –  a and default specified value taken for variable b    (i.e. b=0), hence we got result, 10+0=10

In case-2, we have tried to pass two arguments. first argument mapped to first variable (i.e. a) likewise second argument mapped to second variable (i.e. b) by overwriting its default value zero. Hence we got addition result, 10+20=30

You need to very careful when you define some value for variable in function but at the same time trying to pass value for same variable while calling the function.

3. PYTHON Keyword ARGUMENTS

As discussed in the first two argument types, when we call function with values, these values get assigned to the arguments according to its variable position.

In above example first value always assigned to first variable – a and second value assigned to second variable – b.

Python gives you flexibility to assign values for arguments by specifying its variable name. You could call this function as addition(a=10, b=20) or addition(b=20, a=10). In both the cases you will get the same results.

 
def addition(a,b):
    result=a+b
    print("Addition result :", result)

addition(a=10, b=20)

Addition result : 30

>>>

addition(b=20, a=10)

Addition result : 30

>>>

Also, there is possibility to call function in a mixed way – passing default arguments along with keyword arguments but here you need to keep in mind one important rule.

Rule: When you are calling a function, you must provide all the positional(default) arguments first, then you can pass keyword arguments.

Having a positional (default) arguments after keyword arguments can result into an error. Here are few examples.

addition(10, b=20)

>>> addition(10, b=20)

Addition result : 30

>>>

addition(b=10, 20)

>>> addition(b=10, 20)

SyntaxError: positional argument follows keyword argument

>>>

Here is one very interesting scenario – In case if you attempt multiple arguments refer to same variable then it will result into an error.

addition(10, a=20)

Traceback (most recent call last):

  File “<pyshell#15>”, line 1, in

  addition(10, a=20)

TypeError: addition() got multiple values for argument ‘a’

Here, you have already provided value for variable – a by passing position argument (10) but still you have provided value for variable- a again through keyword argument (a=20) and it ends up with an error.


 

4. Variable Length or Arbitrary Arguments

If you are not sure how many argument values to be passed to the function, then these arbitrary arguments come in picture by defining its variable argument length.

Mostly such type of argument used where we are passing values from outside to the loop statements.

The asterisk * used with variable name (*a) to decide its variable argument length.


def addition(*a):
    sum=0
    for var in a:
        sum=sum+var
    print("Addition Result :", sum)
# call function
addition(10,20,30,15,20)

Output


Addition Result : 95
>>>

In this example we have called function with multiple arguments.  These argument gets wrapped into tuple and values gets assigned to it. Inside function we have used for loop to retrieve those arguments back.

An example which describes combination of default argument and arbitrary argument.


def addition(b, *a):
    sum=0
    for var in a:
        sum=sum+var
    print("Addition Result :", sum)
    print("Value of variable b :", b)
# call function
addition(10,20,30,15,20)

Above program gives following result – 


Addition Result : 85
Value of variable b : 10
>>>

Here, we have assigned value 10 for variable – b and rest arguments are assigned for variable – a and it retrieved back further with for – loop, hence we got the final result – 85

Python Define Functions

python define function

What are Python Functions?

In the python programming context, function is a named collection of python statements combined together to perform specific task. Python def keyword is used to define the function in python. It is a package of generic python code which you can be used whenever required in your code.

There are many built in functions available in the python. Also, there are possibility to create new customised, user written functions in python using python def keyword.

Built-in Function

Python built-in functions are already predefined into python standard library hence you don’t need to import any modules to use built-in functions.

You have already seen many python functions since my first article –What is python? Starting from basic program to print “Hello World” to more complicated and lengthy codes. You might have written “print” statement thousands of time, but did you ever wonder how print – statement works?

Similarly, there are other functions we use regularly such as – input, eval, int, float, range, and type. These are the common built-in functions included in the python standard library hence can be available at any time. 

Apart from this we do have many other built in functions in python but to use those functions you need to import related modules in the beginning of your code.

Use defined function

The function we define /creates by ourselves to perform any specific task known as user defined function. Python def keyword is used to define user defined functions.

The whole concept of functions revolves around two things – first, how you define / write your function and second, how and where you call that function by supplying necessary parameters to the function.

Syntax:

 
#define your python function (python def Keyword)
def FunctionName(parameters) 
	. . . . . . . . . 
	. . . . . . . . .
#call python function
def FunctionName(parameters)

Try to understand simple python function – show() to display some predefined text message whenever this function gets called in the code.

 
#define show() function
def show():
    print("Show function executed")
#call show() function
show()



Python_Functions.py


Show function executed
>>>

Output

Observe this example – show() is your user defined/created function but inside show() function we are calling built-in print() function. 

Now we know when we call show function, it will execute lines of code written inside the function. In a similar way, when we are calling print() function – some sort of python code executes which is available in the python standard library. 

There are many generic codes already written in python and imported into python standard library. In function irrespective of its types- either built-in or user defined, there are some rules needs to be followed as per logic written inside that function in ordered to reuse the code.

Example:

Python Function to add two numbers

This example demonstrates simple python function to add two numbers by taking inputs from user.

 
#definefun function - add()
def add(a,b):
    result=a+b
    print("Addition of two numbers :", result)
#take input from user
a=int(input("Enter First Number :"))
b=int(input("Enter Second Number :"))    
#call add() function to perform addition.
add(a,b)

Python_add.py


Show function executed
Enter First Number :25
Enter Second Number :100
Addition of two numbers : 125
>>> 

Output

Python try except and finally

Python try except and finally - exceptional handling

An exception is a very known to every programmer! Afterall we most of the time seems to be playing with this keyword. Python try except and finally statements allow you to handle these exceptions.

Python exception or error doesn’t indicate that there is always something wrong with the logic or algorithm. 

There are some circumstances where your program is absolutely correct, still you encounter run-time error that situation is known as an EXCEPTION.

At this point, our run time errors resulted in a termination of program execution. Rather terminating the program execution, program could detect the error before hand and handle it in a very smart way, that concept is called as Exceptional handling.

An Exceptional handling is a standard python mechanism allows programmers to deal with the run-time errors. 

Examples of exceptional errors: integer division by zero, attempting to convert a non-number to an integer, accessing a list with an out-of-range index, and using an object reference set to None.

Few common python exceptions are described here but if you want to go through all the exception list then visit this page Python built-in Exception.

PYTHON EXCEPTIONS

1. ZeroDivisionError: division by zero

You have a program where you are doing some calculations. You have defined two integer variables and assigned value to them. Now you are trying to attempt division operation.

N1=int(input(“Enter first Number – N1 :”))

N2=int(input(“Enter Second Number – N2 :”))

Result=N1/N2

print(“Result :”, Result)

Your code is absolutely perfect, and it will give you division answer but what will happen if user enters 0 value for variable N2! Always remember, you never have a control over an end user. 

In this case program execution will be terminated with error – ZeroDivisionError: division by zero

Output

Enter first Number – N1 :100

Enter Second Number – N2 :0

Traceback (most recent call last):

File “C:/Users/Python37/exceptional_handling.py”, line 3, in

Result=N1/N2

ZeroDivisionError: division by zero

>>>

2. ValueError: invalid
literal for int()

To continues with same above example where you expect user should enter integer number(digits) but consider user has entered some random characters or numbers in a word (say five instead of 5) for variable N1 then WHAT? It will throw this exception – ValueError: invalid literal for int()

Enter first Number – N1 :five

Traceback (most recent call last):

  File “C:/Users/Python37/exceptional_handling.py”, line 1, in <module>

    N1=int(input(“Enter first Number – N1 :”))

ValueError: invalid literal for int() with base 10: ‘five’

>>> 

3. OverflowError:
integer division result too large for a float

To continues with the same example, now user has entered very large number for variable N1. Observe what happened with your result – error  OverflowError: integer division result too large for a float

python exception handling OverflowError

Looking for Solution?

Yes, it is absolutely possible to write a code to avoid such kind of errors in python like other programming languages, but python has unique features which you can apply.

Python has built in conditional execution structure to handle the situation where you might encounter expected or unexpected run-time errors.

1.    Try

2.    Except

3.    Else

4.    Finally

Python Try and except

try/except block to be added where you think potential exception can occur in your program. 

Syntax:

try:

                  #It contains code that might raise an exception.

except:

                  #It contains code to execute Only when try block raise an exception.

Back to our previous example and we will see how it works. Now you know where possible exception error can come in our example so try to add try/except block into it.

Firstly, we will try display text message to the user so they can understand what went wrong! The technical error user might not understand so let’s change default error message with simple plain English text.

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

except OverflowError:

    print(“Oops-ERROR!! Result value seems to be too large to display”)

print(“Program execution continues….”)

Scenario #1

Enter first Number – N1 :five

Oops!! Seems you have entered invalid Number

Program execution continues….

>>> 

Scenario #2

python try except exception handling

Summary

  • Program execution doesn’t terminate when you use try except block and exception occurs.
  • An except block doesn’t execute unless try block don’t raise an exception.
  • Multiple except block can be written for one try block.

Python else

If try block raise an exception, then only except block gets executed otherwise else block will be executed.

In other words, else block only executed when try block do not raise an exception.

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

else:

print(“Division Successful!”)

print(“Program execution continues….”)

Python finally

finally block always executes after try/except block execution. It does nothing extraordinary, just creates the space for you to execute something after try/except block.

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

finally:

print(“Executing finally…block!”)

print(“Program execution continues….”)

So far, we have seen basic use of try/except, else and finally block in python. Mostly it is being used with the conditional loop statements and allow users to try one more time – with proper message on screen when they enter wrong values, for instance.

Example

Write a program to demonstrate an
exceptional handling case with Loop statements!

In this example users can input any small integer value less than 100. They can enter number greater than 100 to complete the program execution. This code will not fail or terminate the execution if try block raise ValueError exception.

x = 0

while x < 100:

    try:

    # I hope the user enters a valid Python integer!

        x = int(input(“Please enter small integer Number: “))

        print(“x =”, x)

    except ValueError:

        print(“Oops!! Input cannot be parsed as an integer – Please try again”)

print(“Program finished”)

 

Output

Please enter small integer Number: 25

x = 25

Please enter small integer Number: 50

x = 50

Please enter small integer Number: five

Oops!! Input cannot be parsed as an integer – Please try again

Please enter small integer Number: 5

x = 5

Please enter small integer Number: 200

x = 200

Program finished

>>> 

 

Read More: Python raise Keyword

Python raise keyword

python raise keyword

Python raise keyword. In python we can raise exception by using raise keyword. We have already gone through detailed overview on in-built Python exceptions and how it is being handled with python try except & finally statements.

All these exceptions are default and python interpreter decide when to raise the exception but WHAT if you want to raise an exception?

Python raise

Python gives your flexibility to raise exception whenever you want in the program. It is very powerful keyword and having unique features in it.

Mostly people are using python raise – keyword in conditional block to decide when and where to raise an exception.

Syntax:

raise  <exception>

When you specify raise keyword in your code and the moment program execution reaches that point – immediately exception is being raised by skipping further statements. 

An interpreter doesn’t see, whether do you really have an error in your code or not. It simply raises an exception as per specified exception name.

Example

Python_raise.py

var=10

print(“Var= “, var)

raise ValueError 

print(“Program execution continues….”)

Output:

Var=  10

Traceback (most recent call last):

  File “C:/Users/Documents/Python_raise.py”, line 3, in <module>

    raise ValueError

ValueError

>>> 

Python raise keyword most often used in try block for various reasons for instance, to cross verify whether exceptions are properly getting raised and check its execution flow, to avoid the program execution termination, etc.

python_raise.py

try:

    var=10

    print(“Var= “, var)

    raise ValueError

except ValueError:

    print(“Oops!! Value error raised “)  

print(“Program execution continues….”)

 

Output

Var=  10

Oops!! Value error raised

Program execution continues….

Use raise keyword in try except

It is very effective way to check whether your exceptional handling code – try/except block working properly without involving end user. 

If there would be chances of an exception can occur in your code where you already applied, try/except blocks but you want to test it then you can add raise keyword there.

Observe this example – We are performing division of two numbers by taking inputs from users.

In this case we know ValueError exception can occur if user enter non-digit number. We have already seen this example here.

Now we could test this exception by raising ValueError exception manually in the code, irrespective of user inputs. 

Python_raise.py

try:

    N1=int(input(“Enter first Number – N1 :”))

    N2=int(input(“Enter Second Number – N2 :”))

    Result=N1/N2

    print(“Result :”, Result)

    raise ValueError

except ValueError:

    print(“Oops!! Seems you have entered invalid Number”)

print(“Program execution continues….”)

Note this result – we have entered correct input values still ValueError exception encountered due to raise keyword specified in try block code.

Output

Enter first Number – N1 :100

Enter Second Number – N2 :12

Result : 8.333333333333334

Oops!! Seems you have entered invalid Number

Program execution continues….

>>> 

 

Read More: Python try except and finally

Python Exception and Errors

Python Exception and error

python error & built-in exceptions

There are many built-in python exception an interpreter raises whenever the extraordinary situation encounters in the program. 

People often gets confused with error and exception as both looks very similar but these two operates in a very different way.

Python Error

Error encounters in the program when something wrong with the code. In error situation, program execution gets terminated and there is no way to handle this case unless you don’t fix the error.

Most common error observed with programmer is – syntax error. Observe this example to understand how error looks like in python.

This example demonstrates syntax error with if statement. You can see, semicolon is missing in if statement.

var=100

if var>10

    print (“Variable – var=”, var)

  File “C:/Users/Documents/Python_raise.py”, line 2

    if var>10

            ^

SyntaxError: invalid syntax

Python built-in Exceptions

The built-in exceptions are raised by interpreter or built-in functions whenever an extraordinary error situation occur in the code. 

When an exception encounter in your code, program execution will get terminated unless you don’t handle specific situation in your code. HOW to handle an exception? Visit this page – Python try/except and finally Statements.

There is also possibility to raise built-in exception manually by using raise keyword. Visit this page to learn more about Python raise keyword.

[table id=1 /]

Read More : Python try except and finally statements.

Python IF ELSE Code Write in One Line

python if else one line code

 

There are many people like you very curious to know how to write simple one liner Python IF ELSE statements. Because of indentation in Python space has its own value and one extra space can crash your program.

To make your lengthy code looks short and easy human understandable you can write IF-ELSE in one line too.

python if-else statements

Observe the syntax specified in this example. You can’t re-arrange anything, not even single space! This is ordinary Python if-else statements.

age=int(input(“Enter your age:”))

print(“Your age is “, age)

if age>18:

    print(“You are eligible to vote”)

else:

    print(“You are NOT eligible to vote”)

If Else in one line!

Let’s try to put all IF-ELSE statements in ONE LINE without having any issue with the indentation and generates the same result.

python IF ELSE one liner code

Output

python IF ELSE one liner code output

Few more examples to understand how you can implement one liner IF-ELSE Statements.

  • Set value for variable “b” –  IF a=25 then set b=20 ELSE set b=10

>>> a=10

>>> b=20 if a==25 else 10

>>> print(b)

10

  • Set value for variable “b” –  IF var=”OneLineCode” then set b=20 ELSE set b=10

>>> var=”OneLineCode”

>>> b=20 if var==”OneLineCode” else 10

>>> print(b)

20

  • Set value for variable “b” –  IF var=”not_matching_str” then SET b=”New str” ELSE Set b=”TheEnd”

>>> var=”matching”

>>> b=”New str” if var==”not_matching_str” else “TheEnd”

>>> print(b)

TheEnd

>>> print(var)

matching

>>> 

The one liner IF-ELSE code can be used in the loop statements to make your code easily readable.

Read More: Python – IF-ELSE;   For-Loop;   While-Loop

Tips and Tricks: SUPERPUTTY CHANGE FONT SIZE OR BACKGROUND COLOUR

Python WHILE Loop & FOR Loop Control Flow Statements

Python while loop and for loop control flow statements

In this article we are going through Loop control flow statements in python. It is almost same as other programming language such as C, C++ or java etc.

Sometimes you must take control on program execution to run same set of code in a loop to get the desired output. To control the program execution, we have special utilities or statements called as “Control flow statements” 

The loop statements while or for allow us to execute a statement(s) over and over. A loop is controlled by a boolean expression that determines how many time statements can be executed.

Python has two primitive loop commands:
           1. While – loop
           2. For – loop

1. WHILE Loop

While condition is true keep running the loop and exit as soon as the condition becomes false. The conditional while loop syntax is the same as for if-else and elif statements.

Syntax:

while (conditional test):

    <statement1>

    <statement2>

    . . . .

    <last statement>

Example:

Python while loop statement code
Output:

Python while loop statement output

2. For Loop

Another loop statement – for, is best for when you determine in advance how many times you need to execute the block of statements placed in the loop.

It allows you to perform an operation on each element in a list or character in a string.

Syntax:

for in :

   

   

   


There are two types of for loops in python, first one is List – for loop and second one is          Range – for loop.

2.1 List – for loop

It’s very simplest method, all you need to do to specify complete list of items and it will be available in the loop.

Example:

python for loop statement code

Output:

python for loop statement output

Let’s take one more example-

for integer in [0, 1, 2]:

    print (“Integer :” + str(integer))

    print (“Integer Multplication :”+ str(integer * integer))

Output:

Integer :0

Integer Multplication :0

Integer :1

Integer Multplication :1

Integer :2

Integer Multplication :4

2.2 Range – for loop

For loop with range, gives you flexibility to use the appropriate range of values and important thing is you can control that range using available options along with for.

Syntax:

for var in range (start_pos, end_pos, steps):

    statement(s)

  • start_pos: Start position value should be excluded from range value when you specify value for steps otherwise it can be counted.
  • end_pos: End position must be excluded from range value.
  • steps: Steps value controls the range values.

Example:

python for loop range code
python for loop range output

Few more examples which will clear all your doubts if you have any!

Ex. 1

for i in range (1, 20, 2):

    print (“Range value :” + str(i))

Output:

Range value :1

Range value :3

Range value :5

Range value :7

Range value :9

Range value :11

Range value :13

Range value :15

Range value :17

Range value :19

Ex. 2

for i in range (20, 0, -2):

    print (“Range value :” + str(i))

Output:

Range value :20

Range value :18

Range value :16

Range value :14

Range value :12

Range value :10

Range value :8

Range value :6

Range value :4

Range value :2

 

Read More: Python break, continue and pass statements

Python IF ELSE & Nested IF-ELSE Control Flow Statements

Python IF ELSE and Nested IF ELSE control flow statements

In this article we are going through Python IF ELSE control flow statements. It is almost same as other programming language such as C, C++ or java etc.

The program default executes sequentially but sometimes you have to take control on program execution to get the desired output. To control the program execution, we have special utilities or statements called as “Control flow statements” 

Control
Flow IF-ELSE Statements:

               1. IF-ELSE

               2. Nested IF-ELSE

1. Python IF ELSE

IF-ELSE statement used to evaluate the condition and executes the block of statements based on results which is either YES (true) or NO (false)

General Syntax:

If (Condition)

Statement(s)

Else

Statement(s)

Syntax in Python: 

It is bit different syntax in python to write IF-ELSE conditional control flow statements. A blank spaces (indentation) is very important factor while writing code in python, especially if-else or nested if-else multiple conditional blocks. One extra blank space can kill your program!

if:

            <statement(s)>

else:

            <statement(s)>

Note: Please make a note, if-else statements are in lower case characters. In case if you write it in upper case, then you will get syntax error which is most common mistake people are doing. Python is very case sensitive language! 

Example:

Python IF ELSE Statement code

Output:

Python IF ELSE Statement code output

2. Nested IF ELSE

Simple IF-ELSE works fine but if you have multiple conditions and each one of them depends on another condition then Nested If-ELSE is very useful and effective.

It gives you flexibility to write multiple conditions and control your set of commands. It also helps to minimize the execution time as if one condition is true then it will skip further conditions and saves the time.

Syntax:

if :

            <statement(s)>

elif :

            <statement(s)>

elif :

            <statement(s)>

else:

            <statement(s)>

Be careful with if-elif-else statements, they must appear as-is in lower case and ELSE IF should be elif only. In case if you write any character in uppercase or elseif instead of elif, then you will defintely gets syntax error. Python is very case sensitive language and doesn’t allow any syntax violation.

Example:

Python Nested IF ELSE Statement code
Python Nested IF ELSE Statement output

Read More: Python For Loop and While Loop

Python Interactive and Script Mode programming

PYTHON INTERACTIVE AND SCRIPT MODE PROGRAMMING

How to run Python Code?

There are two python programming modes you can use to submit your python programs, Python Interactive and Script Mode Programming.

 

An interpreter works in a same way for both the programming methods so ultimately, we get the same result. But there are few exceptions and limitations to use these methods.

 

If you still do not have python installed on your machine then what are you waiting for! Download Now!!

 

Python Programming modes:


1. Interactive Mode Python Programming

If you are using Command Prompt to write and execute python commands, then you must invoke the interpreter without any parameters. All you need to do is – write “python” and python prompt will start automatically.

Microsoft Windows [Version 10.0.17763.195]

(c) 2018 Microsoft Corporation. Med enerett.

 

H:>python

Python 3.7.2rc1 (tags/v3.7.2rc1:75a402a217, Dec 11 2018, 23:05:39) [MSC v.1916 64 bit (AMD64)] on win32

Type “help”, “copyright”, “credits” or “license” for more information.

>>> 

Type following command in your python prompt and press enter to see the result. The result will appear in next line automatically when you press ENTER.

>>> print(“This is a sample Python Program”) 

Result –

This is a sample Python Program

2. Script mode Python Programming

 

If you are using command prompt to execute python script, then you must invoke the interpreter with file name as parameter. You may write your python code in any editors – notepad, notepad++ but the file extension should be .py to execute the program by interpreter.

Let’s take same example and try to execute it in script mode. Your script name is blog.py and it has the same code –

 

print(“This is a sample Python Program”)

 

We assume that you have Python interpreter set in PATH variable and your file present in the same directory where you are currently at. Now, try to run this program as follows –

$ python blog.py

Your program must be present in current directory otherwise you will get this error – “python: can’t open file ‘blog.py’: [Errno 2] No such file or directory”

 

This script will produce same output.

 

This is a sample Python Program

If you want to know What is Python IDLE then brief descriptive information available here – PYTHON IDLE

a Longr Python Program

Now we’ll try to run program which has more than one-line code. When we have more than one line of code and try to execute in interpreter mode and see the result. Let’s try to print this star using
interpreter mode.

print(”   *    “)

print(”  ***   “)

print(” *****  “)

print(”  ***   “)

print(”   *    “)

If we try to enter each line one at a time into the IDLE interactive shell, the program’s output will be intermingled with the statements you type. For example –

 

>>> print(”   *    “)

   *

>>> print(”  ***   “)

  ***

>>> print(” *****  “)

 *****

>>> print(”  ***   “)

  ***

>>> print(”   *    “)

   *

>>>

 

In such scenario the best approach is to type all code into editor, save the program in file (star.py) and run the program. 

 

Most of the time we use an editor to enter and run our Python programs. The interactive interpreter is most useful for experimenting with small snippets of Python code

In this example if we run this program star.py in script mode then each print statement “draws” a horizontal slice of star.

 

$ python star.py

 

Result:

 

In Python programming, it is more important that no whitespace (spaces or tabs) come before the beginning of each statement. In Python the indentation of statements is significant and must be done properly. If we try to put a single space before a statement in the interactive shell, we get this ERROR.

 

 

An interpreter reports a similar error when we attempt to run a saved Python program if the code contains such extraneous indentation.

 

Read Mode: Python Variable, Value and Data types