Learn Python Programming in 15 Minutes Part-2 in 2018

By Kimberly Cook |Email | Dec 27, 2018 | 24381 Views

Control Flow, Functions, Object Orientation.

Control Flow
The for loop
The for loop in Python has the ability to iterate over items of any sequence such as list or string.
It steps through the items in any ordered sequence i.e, String, List, Tuples, the keys of dictionaries and other iterable terms. The python for loop starts with a keyword for followed by a variable attribute, which will hold the values of the following sequence object.

Syntax of for loop
for variable in sequence:
    statement(s)

Example:

colors.py
colors = ['Red', 'Black', 'Blue', 'White', 'Pink']
for color in colors:
    print(color)

python3 colors.py
Red
Black
Blue
White
Pink

math_table.py
for index in [1, 2, 3, 4, 5]:

    print("{} times 5 is {}".format(index, index * 5))

In this case, we just print the value in the block of statements.

python3 math_table.py
1 times 5 is 5
2 times 5 is 10
3 times 5 is 15
4 times 5 is 20
5 times 5 is 25

The While loop
A while loop statement in Python programming language repeatedly executes a target statement as long as the given condition is true. Unlike the for loop, the while loop will not run n times, but until a defined condition is met.

Syntax of While loop
while condition:
    statement(s)

Example:

countdown_timer.py

flag = 10
while 0 < flag:
    print(flag)
    flag = flag - 1
print('Go !!')

The Range Function
The range function in Python generates a list of numbers, which can be used to iterate over for loops and in other few cases.
Now let's see how range function works
range(n)
range(begin, end)
range(n) generates, the integer numbers starting with 1 and ending with (n-1).
range(begin, end) generates the integer numbers starting with begin and ending with end-1.

$python3
>>> range(8)
range(0, 8)

Example:
Printing the squares of numbers iterating by range function.

square.py
for number in range(1, 7):
     square = number * number
    print(square)

python3 square.py
1
4
9
16
25
36

Functions
The function is a block of reusable code that performs a specific task. It is a small unit of computation which may take arguments and may return values.

Note: Function body must be indented like 'if' statement.

Declaring a function
The keyword def introduces a function definition followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented.

Syntactically,
def function_name(formal parameters):
    statement(s)

Note: Declaring a function doesn't run the function. In order to run, you have to call the function using the function name.
Example

greet.py
# Declaring a function.
def greet():
    print("Hello ! Welcome to the party.")
# calling the function.
greet()

python3 greet.py
Hello ! Welcome to the party.

In this program, we created a function named greet with no parameters such as empty parenthesis. The function is defined to print a string called ??Hello! Welcome to the party.??
So calling the function just prints the given string.

Functions with parameters.
A function can take parameters which are values you supply to the function so that the function can do something utilising those. Parameters are specified within the pair of parentheses in the function definition separated by commas.

Example:
greet_names.py
def greet_name(name):

    print("Hello {}".format(name))

greet_name("Flash")

greet_name("Arrow")

greet_name("Bat")

python3 greet_names.py
Hello Flash
Hello Arrow
Hello Bat

factorial.py

def num_factorial(num):

    factorial = 1

    if num < 0:

        print("Sorry, factorial does not exist for negative numbers")

    elif num == 0:

        print("The factorial of 0 is 1")

    else:

        for i in range(1, num + 1):

            factorial = factorial * i

    print("The factorial of number is {}" .format(factorial))

num_factorial(5)

python3 factorial.py
The factorial of a number is 120

Also see Recursion, Scope of Variable.
Introduction to Object-Oriented Python
In all the programs we wrote till now, we have designed our program around functions i.e. blocks of statements which manipulate data. This is called the procedure-oriented way of programming. There is another way of organizing your program which is to combine data and functionality and wrap it inside something called a class. This is called the object-oriented programming paradigm.

A quick glance at the basics of the Object Orientation terminology.

Class : A class is a blueprint from which individual objects are created.
Object : A real World entity which has state and behavior.
Let's create a class Person with a class method says in the class.

class Person():
    def say(self):
        print("Hello")

Now let's create an object instance for the class.
class Person():
    def say(self):
        print("Hello")

jackman = Person()
jackman.say()

Extending the plot further lets us create two methods, hello and bye that take arguments.

methods_examples.py
class Person():
    def hello(self, name):
        self.name = name
        print("Hello {} How are you ?".format(self.name))
    def bye(self, name):
        self.name = name
        print("Nice Meeting You {}".format(self.name))
jackman = Person()
jackman.hello("Lee")
jackman.bye("Edison")


python3 method_examples.py
Hello Lee How are you?
Nice Meeting You Edison

Note: Self is a default argument for all instance method

This needs us to repeat the instance variable for every class method instead of creating an object with the instance variables. It's now time to work with constructors.

Constructors
Constructors in Python are written under a special method __init__.
Now let us write a constructor for an object. In this, example let's create an object with instance variables name and year_of_birth. This process of writing a constructor in a class eliminates the repeating of the instance variables for every instance method.

constructors.py

class Person():

    def __init__(self, name, year_of_birth):

        self.name = name
        self.year_of_birth = year_of_birth
    def detail(self, name):
        print("Name of the person is {}".format(name))
    def age(self, year_of_birth):
        print("Your are {} Years Old".format(year_of_birth))

person = Person('Vihar', 1998)

person.detail('Vihar')

person.age(19)

python3 constructors.py
Name of the person is Vihar
You are 19 Years Old

Classes and Objects Example :
bank_account.py

class BankAccount:
    def __init__(self):
        self.balance = 0
    def withdraw(self, amount):
        self.balance -= amount
        return print(self.balance)

    def deposit(self, amount):

        self.balance += amount

        return print(self.balance)

a = BankAccount()

b = BankAccount()

a.deposit(100)

b.deposit(50)

b.withdraw(10)

a.withdraw(10)

python3 bank_account.py
100
50
40
90


The article was originally published here

Source: HOB