Debre Berhan University
College of Computing
Department of Software Engineering
Principles of Programming
Chapter One
Python Basics
By Girmachew Gulint
girmachewabebe@gmail.com
Nov 2017 E.C
Contents
Turtle Graphics
Programming tokens
Programming
1.2 1.4
1.1 1.3 1.5
Why programming in Python? Conditionals and loops
2
Learning outcomes
➢ Understand basic programming concepts
➢ Identify syntax and semantics of programming tokens
➢ Solve problems by writing program in python CLI and Turtle GUI
➢ Debugging simple python program
➢ Test simple programs of python
3
1.1 Programming
➢ Computer has two main components; hardware and software
➢ Software is set of instructions used to interact to the computer. This set of
instruction is also called program.
➢ This set of instructions written by programmers to solve a problem. This
activity is called as programming. So, programming mean writing well
organized set of instruction to solve a problem.
➢ To write a program programming languages to be used. One of them is
python
➢ It is all about syntax and semantics
4
Continued
keyWord, starting, spaces and ending of programming tokens must be appropriate to follow the syntax
unless syntax error will happen. here are some syntax and semantics rules
● Opened bracket must be closed by corresponding one
● Opened quotes must be closed with the same type
● For numeric data quotes are not necessary
● If, elif, else, function and class start with colon(:)
● Indentation keep when needed
● Initialization variables before trying to use
● Define function before trying to call
● Create an object before trying to use
● Type of operator used must appropriate for data
5
1.1.2 Understanding a problem
● Using tools
● ERD
● Flow Chart Domain knowledge
understanding
● DFD
● UML
● PSEUDOCODE
● Algorithm
6
1.2 Why python?
➢ It is high-level general purpose programming language
➢ It has so many powerful standard and third-party libraries
➢ It has simple and readable syntax
➢ It is cross platform and compatible
➢ It is beginner friendly
➢ It is can be integrate with other languages
➢ It has large community and support
➢ It is compatible with may database softwares
➢ It is versatile and flexible :
○ ML
○ DS
○ AI
○ Web development
○ NLP
○ Game Development
○ Desktop application
7
1.2.1 How python interpreter interpret source code?
● Python interpreter is written by c programming language
● Here are the steps how python code runs
● Lexical analysis: tokens
● Parsing: Abstract Syntax Tree
● Compilation: bytecode
● Execution
8
1.3 Programming tokens
➢ Symbols
➢ Keywords
➢ Variables
➢ Constant
➢ Data types
➢ Comment
➢ Input/output
➢ Operators
➢ Conditionals
➢ Loops
➢ Functions
➢ Class
➢ Module
➢ packages
9
1.3.1 Symbols
+ - * / > < ,
() {} [] ** // >= =
=/ +/ : =* =- ! ==
<= := -> . @ # &
| ^ % _ ~ ““ ‘‘
>> << \t \r \n … :=
10
1.3.2 Keywords/Reserved words
def import while and None
class if in or as
self elif not from raise
try else True return match
except for False pass case
break continue lamda yield global
nonlocal with finally assert
11
1.3.3 Variables/ Identifiers
➢ Storage
➢ Mutable/Override
➢ Case sensitive
➢ Naming Convention
➢ Initialization
➢ scope
12
Variable initialization/literals
X = 90 # no semicolon is needed at the end of the statement
name = ”Samuael” # string variables must be in quote either in single quote or double quote
age = 25 # integer variables must initialize without quote
weight = 65.5 # float variables must initialize without quote
height = 1.72
X = 70 # change the value of X to 70 since variable is mutable
Apple = 90
apple = 80 They are different because variables are case sensitive
13
Multiple variables initialization in a line
a, b, c = 3, 4, 6 # different values initialization in a line
a = 3, b = 4, c = 6 # invalid syntax
z=x=y = 10 # the same value initialization in a line
z, x, y =10 # invalid syntax
user1, user2 = “Admin”,”Student”
14
Sequence variables initialization
list1 = [10, 20, 30] # A list containing integers
list2 = ['10', 20, 30] # A list containing a string and integers
tuple1 = (20, 30, 60) # A tuple containing integers
set1 = {5, 6, 7} # A set containing unique integers
dict1 = {"name": "Samuel", "age": 25} # A dictionary with key-value pairs
numbers = range(5) # A range object from 0 to 4
15
Sequence variables initialization with constructors and empty
list1 = [] # An empty list
list2 = list() # An empty list using the list() constructor
tuple1 = () # An empty tuple
set1 = set() # An empty set (using the set() constructor)
dict1 = {} # An empty dictionary (using curly braces)
numbers = range(0) # An empty range (from 0 to 0)
16
1.3.4 Constant
In python constant values also mutable, however by convention it is written in
capital letters
PI = 3.14
GRAVITY = 9.8
17
1.3.5 Data Types
➢ Numeric: int, float, complex
Objects
➢ String - Properties
➢ Boolean: bool - Methods
➢ Binary: bytes, bytearray, memoryview
➢ Sequence : list, tuple, range
➢ Set:set, frozenset
➢ Dictionary / map
➢ None Annotation
➢ Class
➢ Date 📅
18
Know type of variables type()
# Different data types and using type() to check their types
print(type([1, 2, 3])) # <class 'list'>
print(type((1, 2, 3))) # <class 'tuple'>
print(type({1, 2, 3})) # <class 'set'>
print(type({"name": "Samuael"})) # <class 'dict'>
print(type("Hello")) # <class 'str'>
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(range(5))) # <class 'range'>
19
1.3.6 Comment
➢ #
➢ ‘’ “
➢ ‘’
➢ ‘’’ ‘’’
➢ “”” “””
20
1.3.7 Input/Output
➢ input()
➢ print()
21
Print output
print(“Hello World”) # print is polymorphism function
print(23) # to print numeric data or
greeting =”Good morning”
print(greeting)# variable value no need to use quotation mark
22
Conti…
23
Formatting Output
➢ f-string
➢ placeholder
24
Input
25
Multiple inputs
➢ split() function with input()
26
Casting input
➢ int()
➢ float()
➢ complex()
➢ bool()
➢ set()
➢ list()
➢ tuple()
➢ frozenset()
➢ datetime.strptime()
➢ enumerate()
27
Cont… input number
28
Cont…
29
1.3.8 Operators/symbols
1. Assignment: [ =, +=,-=,/=,*=]
2. Arithmetic: [+,-,/,*,//,%,**]
3. Relational or Comparison: [<,>,<=,>=,==,!=]
4. Logical: [and, or, not]
5. Bitwise: [&,|,~,^,>>,<<]
6. Membership: [in, not in]
7. Identity: [is, is not]
8. Ternary
9. Lamda
10. Warlus
11. Null-Coalescing: result = value if value is not None else "Default Value"
30
1.3.8.1 Assignment operators
x = 10
x += 5 # x = x + 5 (Add)
x -= 3 # x = x - 3 (Subtract)
x *= 2 # x = x * 2 (Multiply)
x /= 4 # x = x / 4 (Divide)
x %= 3 # x = x % 3 (Modulo)
x //= 2 # x = x // 2 (Floor division)
x **= 3 # x = x ** 3 (Exponentiation)
print(x) # Result after all operations
31
1.3.8.2 Arithmetic operators
➢ Samuael’s principle of programming course
assessments results are 9, 19, 30 and 38
quiz, individual project, group project and
final exam respectively.
➢ How much is his total score out of 100?
32
1.3.8.3 Relational/ Comparison operators
➢ Mr X is 25 years old and Mr Y is 30 years old.
➢ Write a python code snippet to check Mr X is younger than Mr Y
33
1.3.8.4 Logical operators
➢ Write python code snippet to determine whether they set on final
exam or not based on the attendance. If attendance is less than
85% he/she is not allowed to set else can set on final exam.
➢ Write python code snippet to check username and password is
match or not.
➢ Write python code to check a passenger identification is
passport or kebele ID.
34
1.3.8.5 Bitwise operators
➢ And (&)
➢ or(|)
➢ XOR(^)
➢ Not(~)
➢ Shift to the left (<<)
➢ Shift to the right (>>)
35
1.3.8.6 Membership operators
➢ in: This operator checks if a value exists in a sequence.
➢ not in: This operator checks if a value does not exist
in a sequence.
➢ Syntax:
➢ value in sequence
➢ value not in sequence
➢ in: Returns True if the value is found in the sequence,
otherwise it returns False.
➢ not in: Returns True if the value is not found in the sequence,
otherwise it returns False.
36
1.3.8.7 Identity operators
➢ The identity operators are is and is not.
➢ They are used to compare the memory locations of two objects, not their
values.
37
1.3.8.8 Ternary operator
➢ The ternary operator in Python is a one-liner shorthand for
an if-else statement.
➢ It allows you to assign a value based on a condition in a
concise way
➢ syntax
<variable> = <true_value> if <condition> else <false_value>
38
1.3.8.9 lambda
➢ function is a small anonymous function defined with the lambda keyword. It
can have any number of arguments but only one expression.
➢ The expression is evaluated and returned.
➢ Syntax
variable = lambda argument/s : expression
39
1.3.8.10 Walrus
➢ Kind of assignment expression
➢ walrus operator in Python, which is represented by :=
➢ This operator allows you to assign a value to a variable as part of an
expression.
➢ Used to write short code for repeated tasks
40
1.3.8.11 Null-Coalescing
➢ In Python, the concept of null-coalescing is not directly available as a built-in
operator like in some other languages (e.g., ?? in C#).
➢ However, it can achieve similar functionality using the or operator or the
if-else expression.
➢ The null-coalescing operator is used to provide a default value if the original
value is None or evaluates to False.
41
Examples
42
1.3.9 Operators Precedence
1. Parentheses ()
2. Exponentiation **
3. Unary plus and minus, Bitwise NOT +x, -x, ~x
4. Multiplication, Division, Floor division, Modulo *, /, //, %
5. Addition, Subtraction +, -
6. Bitwise shifts <<, >>
7. Bitwise AND &
8. Bitwise XOR ^
9. Bitwise OR |
10. Comparison operators <, >, <=, >=, ==, !=
11. Logical NOT not
12. Logical AND and
13. Logical OR or
43
1.3.10 string manipulation
➢ string in python is a character or sequence of characters in quotation mark
➢ Single, double or triple quote is allowed to create string
➢ Output by concatenation, placeholder and format
44
String data manipulation
➢ Concatenate by *
➢ Access by index
➢ Immutability
➢ Check by in keyword
➢ Loop through it
45
Cont …
➢ Comparison
46
String built-in methods
➢ .upper()
➢ .lower()
➢ .capitalize() and other built-in methods
➢ They are important in string manipulation
47
Escape characters
➢ To insert illegal character
48
Cont…
➢ \’ remove the error
49
Cont…
Escape character description
\\ backslash(\)
\’ Single quote(‘)
\” Double quote(“)
\n New line
\t tab
\b backspace
\r Carriage return
\ooo Character with octal value with ‘ooo’
\xhh Character with hexal value ‘hh’
50
Cont…
51
1.4.1 Conditionals start
➢ Branching and dynamic decision making techniques
➢ Based on the condition/state operate different functions
➢ if
➢ if else
➢ if elif elif elif elif elif else Cond
○ elif can be as many as you want
false ition
➢ Indentation and colon(:) true
○ make branching syntax to be correct
➢ With Logical operators can make complex condition
➢ Match
End
52
if condition 1:
Syntax
# true block
elif condition 2:
# true block
elif condition 3:
if condition: if condition:
# true block
# true block # true block elif condition n:
else: # true block
else:
# false block
# false block
53
example
if x > 0: if x > 0:
print(x, “ is positive number”) print(x, “ is positive number”)
else:
print(x, “is negative number)
54
Example 2
if …elif…elif…else
55
Nested if syntax
Example 1
if condition 1:
If condition 2:
# true block
else:#optional
# false block
56
Example 2
57
Multiple if
if condition:
# body These if statements have no dependency
if condition:
# body
if condition:
# body
58
match
Match command:
case “expression 1”:
#body
case “expression 2”:
#body
case “expression n”:
#body
case _:
#body
59
1.4.2 Loops/Iterations
➢ Used to perform repeated tasks with a short code size
➢ For and while are two kind of loops in python
➢ They are important to manipulate sequences like list, set, range and
dictionary
➢
60
Conti…
Flow chart
False
True
61
For loop syntax
for expression in sequence:
# operation/s
62
While loop
➢ It execute code until condition get false
➢ syntax
while condition:
# operation/s
63
exercises
1. Write python code to calculate electric billing
2. Write python code to identify a letter as vowel or consonant
3. Write python code to calculate net salary
64