0% found this document useful (0 votes)
3 views

Python Lecture Hnin

Uploaded by

info.bptrades
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Lecture Hnin

Uploaded by

info.bptrades
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Python Basic

Tr.Pwint Phyu Shwe


Updated: 03-12-2022
Outline
• Getting started with Python & Python environment

• Understanding data types & messages

• Variable Input and Output

• Maths Calculation with Python

• Selection & Repetition Structure with Python

• List and Dictionaries

• Search and Sorting Algorithms

• OOP with Python & Data Modeling


Python
• is an interpretation language
• shell is a interactive interpreter
• less code required that C, C++ or Java
• high-level data types allow you to express complex operations in a single statement;
• statement grouping is done by indentation instead of beginning and ending brackets;
• no variable or argument declarations are necessary.
Arthimetic
• same as any programming language
• multiplication used (*)
• modulus (%) for remainder
• Single division (/) for decimal quotient
• Double division (//) for integeter quotient
• type() function can be checked for each value – type (7), type (‘hello’), type (3.5)
String
• string can write with single quote or double quote ‘hello’
• string concatenation is allowed with +
• len() function to check length of string or any other data types

String literal
• triple quoted string support multiple line
• escape codes are embed when use triple quoted string
For Example
stringTest = ‘’’ Test
Susan’s car ‘’’’
escape sequence (\n, \’) is embedded.
variable name
• variable name can be letters, digit or _
• must start with letter
• some words are reserved – True, False, lamda, glboal, elif, assert, etc..
• python is case sensitive for variable name width != Width
• meaningful names are important for any programming languages
• if long variable name – practice (underscore or camel) case . For example: data_size or dataSize
print
• print function will print the information both static and dynamic.both Single or double quote can be used for
print
print (‘hello’)
print (“input’s”)
print (“Hi”, person)
• print with keyword sperator
print (“Hi”, person, ‘!’, sep = ‘ ’)

The above function will remove all blank from print function.
input-output
• direct assign to variable and ask user to enter the value for input
For example: person = input (‘enter your name’) # prompt format
print (‘hello’,person)
conversion from string input to integer
x = int(input("Enter an integer: "))
y = int(input("Enter another integer: "))
print(’The sum of ’, x, ’ and ’, y, ’ is ’, x+y, ’.’, sep=’’)

Fill in the blank


person = input(’Enter your name: ’)
greeting = ’Hello {}!’.format(person)
print(greeting)
Example
student = input("Enter the applicant’s first name: ")
subject = input("Enter the subject’s name: ")
time = input("Enter the exam time: ")
print(student + ' will sit exam for subject ' + subject + ' at ' + time +'.')
print(student, 'will sit exam for subject ', subject, 'at', time, '.', sep='')
print('{} will sit exam for subject {} at {}'.format(student, subject, time))
print('{0} will sit exam for subject {1} at {2}'.format(student, subject, time))
print (f"{student} will sit exam for subject {subject} at {time}.")
#string format method
formatStr = ’{0} + {1} = {2}; {0} * {1} = {3}.’ equations = formatStr.format(x, y, x+y, x*y)

* if braces is needed in format string then double brace is need to represent {{ }}


function
• function support single task to perform and can be called multiple times without rewriting codes
• indent defined scope of function and two line belows will exit from function as default in Python
• function can be with
• no parameter
• with parameter (s)
• with list
• return or no return value

def functionname():

functionname()
function-parameter and local scope
• parameter can be defined for function and paramter can be used as local copy
for example: def functionname(num)
accept num as paramter and calling program shall pass 1 argument when call the function
num is declared as local scope meaning outside function can’t be used ‘num’ variable. same for
anything declared inside function

def functionname():

functionname()
List Type
• Lists are ordered sequences of arbitrary data.
• List are mutable (length can be changed and elements can be substituted)
• List defined with square bracket

[’red’, ’green’, ’blue’]


[1, 3, 5, 7, 9, 11]
[’silly’, 57, ’mixed’, -23, ’example’]
[] # the empty list

Built in function range


list(range(4)) – auto generated to number starting from zero
Loop & Sequence
• For Loop
• While loop
for count in [1, 2, 3]:
print(count)
print(‘Yes’ * count)

n = int(input(’Enter the number of times to repeat: ’))


for i in range(n):
print(’This is repetitious!’)

while condition true :

print(“Result:”, s)
Dictionaries
• dictionaries is key value paired built by Python
• variable can be declared as dictionary

burglish = dict():
burglish[‘Youk p’] = ’Arrive’
burglish[‘Nay kg lar’] = “R u well’

print(burglish[‘Youk p’])
Dictionaries with string formatting

burglish = dict():
burglish[‘Youk p’] = ’Arrive’
burglish[‘Nay kg lar’] = “R u well’

print(burglish[‘Youk p’])
burglishFormat = “From burglish to english: {0},{1},{2}..”
withSubstitutions = burglishFormat.format(0 = ‘Youk p’, 1 = ‘Nay kg lar’)
print(withSubstitutions)

used object.methodname(paramters)
Dictionaries with ** notation

burglish = dict():
burglish[‘Youk p’] = ’Arrive’
burglish[‘Nay kg lar’] = “R u well’

print(burglish[‘Youk p’])
burglishFormat = “From burglish to english: {0},{1},{2}..”
withSubstitutions = burglishFormat.format(0 = ‘Youk p’, 1 = ‘Nay kg lar’)
print(withSubstitutions)

used object.methodname(paramters)
Object Oriented Programming with Python
• Python is object orientation language
• Better than Procedural language Car (class)
• objects has attributes & methods are essential part of Python wheel
• Object simplfied complex model Steering
Engine
• object is an instance of a class ( 1.. n)
roof
• Essential of OOP Inheritance, Polymorphism (many forms), Abstraction
(Define - implementation own), and Encapsulation (hide)

Forward()
Backward()
Break()
Class
Cat • classes have methods and attributes
• Class is a blueprint of objects
Attributes: • Object is an instance of class.
Color
Type class Cat(object):
pass
Methods:
Eat
brownie = Cat()
Sleep
print(brownie)
Poop
nyomi = Cat()
print (nyomi)
Data Modeling
Encapsulation This property hides unnecessary details and makes it easier to manage the program structure. Each object’s implementation
and state are hidden behind well-defined boundaries and that provides a clean and simple interface for working with them. One way to
accomplish this is by making the data private.

Inheritance Inheritance, also called generalization, allows us to capture a hierarchal relationship between classes and objects. For instance, a
cat is generalization/inheritance of animal. Inheritance is very useful from a code reuse perspective.

Abstraction This property allows us to hide the details and expose only the essential features of a concept or object. Example: knows how
function works and hide details of how it works. A person driving a scooter knows that on pressing a horn, sound is emitted, but he has no idea
about how the sound is actually generated on pressing the horn.

Polymorphism Poly-morphism means many forms. That is, a thing or action is present in different forms or ways. One good example of
polymorphism is constructor overloading in classes. For example, an animal barks but dog and cat will have different sounds.
Code Sample
#code to explain simple class Cat.EyeColor=”White” Cat (class)
class Cat(object): self.color
def getColor (self): Brownie (object 1) self.age
return self.color
self.color getColor()
def setColor (self, colorcode):
getColor() setColor(self, colorCode)
self.color = colorcode
setColor(self, brown)

Nyomi (object 2)
brownie = Cat() //instance1 self.color
brownie.setColor("brown") getColor()
print(brownie.getColor()) setColor(self, black)

nyomi = Cat() //instance2


nyomi.setColor("black")
print(nyomi.getColor())
#code to explain simple class

Init Constructor class Cat(object):


def __init__(self):
self.color = 'White'
def getColor (self):
• object initialization return self.color
• method is called as soon as object is initiated def setColor (self, colorcode):
self.color = colorcode
• initalization method can be used to initialize value while in creation stage

def __init__(self):
self.color = 'White' brownie = Cat() #instance1
brownie.setColor("brown")
print(brownie.getColor())

nyomi = Cat() #instance2


nyomi.setColor("black")
print(nyomi.getColor())

shwewar = Cat() #instance3


print(shwewar.getColor())
Attributes
• attributes can be defined inside the class as class data OR count
• attributes could be defined inside instance as instance/object data

Nyomi brownie shwewar


class SimpleCounter(object):
Age: 3 Age: 4 Age: 1
count = 0 #class attribute
def __init__(self, val):
self.val = val
SimpleCounter.count += 1 instance create
def setValue (self,newval): setvalue
getvalue
self.val = newval
getcount
def getValue (self):
return self.val
def getCount(self):
return SimpleCounter.count
Class and Instance data
• data can be stored both in class and instance
• class attirbute is accessible for all instances and data
• instance attribute is accessible from an instance

Example: SimpleCounter class


Class with method Overloading
• A function with called with different input
• Example: Animal.py
Inheritance
• code reuse
• differentiate between general class and specialize class
• when inheritance , the base class information (data/method) can be used from special class (child class)
• Parent class is called (super/base/general) class
• Child class is called (derived, sub, child) class
• Data and method that are in private hiding are not accessible from derived class
• Example: cat is animal, dog is animal, human is animal. Software engineer is employee, An Accountant is employee.
Example Employee
Name
Age
DOB
getName
getAge

Programmer Tester
Salary Hrsalary
getMonthlySalary getHrSalary
Multi-inheritance
Employee Student
Name SchoolName
counter degree
getName getter/setter
getCounter getter/setter

Programmer Tester
Salary Hrsalary
getMonthlySalary getHrSalary
Polymorphism
• Represents many forms
• Conform same function
• Implement different
• different signature, different data type could be

Dog Barks

Meows
Cat
Polymorphism with Inheritance:

Animal

Dog Cat
Encapsulation
Black Animal
Name
Age
Color
breed

Dog
type

You might also like