PHP Professional এবং Zend Certified PHP Engineer (ZCPE ) Course এ সীমিত সংখ্যক আসন বাকি আছে। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

Dive into Python

In this tutorial we will learn about different Python features. We will write some code and see what is really happening.

Python

Topics
We will learn about following topics in this tutorial.

1. Assessing logic
2. Conditions
3. Casting data type
4. Lists
5. Tuple
6. Dictionary
7. Loop: While
8. Loop: For
9. Functions
10. Handling Exceptions
11. Generators

1. Assessing logic
There are 3 logical operators in Python and (Logical AND), or (Logical OR), not (Logical NOT). The logical operators used with two Boolean values, True and False. Let’s check it by a program.

Create a new script with logic.py

a = True
b = False

print " "

print("a = True")
print("a = False")

print " "

print "and Logic ---"
print "a and b: ", a and b
print "a and a: ", a and a
print "b and b: ", b and b

print " "

print "or Logic ---"
print "a or b: ", a or b
print "a or a: ", a or a
print "b or b: ", b or b

print " "

print "not Logic ---"
print "a not a: ", not a
print "b not b: ", not b

print " "

Output:

a = True
a = False

and Logic ---
a and b: False
a and a: True
b and b: False

or Logic ---
a or b: True
a or a: True
b or b: False

not Logic ---
a not a: False
b not b: True

The output shows the truth table operations.

2. Conditions
Before write our program for condition, we need to know something very important.

1. Usually, Python doesn’t use brackets for its conditional check rather it use colon (:) and indentation.
2. In Python, indentation is everything. Usually four (4) spaces is a good for nesting.

So, be careful about these two points. If you mess with these, your program may not work properly.

Now create condition.py and write the following code.

a = 2

if a == 1:
    print "One"
elif a == 2:
    print "Two"
else:
    print "Neither"

In-line condition check is also possible in Python

a = 2

print "Variable is: ", "Even" if(a % 2 == 0) else "Odd"

It will check if the variable is even or odd.

3. Casting data type
There are several Python data types but the most common ones are int(), str(), float(). And type() function checks the data type of the variable. By default Python takes all the data from user is a string object. So we need to convert it before use.

Now create new script named cast.py

a = raw_input("Enter 1st integer: ")
b = raw_input("Enter 2nd integer: ")

print ""

print "Data type of 'a': ", type(a)
print "Data type of 'b': ", type(b)

print ""

a = int(a)
b = int(b)

print "Data type of 'a': ", type(a)
print "Data type of 'b': ", type(b)

c = a + b

print ""

print "a + b = %d" % c

Output:

Enter 1st integer: 3
Enter 2nd integer: 5

Data type of 'a':
Data type of 'b':

Data type of 'a':
Data type of 'b':

a + b = 8

4. Lists
Lists are like arrays in other language. We can access list with its index number.

Create a file called lists.py

years = ["January", "February", "March", "April"]
coords = [[1, 2, 3, 4], [5, 6, 7, 8]]

print "The month I was born: %s" % years[1]

print "coord[1][2] is %d" % coords[1][2]

5. Tuple
The values of regular list can be changed by program. But we can create list with fixed immutable values that we cannot change. This kind of list is called tuple.

Lets create a new file called tubles.py

colors = ("red", "green", "red", "blue", "yellow")

print "The second color is: %s" % colors[1]

6. Set
Regular list can have duplicate values. But in set duplicate is not allowed. This list is called set in Python. Set’s does not support indexing. Regular set manipulation functions are given below –

set.add(x) : Adds item x to the set
set.update(x,y,z) : Adds multiple items in a set
set.copy() : Returns a copy of the set
set.pop() : Removes one random item from the set
set.discard(i) : Removes item at position i from the set
set1.intersection(set2) : Returns items that appear in both sets
set1.difference(set2) : Returns items in set1 but not in set2

Create a new script, sets.py

colors = {"red", "green"}

print colors
print "Length of the set is: %s" % len(colors)

colors.add("yellow")
print colors
print "Length of the set is: %s" % len(colors)

7. Dictionary
Dictionaries are associative arrays in other language. It stores multiple unordered key:value pairs. We can access value with the reference of key.

Now create a new file, dict.py

dictionary = {"name": "Shahjalal", "ref": "Python", "sys": "Mac"}

print dictionary

print ""

print "The system is: %s" % dictionary["sys"]

8. Loop: While
Loops are used to iterate through the sequence. We can interrupt this execution with “break” and “continue” keywords.

Create a new script while.py

i = 0

while i < 10:

    if i == 2:
        i += 1
        continue
    elif i == 7:
        break
    else:
        print i

    i += 1

9. Loop: For
For loop is work like while. It is usually used to loop over all the items in the list.

To check this create for.py

dictionary = {"name": "Shahjalal", "ref": "Python", "sys": "Mac"}

for key, value in dictionary.items():
    print key, " = ", value

10. Functions
In Python function starts with def keyword with the function name and parentheses. We can pass zero or more arguments into the function. And the function can or can not return values. One more important thing need to remember function should be define first then the call. Otherwise you call can not get the function.

Create a new file, function.py

a = 3
b = 6

def addValue(a, b):
    c = a + b
    return c

print "a + b = %d" % addValue(a, b)

11. Handling Exceptions
In Python exception handling works with “try except” block. Optionally we can use “finally” block, as well. “finally” block will always work after handling all the errors. Usually in finally block we keep all the file, database or network close connections.

Create except.py

a = 5

try:
    if a == 5:
        raise ValueError(“Invalid Number”)
except ValueError as msg:
    print msg
finally:
    print “The number is almost ok…”

12. Generators
When a Python function is called, it executes a statements it contains and may return any value specified to the return keyword. After the function ends, control returns to the caller and the state of the function is not retained. When the function is next called, it will process its statements from start to finish once more.

A Python generator is a special function that returns a generator object to the caller rather than a data value. This retains the state of the function when it was last called so it will continue from that point when next called.

Create a file named generator.py

def fibonacciGenerator():
    a = b = 1

    while True:
        yield a
        a, b = b, a+b

fib = fibonacciGenerator()

for i in fib:
    if i > 100:
        break
    else:
        print i

All codes are available in my git repository.

Conclusion
It’s a long reading. Take a break. In next tutorial we are going to learn more advance feature of Python, line OOP.

Happy Coding… 🙂

Dive into Python

Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.

Leave a Reply

Your email address will not be published. Required fields are marked *