Basic Python

Recently, I have a good opportunity to work with python on some personal projects and client projects. I realized that Python is a simple programming language and easy to learn but powerful.

Today, I would like to share with you about basic python such as: data types, code layout, how to write a first simple program in python. The post is a guide or a tutorial for beginners who want to learn python.

At first, we should find out why we use Python and what python is used for.
Python was created by Guido Van Rossum in 1991.

Why Python ?

  • Simple: simple, easy to understand, readable.
  • Easy to learn: simple syntax
  • Free & open source
  • High level language: never bother the low-level details such as memory management etc.
  • Portable: python programs work on different platforms (Mac, Windows, Linux ..) without requiring any changes.
  • Interpreted : python doesn’t need compilation to binary. Internally, Python converts source codes into an intermediate form called byte-codes and then translates this to the native language of the computer and then runs it. You don’t worry about compiling the programs, making sure the proper libraries are linked and loaded etc. You just run the program directly from source code.
  • Object oriented: support procedure oriented programming & object-oriented programming.
  • Extensible: you can code a part of programming in C/C++ to run very fast and then use it from the python program
  • Embedded: embed the python within C/C++ program to give scripting capabilities for users
  • Extensive libraries: huge libraries on Python Package Index

Python used in

  • GUI application (PyQt4, PyQT5 etc)
  • Web apps (Django, Flask, etc)
  • Scrape data from websites (requests, scrapy etc)
  • Data analysis (Pandas, etc)System administration utilities
  • Game development (pygame ..)
  • Data science (pandas, numpy, sklearn, matplot…)

Prerequisites

  • Install python with latest version
    • on Windows:
      • Download python on Windows
      • Add python.exe to PATH in Environment Variables (Control Panel -> System -> Advanced System Settings -> Environment Variables)
      • Open terminal using cmd, and enter python3 -v
    • on Linux
      • Download python with latest version on Linux
  • IDE: Visual Studio Code or PyCharm
  • Editor: Notepad++ or Vim

Keep in mind

  • Syntax: use indentation to indicate a block of code.
  • Indentation is very important.
  • Comment: Using # for line comment or double quote “”” or ”’ for block comment
  • Variables: a container for storing values. No command to declare variable. A variable created once you assign a value to it.
  • Setup a virtual environment for each project. See more details, please refer to the post.
  • Think about a code layout:  top-down or bottom-up. It depends on the logic flow.
  • Organize a project structure in Python, please see the post
  • Style guide, please see the post

How to run 

  • On windows:
    • Check a python version: python3 -v
    • Run a python file: C:\python3 filename.py
    • Or run a python file: C:\filename.py (because Windows use the system registry and the file association to determine which program to use for running a particular file
  • On Linux
    • Check a python version : python3 -v
    • Run a python file: $python3 filename.py
    • To run a python file as command: $ ./filename.py
      • Use shebang: in the filename.py, 
        • add the line : #!/usr/bin/python (using absolute path)
        • or #!/usr/bin/env python : using the operation system env command which locates and execute python by searching the PATH environment variable
      • To run script, we need to assign execution permission to the filename by using
        • chmod 755 filename.py
        • or chmod +x filename.py

How to write a python code to resolve the problem given?

In order to start with new programming language, we recommend that you learn data types, control flow, functions & modules etc. and find out how it works.

Data types

  • Number: int or float
  • String
    • built-in method 
    • combine strings
  • Casting type: int(), float(), str()

Data structures

1.list

  • Syntax: a_list = [value_1,.., value_n]
    • any type of sobject from numbers, string to more lists
    • can be indexed, changed, sliced
    • operators:
      • slicing: 
        • a_list[start:stop]: items start through stop-1
        • a_list[start:]: items start through the rest of array
        • a_list[:stop]: items from beginning through stop-1
        • a_list[:]: a copy of the whole array
      • delete
        • a_list.remove(3)
        • a_list.pop(3)
        • del a_list[0]
        • clear(): erase all the elements of a list
    • Reference: https://www.programiz.com/python-programming/list

2.tuple

  • Syntax: a_tuple =(value_1,…, value_n)
    • can not modify
    • operator:
      • slicing
      • No add or delete
    • Reference: https://www.programiz.com/python-programming/tuple

3.set

  • Syntax: a_set = {value_1, …, value_n}
    • no ordered & indexed
    • no duplicates, no change
    • operators:
      • union, intersection, symmetric difference, 
      • add(), update()
      • remove(), discard()
    • Reference: https://www.programiz.com/python-programming/set

4.dictionary

  • Syntax: a_dict = {key_1: value_1, key_2: value_2,.., key_n: value_n }
    • no ordered, changeable, indexed
    • operators:
      • get(): return value of a specified key
      • pop(): remove the element with the specified key
      • update(): update the dictionary with the specified key-value pairs
      • values(): list all the values in the dictionary..
    • Reference: https://www.programiz.com/python-programming/dictionary

Operators & expression

  • plus (+): 3 +5 gives 8; ‘a’ + ‘b’ = ‘ab’
  • minus (-): 5-3 gives 2
  • divide (/): 8/2 gives 4
  • multiple (*): 3*2 gives 6
  • modulo (%)
  • power (**): 3**2 gives 3*3
  • ~, &, |, ^
  • <, <=, >, >=, ==, !=
  • << (left shift), >> (right shift)
  • Boolean and, or

Control flow

  • if else or if elif else: to check a condition. If the condition is True, it will run a block of statement called if-block, otherwise it process another block of statements called else-block.

                if x==2:
                    do something
                else:
                    do something

  • while statement: execute a block of statements repeatedly as long as a condition is true

                while True:
                    do something

  • for … in statement: iterate over a sequence of objects (go through each item in a sequence): 

                for i in range(1,5):
                   print(i)

  • break statement: break out of a loop statement  

     while True:
                do something
                if i>100:
                    break

  • continue statement: to skip the rest of statements in the current loop block and to continue the next iteration of the loop

Function

A function is a block of code which only runs when it calls. We can pass the parameters and return the data as a result. 
Syntax: def name(a, b):               
pass / return
-def: keyword
-name: name of function
-a,b: argument or parameter.
-pass: a function is not empty. In case you don’t have the content, use pass to avoid getting the error.
-return: to let a function return value

Arguments / Parameters

A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called.

  • *args: in case you don;t know how many arguments will be passed into your function, add * before the parameter name. the function will receive a tuple of arguments and can access item accordingly.
  • **kwargs: if you don’t know how many keyword arguments will be passed into you function, add ** before the parameter name. The function will receive a dictionary 
  • default parameter value:
    • def my_function(name=’Thu’)

Local & Global variable

  • Local variable: declare inside the function

                x=10
            def my_name():
                x = 1
                print(x)
            # Call my_name
            my_name()
            # Print value x
            print(x)
Output:
            1
            10

  • Global variable: is defined and declared outside a function and need to use them inside a function. You only use the global keyword in a function if you want to do the assignments / change item

x=10           
def my_name():    
        global x
         print(x)  
         x = 1      
         print(x)
  # Call my_name  
       my_name()           
print(x)                        
output:           
10           
1           
1

A lambda function is a small anonymous function.

Syntax:
lambda arguments: expression
e.g: x = lambda a,b : a+b  => print(x(5,6))

Now, we should apply the concepts by the problem given as below:
Everybody would use a calculator such as Casio etc. to perform operators such as +,-,*, / and sqrt. You write a python program that allow user to 
– Enter two numbers
– Perform operators: +,-,* and /

Firstly, you analyze the requirements:
– User will enter first number, then second number
– Next, user will perform operators by choosing one of these operators
– The program displays the result
– Loop step 1 if user would like to perform another operator.
Secondly, you should write down the workflow in your language.
Each operator should design as a function.
def plus(a,b):   
return float(a)+float(b)
def minus(a,b):
    return float(a)-float(b)
def multiple(a,b):
    return float(a)*float(b)
def divide(a,b): 
  return float(a)/float(b)
def main():
    while True: 
        #Enter numbers
        a = input(‘Enter your first number :’)
        b = input(‘Enter your second number :’)
        # Ask a user to choose an operator to perform them. 
      c = input(‘Choose one of operators : +,-,*,/ :’)
        # Call a function
        if c == ‘+’ :
            print(plus(a,b))
        elif c == ‘-‘: 
          print(minus(a,b))
        elif c==’*’: 
          print(multiple(a,b))
        elif c==’/’:
            print(divide(a,b))
        b = input(‘You would like to quit the program ? [Y,N]’)
        if b ==’Y’: 
            break
if __name__ == ‘__main__’:    main()

Our comments: the program is NOT really perfect, it still needs some improvements to work better, for example:
– need to check if the numbers is numeric
– need to display a message if the user enters a wrong operator
Now your turn: make the improvements.
Please share with us your solutions by leaving your comments. All are welcome.

Online book
Automate the Boring Stuff with Python
Python programming