Python Programming by Example (2015)
2. Python Programming Language
This chapter explains the basic of Python programming language.
2.1 Common Rule
Python language doesn't write ";" at the end of syntax like you do it on C/C++ languages. Here is the syntax rule of Python:
syntax_code1
syntax_code2
syntax_code3
2.2 Variables
In this section, we explore how to define a variable and assign its value. By default, we define variables on Python with assigning value .
# declare variables
num = 2
area = 58.7
city = 'Berlin'
country = "Germany"
z = 10 + 5j # complex number
If you want to declare variables without assigning values, you can set it using None.
# declare variable without initializing value
counter = None
index = None
Write these codes for testing.
# declare variables
num = 2
area = 58.7
city = 'Berlin'
country = "Germany"
z = 10 + 5j # complex number
# declare variable without initializing value
counter = None
index = None
global var_global
var_global = 10
print(num)
print(area)
print(city)
print(country)
print(z)
print(z.real)
print(z.imag)
print(var_global)
Save these scripts into a file, called ch02_01.py.
Now you can type this file using Python 3.x.
$ python3 ch02_01.py
A sample of program output can seen in Figure below.
2.3 Comment
You may explain how to work on your code with writing comments. To do it, you can use # and """ syntax. Here is sample code:
# this a comment
"""
These are long comments
These are long comments
These are long comments
"""
2.4 Arithmetic Operations
Python supports the same four basic arithmetic operations such as addition, subtraction, multiplication, and division. For testing, create a file, called ch02_02.py.
The following is the code illustration for basic arithmetic in ch02_02.py:
a = 2.3
b = 8
c = a + b
print(c)
c = a - b
print(c)
c = a * b
print(c)
c = a / b
print(c)
Save and run this program.
python3 ch02_02.py
A sample of program output:
2.5 Mathematical Functions
Python provides math library. If you’re working with Python 2.x, you can read this library on https://docs.python.org/2/library/math.html . For Python 3.x, you can read math library on https://docs.python.org/3/library/math.html .
Create a file, called ch02_03.py. Write the following code.
from math import *
a = 1.8
b = 2.5
c = pow(a, b)
print(c)
c = sqrt(b)
print(c)
c = sin(a)
print(c)
print(pi)
Save and run the program.
python3 ch02_03.py
A sample of program output:
2.6 Increment and Decrement
Python doesn't has special syntax for increment and decrement. We can define increment and decrement as follows.
· ++ syntax for increment. a++ can be defined as a = a + 1
· -- syntax for decrement. a-- can be defined as a = a - 1
For testing, create a file, called ch02_04.py. Write the following script.
a = 4
print(a)
# increment
a = a + 1
print(a)
a += 10
print(a)
# decrement
a = a - 2
print(a)
a -= 7
print(a)
Then, save and run the program.
python3 ch02_04.py
A sample of program output:
2.7 Getting Input from Keyboard
To get input from keyboard, we can use input() for Python 3.x and raw_input() for Python 2.x.
For testing, create a file, called ch02_05.py, and write this script.
# getting input from keyboard using input()
name = input('What is your name?')
print('Hello,' + name + '!!')
user_id = input('What is your ID?')
print('Id is ' + str(user_id))
# getting input from keyboard using raw_input()
product = raw_input('Product name?')
print('Product=' + product)
product_id = raw_input('Product ID?')
print('Product id= ' + str(product_id))
Save and run the program.
python3 ch02_05.py
A sample of program output:
2.8 Python Operators
In this section, we learn several Python operators such as comparison, logical and bitwise operators.
2.8.1 Comparison Operators
You may determine equality or difference among variables or values. Here is the list of comparison operators:
== is equal to
!= is not equal
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
2.8.2 Logical Operators
These operators can be used to determine the logic between variables or values.
&& and
|| or
! not
2.8.3 Bitwise Opeators
Bitwise operators in Python can be defined as follows
& AND
| OR
^ Exclusive OR
>> Shift right
<< Shift left
~ Not (Inversion)
2.8.4 Testing All
Now we test how to use comparison, logical and bitwise operators in code. Create a file, called ch02_06.py, and write these scripts.
# comparison operators
a = 3
b = 8
print(a == b)
print(a != b)
print(a > b)
print(a >= b)
print(a < b)
print(a <= b)
# logical operators
print((a == b) and (a != b))
print((a <= b) or (a > b))
print(not (a >= b))
# bitwise operators
# declare binary variables
m = 0b01010011
n = 0b11111001
print(m)
print(n)
print(bin(m & n))
print(bin(m | n))
print(bin(m ^ n))
print(bin(~m))
print(bin(b << 3))
print(bin(b >> 2))
Save this file and run the program.
python ch02_06.py
A sample of program output:
2.9 Decision Control
Syntax model for if..else can be formulated as below:
if (conditional):
# do something
else:
# do something
#########
if (conditional):
# do something
elif (conditional):
# do something
else:
# do something
For testing, create a file, called ch02_07.py and write these scripts.
# if-else
a = 10
b = 30
print('demo if-elif-else')
if (a > 10) or (b > 10):
# do something
print('(a > 10) or (b > 10)')
elif (a != 5) and (b <= 7):
# do something
print('(a != 5) and (b <= 7)')
else:
# do something
print('else')
# nested if
if (a == 0) or (b > 20):
if b < 50:
print('nested-if')
else:
print('else-nested-if')
else:
print('if-else')
Save and run the program.
python3 ch02_07.py
A sample of program output:
2.10 Iteration - for and while
Iteration operation is useful when we do repetitive activities. The following is for syntax.
for (iteration):
# do something
while (conditional):
# do something
For testing, create a file, called ch02_08.py and write these scripts.
# iteration - for
print('demo - iteration for')
for i in range(1, 5):
print(i)
# nested - for
print('demo - nested for')
for i in range(1, 3):
for j in range(5, 10):
print(str(i) + '-' + str(j))
# iteration - while
print('demo - iteration while')
i = 0
while i < 10:
print(i)
i += 1
Save and run the program
python3 ch02_08.py
A sample of program output:
2.11 break, continue and pass
break can be used to stop on the code point. Otherwise, continue can be used to skip some scripts. For illustration, we have a looping. The looping will be stopped using break if value = 7. Another sample, we can skip the iteration with value = 4 using continue syntax.
Write these scripts.
print('demo - break, continue and pass')
for i in range(1, 10):
if i == 4:
continue
if i == 7:
break
print(i)
pass # do nothing
print('This is the end of program')
Save these scripts into a file, called ch02_09.py.
Run the program.
python3 ch02_09.py
A sample of program output:
2.12 Date & Time
We can work with Data and time in Python using time library. We must import this library.
For testing, write these scripts.
import time
# get current time
now = time.time() # utc
print(now)
# display readable current time
print(time.strftime("%b %d %Y %H:%M:%S", time.gmtime(now)))
print(time.timezone)
Save the program into a file, called ch02_10.py.
Run the program.
python3 ch02_10.py
A sample of program output: