Python Basic: 1.1 Hello World
Python Basic: 1.1 Hello World
Python Basic
1.1 Hello world
We will use the print() function to print our first python program: hello world.
Here, 'hello world' is a string, a sequence of characters. In Python, strings are enclosed in single
quotes, double quotes, or triple quotes.
world""")
1.2 Comments
Comments are very important while writing a program. They explains the codes in lines for
programmers to better understand a program.
In Python, we use the hash (#) symbol to start writing a comment.Python Interpreter ignores
comments during excution.
We can have comments that extend up to multiple lines. One way is to use the hash(#) symbol at
the beginning of each line. Another way of doing this is to use triple quotes, either ''' or """.
In [3]: """
triple quotes for
multiple
lines
"""
print("hello world")
hello world
As our application program grows larger in size with a lot of modules, we place similar modules in
one package and different modules in different packages. This makes a project (program) easy to
manage and conceptually clear.
import
from ... import ...
Out[4]: 'D:\\lab\\code'
Out[5]: 'D:\\lab\\code'
platform.platform()
Out[6]: 'Windows-10-10.0.19041-SP0'
pf.platform()
Out[7]: 'Windows-10-10.0.19041-SP0'
1.4 Variables
Variables are containers for storing data values. A variable is a named location used to store data
in the memory.
In [9]: a = 2
print(a)
In [10]: aA9_ = 1
price = 100
If you want to create a variable name having two words, use underscore to separate them.
In [12]: number_of_cats = 6
1.5.2 Keywords
Keywords are the reserved words in Python.They cannot be used as ordinary identifiers and must
be spelled exactly.
Out[59]: ['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
In [60]: help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
1
2
2
1
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-63-e03f8af417bd> in <module>
1 x = 0
----> 2 print(x+y)
3 y = 1
1.8 Indentation
A code block (body of a function, loop, etc.) starts with indentation and ends with the first
unindented line.
The number of space to be indented is up to you, but it must be consistent throughout that block.
Indentation makes Python code look neat and clean. This also makes Python code look similar
and consistent.
def func2():
a = 2
b = 2
Local variables are variables declared in local scope (code block with indentation).
c = 3
print(a+c)
4
In [66]: print(a+f)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-66-e5cacae4cdcc> in <module>
----> 1 print(a+f)
In [68]: help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
In [69]: a = 1
id(print)
Out[69]: 2693858468152
In [70]: a = 1
type(a)
Out[70]: int
In [71]: a = 1
del(a)
print(a)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-71-691d79be5171> in <module>
1 a = 1
2 del(a)
----> 3 print(a)
In [72]: len("hello")
Out[72]: 5
Integers and floating points are separated by the presence or absence of a decimal point.
Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary
part.
Integers can be of any length, a floating-point number is accurate only up to 15 decimal places (the
16th place is inaccurate).
In [73]: a = 5
print(type(a))
<class 'int'>
In [74]: a = 5.0
print(type(a))
<class 'float'>
In [75]: a = 5 + 6j
print(a + 6)
print(type(a))
(11+6j)
<class 'complex'>
2.2.1 String
In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every
character in all languages and bring uniformity in encoding. You can learn about Unicode from
Python Unicode.
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple
quotes can be used in Python but generally used to represent multiline strings and docstrings.
In [76]: # create a string
s1 = "Χαίρετε Python"
s3 = """Χαίρετε
Python
""" # triple quotes for multiline strings and docstrings
print(s1)
print(s2)
print(s3)
print(type(s1))
print(type(s2))
print(type(s3))
Χαίρετε Python
Χαίρετε Python
Χαίρετε
Python
<class 'str'>
<class 'str'>
<class 'str'>
An escape sequence starts with a backslash and is interpreted differently. If we use a single quote
to represent a string, all the single quotes inside the string must be escaped. Similar is the case
with double quotes.
python"
python\
In [79]: # to start a new line
s = "py\nthon"
print(s)
py
thon
In [80]: s = r"C:\abc\abc\abc.txt"
print(s)
C:\abc\abc\abc.txt
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range
of items in a string by using the slicing operator :(colon).
In [81]: s = "python"
s[0]
Out[81]: 'p'
In [82]: s[1]
Out[82]: 'y'
In [83]: s[-1]
Out[83]: 'n'
In [84]: s[99]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-84-d35b3764b244> in <module>
----> 1 s[99]
In [85]: s[1.0]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-85-e1d895c8c1d6> in <module>
----> 1 s[1.0]
In [86]: # python
s[0:3]
Out[86]: 'pyt'
In [87]: # python
s[0:4:2]
Out[87]: 'pt'
In [88]: # unchangeable
s[0] = "l"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-88-38542d03ab79> in <module>
1 # unchangeable
----> 2 s[0] = "l"
Joining of two or more strings into a single one is called concatenation. The + operator does this in
Python.
The * operator can be used to repeat the string for a given number of times.
In [89]: # + operator
a = "hello"
b = "world"
print(a+b)
helloworld
In [90]: # * operator
a = "hello"
b = 2
print(a*b)
hellohello
Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace() etc.
In [91]: # split
# str.split(str1):split a string by str1
s = "python is cool"
s.split(' ')
In [92]: # replace
# str.replace(str1,str2):replace the str1 by str2
s = 'python'
s.replace('py','ABC')
Out[92]: 'ABCthon'
python
PYTHON
In [94]: # join
# str.join(iter):join the string by iter
"--".join(['python', 'is', 'cool'])
Out[94]: 'python--is--cool'
2.3 Lists
Lists are mutable sequences, typically used to store collections of homogeneous items.
[1, 2, 3]
2
[1, 2]
[1, 3]
[1, 0, 3]
In [100]: # * operator
print(a*2)
# + operator
print(a+b)
[1, 2, 3, 1, 2, 3]
[1, 2, 3, 4, 5]
In [104]: # list.pop([index=-1]): removes and returns the last item if the index is not pro
print(animals.pop()) # removes the item at index -1 and returns the left items
print(animals)
bird
['cat', 'fish', 'dog']
In [105]: # enumerate(sequence): adds counter to an iterable and returns it.
for i, x in enumerate(animals):
print(i, x)
0 cat
1 fish
2 dog
In [109]: l = [[1,3],[4,5]]
l[1][0]
Out[109]: 4
List slicing returns a slice object that can be used to slice strings, lists, tuple etc.
list[start:end:step]:
Out[110]: [0, 2, 4]
In [111]: l[1:4:2]
Out[111]: [1, 3]
2.4 Tuples
Tuples are immutable sequences, typically used to store collections of heterogeneous data (such
as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an
immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict
instance).
(obj1,obj2.....)
t1 <class 'int'>
t2 <class 'tuple'>
2
In [115]: # tuple unchangeable
t[1] = 0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-115-b8896bff046e> in <module>
1 # tuple unchangeable
----> 2 t[1] = 0
2.5 Dictionaries
A dictionary is an unordered collection of items. Each item of a dictionary has a key:value pair.The
keys within one dictionary are unique. If you store data using a key that is already in use, the old
value associated with that key is forgotten. Extracting a value using a non-existent key will cause
error.
Dictionaries are unordered, changeable and does not allow duplicates. A pair of braces creates an
empty dictionary: {}.
{key:value}
print(x)
print(x2)
print(x3)
Spam
In [118]: print(x["a"]) # report an error when extract a value using a non-existent key.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-118-759f8566e7f5> in <module>
----> 1 print(x["a"]) # report an error when extract a value using a non-existe
nt key.
KeyError: 'a'
Spam
None
cannot find a
2.6 Sets
A set is an unordered collection with no duplicate elements.
Set objects also support mathematical operations like union, intersection, difference, and
symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you
have to use set(), not {}; the latter creates an empty dictionary
{obj1, obj2,....}
{'Techs', 'Prince'}
{'Techs', 'Prince'}
False
True
In [125]: # set.add(obj): adds a given element to a set. If the element is already present,
sample_set.add('Data')
print(sample_set)
print(len(sample_set))
{'Techs', 'Prince'}
[1, 3, 5]
In [128]: sample_set = frozenset(sample_set) # unchangeable set
sample_set.add('cat')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-128-35f062032d89> in <module>
1 sample_set = frozenset(sample_set) # unchangeable set
----> 2 sample_set.add('cat')
copy.copy(x)
copy.deepcopy(x[, memo])
The difference between shallow and deep copying is only relevant for compound objects (objects
that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts
references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of
the objects found in the original.
In [131]: b[3][0]=99
print(a)
2.7.2 Operators
a+=1: 6
a-=1: 5
a*=2: 10
a/=2: 5.0
In [134]: # comparison operators
print(1>=2)
print(1<=2)
print(1!=2)
print(1==2)
False
True
True
False
Out[135]: False
Out[136]: True
Out[137]: False
Out[138]: True
In [139]: 4 not in a
Out[139]: True
print(a is b)
print(a is c)
print(a == b == c)
True
False
True
3.1 if statement
The if statement is used for conditional execution.
It selects exactly one of the suites by evaluating the expressions one by one until one is found to
be true; then that suite is executed (and no other part of the if statement is executed or evaluated).
If all expressions are false, the suite of the else clause, if present, is executed.
There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for
‘else if’, and is useful to avoid excessive indentation.
An if … elif … elif … sequence is a substitute for the switch or case statements found in other
languages.
In [145]: type(score)
Out[145]: float
In [147]: if 100>=score>=60:
print("A")
else:
print("F")
C
The conditions can be True or False. 0 and None value are also False, while the other values are
Ture.
In [149]: if 0:
print("F")
if 1:
print("T")
if "python":
print("python")
if None:
print("None")
T
python
3.2 Loops
The while statement is used for repeated execution as long as an expression is true. It's used
when we don't know the number of times to iterate beforehand.
A break statement executed in the first suite terminates the loop without executing the else
clause’s suite.
A continue statement executed in the first suite skips the rest of the suite and goes back to testing
the expression.
In [150]: i = 0
while i<9:
i+=1
print(i)
else:
print("loop ends")
1
2
3
4
5
6
7
8
9
loop ends
In [151]: i = 0
while i<9:
i+=1
if i == 3:
print("Skip this loop")
continue # skips the rest of the suite and goes back to testing the expre
print(i)
else:
print("loop ends")
1
2
Skip this loop
4
5
6
7
8
9
loop ends
In [152]: i = 0
while i<9:
i+=1
if i == 5:
print("Terminates the loop")
break # terminates the loop without executing the else clause’s suite
print(i)
else:
print("loop ends")
1
2
3
4
Terminates the loop
first
second
third
Else statement can be added in the end of for statement. It will be excused when the loop normally
ends.
first
second
third
The loop ends
1X1=1
1X2=2 2X2=4
1X3=3 2X3=6 3X3=9
1X4=4 2X4=8 3X4=12 4X4=16
1X5=5 2X5=10 3X5=15 4X5=20 5X5=25
1X6=6 2X6=12 3X6=18 4X6=24 5X6=30 6X6=36
1X7=7 2X7=14 3X7=21 4X7=28 5X7=35 6X7=42 7X7=49
1X8=8 2X8=16 3X8=24 4X8=32 5X8=40 6X8=48 7X8=56 8X8=64
1X9=9 2X9=18 3X9=27 4X9=36 5X9=45 6X9=54 7X9=63 8X9=72 9X9=81
4. Functions in Python
4.1 Functions
In addition to built-in functions, we can define our own functions by def statemesnt and lambda
statement.
func()
hello
world
positional arguments
default arguments
keyword arguments
arbitrary positional arguments
arbitrary keyword arguments
# default arguments
f()
a: 128
b: 2
args: ()
a: 0
b: 4
args: ()
In [159]: # keyword arguments
f(b=4,a=0)
a: 0
b: 4
args: ()
In [160]: '''
def f(a=128, b=2, *args, **kwargs):
print("a: %d" %(a))
print("b: %d" %(b))
print("args:",args)
for key, value in kwargs.items():
print ("%s is %s" %(key, value))
print()
'''
a: 1
b: 2
args: (3, 4, 5)
In [161]: '''
def f(a=128, b=2, *args, **kwargs):
print("a: %d" %(a))
print("b: %d" %(b))
print("args:",args)
for key, value in kwargs.items():
print ("%s is %s" %(key, value))
print()
'''
a: 128
b: 2
args: ()
cat is animal
dog is animal
cheese is food
return value
In [162]: # single return value
def func(a,b):
return a+b
a = func(2,3)
print("a:",a)
a: 5
a = func()
print("a:",a)
a: (1, 2, 3)
Define a function that takes a number as argument, and returns the fibonacci sequence. The
length of the returned sequence is decided by the argument.
fibs(5)
Out[164]: [0, 1, 1, 2, 3]
def (parameters):
return expression
a(1,2)
Out[165]: 3
(1, 'a')
(2, 'b')
(3, 'c')
In [167]: # map
print(*map(lambda x:x*x, [1,2,3]))
1 4 9
In [168]: # filter
print(*filter(lambda x: x%2==1, [1,2,3]))
1 3
In [169]: # sorted
sorted([('b',2),('a',1),('c',3),('d',4)], key=lambda x:x[1])
Code reusability
Easier to maintain
Better productivity
Easier to extend
5.1 class
Python classes provide all the standard features of Object Oriented Programming:
Encapsulation
Inheritance
Abstraction
Polymorphism
def sit(self):
print(self.name.title()+"is now sitting")
def run(self):
print(self.name.title()+"is now running")
In [171]: # instantiation
my_dog = Dog("Husky", 3)
my_dog.sit()
my_dog.run()
cat food
5.2 Encapsulation
Encapsulation can be used to hide the values of data inside an object, preventing unauthorized
parties from direct accessing them.
counter = SimpleCounter()
counter.count()
print(counter.publicCount)
100
0
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-176-1335881a4be1> in <module>
----> 1 print(counter.__secretCount) # cannot access private variable directly
5.3 Inheritance
Inheritance allows us to define a class that inherits all the methods and data from another class.
In [177]: class Parent: # parent class
parentAttr = 100
def __init__(self):
print("instantiating parent")
def parentMethod(self):
print('parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("parent attribute: ", Parent.parentAttr)
instantiating child
child method
parent method
parent attribute: 200
child says hello!
child method
5.4 Abstraction
An abstract class is a blueprint for other classes. We can create a set of methods that is required
to be created within any child classes built from the abstract class.
The main goal of abstraction is to handle complexity by hiding details from the user.
The ABC module provides the infrastructure for defining abstract base classes (ABCs) in Python.
In [179]: from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def eats_grass(self):
pass
def is_animal(self):
return True
class Cat(Animal):
def __init__(self):
print("miew~~")
# overriding abstract method
def eats_grass(self):
return False
miew = Cat()
print(miew.is_animal())
print(miew.eats_grass())
miew~~
True
False
5.5 Polymorphism
Polymorphism is the ability of an object to have many forms.
print(len([1, 2, 3, 4, 5]))
13
5
class Cat(Animal):
def sound(self):
print("miew")
class Bird(Animal):
def sound(self):
print("jiujiujiu")
class Fish(Animal):
def sound(self):
print("...")
for x in my_pets:
x.sound()
miew
jiujiujiu
...
True
True
In [ ]: