Pravar Agrawal Technology & Travel

Python Learning Part 2

In last post we discussed on some features of Python and getting started with it. Continuing from last time, we’ll look at some more super cool features of Python today.

Python gives us feasibility to assign multiple variables in a single line. Following example explains it better,

>> a, b = 45, 54

This single line assignment of multiple variables is based upon a data-type called tuple in Python. We use comma to create a tuple. For example,

>> var_tup = ("Pravar", "Agrawal", "Reads", "In")

In any programming language, there is one way or the other of formatting strings. In Python, we can achieve this by using .format method like explained below,

>>> var_name = "Pravar"
>>> var_surname = "Agrawal"
>>> print("{0} is my first name and {1} is last name".format(var_name, var_surname))
Pravar is my first name and Agrawal is last name

Now, let’s take a look at operators in Python. Like every other programming language, Python also incorporates logical and mathematical operators. Some examples of mathematical operators are like,

>>> 2+3
5
>>> 20-3
17
>>> 10.0/5
2.0
>>> 14 % 2
0

For logical operations we use Relational Operators and below are the few in Python,

<    Is less than
<=   Is less than or equal to

More of boolean operators can be found here Built-in Types.

There could be scenario when we might need to convert the type of value which we are trying to assign in a variable. For example, our user input gives us the value by default as string type but we can convert that into an integer, float using type converstions in Python. Like,

>>> a = input("Enter the value: ")
Enter the value:
12
>>> b = int(a)
>>> print(type(b))
<type 'int'>

In any programming language, control flow (if-else) statements are very important be it a complex or an easy programme we are writing. In Python, If-else are used in defining the control or decision making in situations like which food option is better than other, which variety of fish is more cheaper etc. For example,

if expression:
    execute this block of code
else:
    execute this one then

Also, for looping we can use While statements in Python as well to repeat a block of code quite a few times. Like,

while condition_1:
    execute this statement
    execute this statement as well

The code which we want to call again must be placed under while block with proper indentation. If the condition is true, then the statements inside while block will be executed. There are other looping statements which we will continue with in our next post in this series.