In Part 1, we talked about the history of python, how to install it and a few basic syntaxes of the language. In this blog, we will see how to control the flow of program execution (if…else, loops, etc.), functions, Object-Oriented Programming, different usage and future of the language in the programming world.
Flow Control
Python usually executes the code in a sequential manner, i.e., if you print 5 number, then it will print them in that order:
But there is a way with which we can control the order of execution, or you can say Control the Flow of the program.
1. The if statement
The if statement is used to check a condition if something is true then do this else to this. The if statement has two blocks of codes associated with it: 1. If Block and 2. Else Block (optional).
The if block is the statements that will be executed when the condition is true, otherwise, else block will be executed. Consider the following code to get an intuition of how to write an if statement in python:
There is another type of if statement which has 3 blocks in it, the usual if block and else block and also elif block. The elif block is used to specify multiple conditions in an if statement, consider the following code:
2. The while statement
The while statement (also known as a “while loop”) allows you to execute a block of statements repeatedly as long as the condition is true. A while statement just like an if statement has two blocks: 1. while block and 2. else block
The while block is executed by the interpreted as long as the condition specified is true, and the else block, which is optional, is executed when the condition becomes false and interpreter exits the while statement.
Consider the following program to get an idea, how you can write a while statement in python:
3. The for loop
The for loop statement is used to iterate over a sequence of objects, unlike while loop in which we check a condition to decide whether to end the loop or not. Consider the following code to see how for loop is used in python.
In the above code, range(1,100) is a built-in function that produces a sequence of numbers from 1 to 99. You can learn more about this and other built-in functions of python in its official documentation. You can see that there is an optional else block in for loop also, that is executed when all the elements in the provided sequence are traversed.
The “sequence” in the for loop can be anything such as an array, list, dictionary, but not any single-valued variables (such as an int, char, or data types like that).
If you write a string in place of the sequence in for loop, then the loop will traverse through each character in the string.
You can learn more about sequences in python, from this online book.
4. Break Statement
The break statement is used to stop the execution of the loop in between, even if the condition is still true. This is useful when you don’t want to run the complete loop every time you run the program. One example of this can be seen in the Linear Search Algorithm, which is implemented in the following code:
X = [1,2,3,4,5]
item = 4
for x in X:
if (x == item):
print(item+" is in the list");
break
5. Continue statement
The continue statement is used to skip the rest of the statement in the current loop block and go to the next iteration of the loop. See the following code for the use of continue statement.
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
In the above code, input() is another built-in function that is used to take inputs from the user and len() is used to get the total length of the string (how many characters are there in the string).
Functions
Functions in programming languages is a reusable piece of code. You can specify a unique name for each function and use that name to use the block of code associated with that function name anywhere in your program and any number of times. This is called the calling of a function.
In python, functions are defined using def keyword (a keyword is a word that is reserved by a program because the word has a special meaning) which is followed by the function name and parenthesis, something like this:
def hello():
# the block of code in this function
print("Hello, Idiomatic Programmer")
and you can call this function like this:
hello()
"""
The output will be
Hello, Idiomatic Programmer
"""
You can pass some information into the function, this information is called function parameters and is executed as:
def add(a,b):
# this function adds parameters a and b
print(a+b)
When you have more than one parameter, then you have to separate them using commas (,).
When you declare variables inside a function, that variable has no relation with anything outside that function, you can say that the variable is local to the function. This is referred to as a Local Variable. And the reach of the variable is known as the scope of a variable, the scope of a local variable if the function/block it is declared and initialized.
Consider the following code for an example:
x = 50
def func(x):
print('x is', x)
x = 2 # This is a local variable
print('Changed local x to', x)
func(x)
print('x is still', x)
"""
The output will be:
x is 50
Changed local x to 2
x is still 50
"""
In this program, you cannot change the value of x, since it is the local variable and the scope of a local variable is within that function.
But what if you do want to change the value of x, then you can use something called a Global Variable which is defined using global keyword in python.
Let’s take the example of previous code and change that a little bit, so that we can change the value of x.
x = 50 # this is a global variable
def func():
global x
print('x is', x)
x = 2 # This changes the global variable x
print('Changed x to', x)
func(x)
print('now x is', x)
"""
The output will be:
x is 50
Changed x to 2
now x is 2
"""
So, this is how you can use variables in a function. You can also set default values for the parameters in a function. These parameters will then become optional and you don’t have to pass that variable if you don’t want to use that variable. Consider the following program:
def say(message, times=1):
print(message * times)
say('Hello')
say('Jello ', 5)
"""
The output will be:
Hello
Jello Jello Jello Jello Jello
"""
In the above program, the parameter times is an optional parameter and if you don’t pass that parameter, then the default value of that variable is used, which is specified as times = 1 in this program and if you pass the value for times, then that passed value overwrites the default value.
So that covers the basic things about functions in python. If you have something to ask, just comment that below.
Object-Oriented Programming (with Python)
All the code we have seen until now was based on functions and blocks. This type of programming is called procedural programming.
There is another way of organizing your program which is to combine data and functionality and wrap it inside something called an object. This is called the object-oriented programming paradigm. Most of the time you can use procedural programming, but when writing large programs or have a problem that is better suited to this method, you can use object-oriented programming techniques.
Classes and Objects are the two main aspects of Object-Oriented Programming.
The object is simply a collection of data (variables) and methods (functions) that act on those data. And, the class is a blueprint for the object. We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. As many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.
Defining a Class
Like function definitions begin with the keyword def, in Python, we define a class using the keyword class.
class Building:
'''This is the syntax of creating a class in python.'''
pass
In the above code, pass is a keyword that is used to construct a body that does nothing.
Creating an Object
A new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class.
ob = Building()
A class can contain different variables (instance variables) and function (methods)
There are many concepts of Object-Oriented Programming, which is unfortunately out of the scope of this blog.
Different uses of Python
Python is used in many application domains, the Python Package Index lists thousands of third-party modules for Python. Some of the industries Python is used in are:
1. Web and Internet Development
- Python offers many choices for web development:
- Frameworks such as Django and Pyramid.
- Micro-frameworks such as Flask and Bottle.
- Advanced content management systems such as Plone and Django CMS.
- Python’s standard library supports many Internet protocols:
- HTML and XML
- JSON
- E-mail processing
- Support for FTP, IMAP, and other Internet protocols
- And the Package Index has yet more libraries:
- Requests, a powerful HTTP client library.
- BeautifulSoup, an HTML parser that can handle all sorts of oddball HTML.
- feedparser for parsing RSS/Atom feeds.
- Paramiko, implementing the SSH2 protocol.
- Twisted Python, a framework for asynchronous network programming
2. Scientific and Numeric
- SciPy is a collection of packages for mathematics, science, and engineering.
- Pandas is a data analysis and modelling library.
- IPython is a powerful interactive shell that features easy editing and recording of a work session and supports visualizations and parallel computing.
- The Software Carpentry Course teaches basic skills for scientific computing, running boot camps and providing open-access teaching materials.
3. Desktop GUIs
And many more, The open-source community of python enabled many third-party developers to make their own libraries and module. There are more than 63,000 packages in python and this number is growing day by day.
Future of Python
The app development market is greedy but flexible. Python is now a trend, no doubt about it. Since it’s so easy to learn, you can start your programming journey with Python. Python is also really friendly, thanks to its popularity and the helpful community.
This versatile, robust and comprehensive programming language is used by many top brand firms like Google, Disney and Red Hat, which is a clear indicator of its popularity. It has even secured a spot in the top ten data analytical tools of the industry list so far, which is affirmative of its bright future in terms of career opportunities. The fact that this tool can be used across multiple platforms and is both flexible and adaptable, makes it a crowd favourite as well as a tool which will survive for long in this industry.