[go: up one dir, main page]

0% found this document useful (0 votes)
17 views35 pages

Lecture 04

python

Uploaded by

gorkemerkanli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views35 pages

Lecture 04

python

Uploaded by

gorkemerkanli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

CENG240

Programming with Python for


Engineers
Lecture 4
M. ÇAĞRI KAYA
Solution - 1
# mile-km conversion # distance calculation
miles = float(input('Miles: '))
km = miles * 1.609344 import math
print(f'Kilometers: {km:.4f}')
x1 = int(input('X1: '))
y1 = int(input('Y1: '))
# Fahrenheit to Celsius conversion x2 = int(input('X2: '))
y2 = int(input('Y2: '))
temp_f = float(input("F: "))
temp_c = (temp_f - 32) * 5/9 distance =
print(f'C: {temp_c:.2f}') math.sqrt((x2-x1)**2 + (y2-y1)**2)
print(f'Distance = {distance:.2f}')

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 2


Solution - 2
# input seconds, output hh:mm:ss

seconds = int(input('seconds: '))


h = seconds // 3600
remainder = seconds % 3600
m = remainder // 60
s = remainder % 60

print(f'{h}:{m}:{s}')

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 3


Outline
Dive into Python
 Basic data types.
 Basic operations and expression evaluation.
 Precedence and associativity.
 Variables and how to name them.
 Aliasing problem.
 Container types.
 Accessing elements of a container type (indexing, negative indexing, slicing).
 Basic I/O.
 Commenting your codes.
 Using libraries.

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 4


Actions in an algorithm
Each action can serve two broad purposes:
 Creating and modifying data
 sequential, conditional or repetitive execution on the data, and produce other data
 Interacting with the environment
 input/output operations with the user or peripherals

Irrespective of its purpose, an action can be of two types:


 Expression
An expression (e.g. 3 + 4 * 5) specifies a calculation, which, when evaluated (performed), yields some data as a result.
An expression can consist of:
 basic data (integer, floating point, boolean etc.) or container data (e.g. string, list, set etc.).
 expressions involving operations among data and other expressions
 functions acting on expressions

 Statement
Unlike expressions, a statement does not return data as a result
 Basic: e.g. storing the value of an expression, deleting an item from a collection of data
 Compound: composed of other statements

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 5


Basic Data - Numbers
 Integers: whole numbers, without decimal points 73, -5 , 73.0 X
 Floating points (Floats): numbers which have decimal points 1.5 , -8 X, 4.36e-8 
 Complex numbers: Real (Integer/Float) + Imaginary (represented by j) -> 1.5 – 2.6j where j is −1

 Use type() function to check types.


 Integer size is limited on the available memory. Float type has the following range per 64-bit IEEE754 standard:
[2.2250738585072014E-308, 1.7976931348623157E+308]
 abs(<Number>) -> Takes the absolute value of the number.
 pow(<Number1>, <Number2>) -> e.g. pow(2, 3): 23
 round(<FloatNumber>)-> rounds to the closest integer.
 Functions from the math library: sqrt(), sin(), cos(), log() ….

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 6


Basic Data - Boolean
 Python provides the bool data type which allows only two values: True and False

 Some notations are interpreted as False:


 0 (the integer zero)
 0.0 (the floating point zero)
 "" (the empty string)
 [] (the empty list)
 {} (the empty dictionary or set)

 and, or, not

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 7


Container data
Many world problems need more specialized solutions: Vectors, Matrices, Ordered and
unordered sets, Graphs, Trees
Python provides five container types:
 String (str): A single character or a sequence of characters
 List (list): Ordered set of all data types (including other lists)
 Tuple (tuple): similar to the list
 Dictionary (dict): maps numbers/booleans/strings to any set of data
Querying an element from dictionary is almost in constant time (hash table)
 Set (set): sets in math, element order is undefined

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 8


Container data cont.
 String, List, Tuple: sequential containers (s-containers). They consist of consecutive elements
indexed by integer values starting at 0
 Dictionary: element indexes are arbitrary
 Mutability: adding new elements, changing and deleting existing ones is possible
 Strings, Tuples are immutable
 Lists, Dictionaries, and Sets are mutable

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 9


Accessing elements in s-containers
 All containers except set reveal their individual elements by an indexing mechanism with
brackets
container_name[index]
 For s-containers: the index is an ordinal number starting from 0.
 Negative index: starting from the end

 Slicing
 Accessing multiple elements at once,

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 10


Container operations
 len() -> number of elements
 + operator -> concatenation for string, tuple, and list
 * operator -> repetition for string tuple, and list
 in and not in -> checks membership for all containers

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 11


String
A container where each element is a character.
Python does not have a special representation for a single character. Characters are represented
externally as strings containing a single character only.
"Hello World!"

'Hello World!'

'He said: "Hello World!" and walked towards the house.'

"A"

""" Andrew said: "Come here, doggy".


The dog barked in reply: 'woof' """

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 12


String- cont.
The backslash (\) is a special character in Python strings, also known as the escape character. It
is used in representing certain, the so called, unprintable characters: (\t) is a tab, (\n) is a
newline, and (\r) is a carriage return.
'It\'s raining' Deletion and insertion
>>> a = 'Python'
"\"hello\"“
>>> a[0] = 'S'
An attempt to change a string character will fail. Traceback (most recent call
last):
File "<stdin>", line 1, in
>>> str(4) Evaluate a string that contains an <module>
'4' expression: TypeError: 'str' object does
>>> str(5.45) >>> s = '3 + 4' not support item assignment
'5.45' >>> eval(s) >>> b = 'S' + a[1:]
7 >>> b
'Sython'

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 13


List and Tuple
Both are sequential containers and can contain any other data type (including other lists and
tuples.)
The difference is that lists are mutable whereas tuples are immutable.
[[1,-1,0],[2,-3.5,1.1]]
("abx",[1.32,-5.12],-0.11)
[("list", "can"), ("contain", "tuple members")]
(["tuple", "can"], ["contain", "list members"])
Lists are preferred more since they are mutable.

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 14


Operations on lists and tuples - deletion
Assigning an empty list to the slice that is going to
be removed:

>>> L = [111,222,333,444,555,666]
>>> L[1:5] = []
>>> print(L)
[111, 666]

Using the del statement on the slice that is going


to be removed:

>>> L = [111,222,333,444,555,666]
>>> del L[1:5]
>>> print(L)
[111, 666]

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 15


Operations on lists and tuples - insertion
Using assignment with a degenerate use of slicing:

>>> L = [111,222,333,444,555,666] The third methods uses the append() method


>>> L[2:2] = [888,999] to insert an element only to the end or
>>> print(L) extend() to append more than one element
[111, 222, 888, 999, 333, 444, 555, 666] to the end:

>>> L = [111,222,333,444,555,666] >>> L = [111,222,333,444,555]


>>> L.insert(2, 999) >>> L.append(666)
>>> print(L) >>> print(L)
[111, 222, 999, 333, 444, 555, 666] [111, 222, 333, 444, 555, 666]
>>> L.extend([777, 888])
where the insert function takes two parameters: The first [111, 222, 333, 444, 555, 666,
parameter is the index where the item will be inserted and 777, 888]
the second parameter is the item to be inserted.

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 16


Operations on lists and tuples - cont.
Data creation with list() and tuple() -> from other data types

Concatenation and repetition with lists and tuples: Similar to strings, + and * operators can be used

Membership via in and not in: similar to strings

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 17


Example: Matrices as nested lists
>>> A = [[3, 4, 1], [-3, 3, 5], [1, 1, 1]]
>>> A
[[3, 4, 1], [-3, 3, 5], [1, 1, 1]]
3 4 1
0, 0 0, 1 0, 2
>>> A[1]
[-3, 3, 5]
-3 3 5
1, 0 1, 1 1,2
>>> A[1][0]
-3 1 1 1
2, 0 2, 1 2, 2

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 18


Dictionary
Dictionary is a container data type where accessing items can be performed with indexes that
are not numerical: keys.
A dictionary is a mapping from keys to values.

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 19


Dictionary cont.
d = {34:"istanbul",
58:"sivas",
"istanbul":[[7,"tepeli","sehir"],(41.0383,28.9703),34,15.5e6],
"murtaza abi":"sivas",
("ahmet",(8,14)):"almanya","james bond":7,
("ahmet",(1,6)):["anne","anneanne"],
("ahmet",7):"sivas",
"karsiyaka":35.5}

>>> print(d["karsiyaka"])
35.5

>>> print(d["ankara"]) >>> print("ankara" in d)


KeyError:'ankara' False

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 20


Set
Sets are created by enclosing elements into a pair of curly-braces and separating them with
commas. Any immutable data type, namely a number, a string or a tuple, can be an element of a
set. Mutable data types (lists, dictionaries) cannot be elements of a set. Being mutable,
sets cannot be elements of a sets.
a = {1,2,3,4} >>> s = frozenset({1, 2, 3})
b = {4,3,4,1,2,1,1,1} >>> print(s)
print (a == b) frozenset({1, 2, 3})
a.add(9)
a.remove(1) Being immutable, frozensets can be a
print(a) member of a set or a frozenset.

True
{2, 3, 4, 9}

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 21


Set operations
S1 <= S2: True if S1 is a subset of S2.

S1 >= S2: True if S1 is a superset of S2.

S1 | S2: Union of the sets (equivalent to S1.union(S2)).

S1 & S2: Intersection of the sets (equivalent to S1.intersection(S2)).

S1 - S2: Set difference (equivalent to S1.difference(S2)).

The following are only applicable with sets (and not with forezensets):
S.add(element): Add a new element to the set.

S.remove(element): Remove element from the set.

S.pop(): Remove an arbitrary element from the set.

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 22


Expressions
 Expressions, such as 3 + 4, describe calculation of an operation among data. When an
expression is evaluated, the operations in the expression are applied on the data, and a resulting
value is provided.

3 +4 3, 4 are operands, + operator (binary)


not is a unary operator
[ ] -> indexing operator

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 23


Precedence and associativity

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 24


Implicit and Explicit Type Conversion
When you apply a binary operator on items of two different data types, it tries to convert one
data to another one if possible. This is called implicit type conversion.
>>> 3+4.5
7.5 float 3.0
>>> 3 + True
4 integer 1
>>> 3 + False
3 integer 0
It is a good programming practice to make these conversions explicit and make the intention
clear to the reader. Explicit type conversion, also called as type casting
>>> str(34)
'34'
>>> list('34')
['3', '4']

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 25


Assignment Statement and Variables
Action semantics of the assignment statement:
1- The Expression is evaluated.
2- If the Variable does not exist, it is created.
3- The evaluation result is stored into the Variable (overwrites former value).

#Multiple assignment #Swapping values #Swapping


#Tuple matching >>> print(a, b) #Tuple matching
>>> a = b = 4 3 4 >>> print(a,b)
>>> a, b = 3, 4 >>> temp = a 3 4
>>> (a, b) = (3, 4) >>> a = b >>> a,b = b,a
>>> [a, b] = [3, 4] >>> b = temp >>> print(a,b)
>>> print(a, b) 4 3
4 3

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 26


Variables & Aliasing
print("address of 5: ", id(5)) a = [5,1,7]
a = 5 b = a
print("address of a: ", id(a)) print("addresses of a and b: ", id(a), id(b))
b = a print("b is: ", b)
print("address of b: ", id(b)) a[0] = 3
a = 3 print("addresses of a and b: ", id(a), id(b))
print("address of a: ", id(a)) print("b is: ", b)
print("b is: ", b)
addresses of a and b: 4414272384 4414272384
address of 5: 4380465840 b is: [5, 1, 7]
address of a: 4380465840 addresses of a and b: 4414272384 4414272384
address of b: 4380465840 b is: [3, 1, 7]
address of a: 4380465776
b is: 5 …
a = [3, -1]

addresses of a and b: 4414271936 4411372864

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 27


Naming variables
◦ Must start with a letter or underscore
◦ Variable name should indicate the content.
◦ a = b * c  salary = hours_worked * hourly_pay_rate

◦ Use i, j, k, m, n for counting only: Programmers implicitly recognize them as integer holding
(the historical reason for this dates to 60 years ago).
◦ Use x, y, z for coordinate values or multi-variate function arguments.
◦ If you are going to use multiple words for a variable, choose one of
these:
◦ Put all words into lowercase, affix them using _ as separator (e.g. highest_midterm_grade,
shortest_path_distance_up_to_now).
◦ Put all words but the first into first-capitalized-case, put the first one into lowercase, affix them
without using any separator (e.g. highestMidtermGrade,
shortestPathDistanceUpToNow).
◦ You cannot use reserved words, such as and, def from, is, continue, print…

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 28


Compound Statements
Python provides statements combining many statements as their parts. Two examples are
conditional and repetitive

if <boolean- while <boolean-


expression>: condition>:
statement-true-1 statement-true-1
statement-true-2 statement-true-2
... ...
else:
statement-false-1
statement-false-2
...

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 29


Actions for input/output
>>> s = input("Now enter your text: ")
Now enter your text: This is the text I entered
>>> print(s)
This is the text I entered

>>> age = 20
>>> height = 1.70
>>> eye_color = "brown"
>>> print(f"I am {height} tall, {age} years old and have {eye_color} eyes")
I am 1.7 tall, 20 years old and have brown eyes

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 30


Ignored actions
# Comments if <condition>:
>>> 3 + 4 # We are adding two numbers here pass # @TODO
fill this part
7 else:
""" statement-1
statement-2
This is a multi-line comment. ...
We are flexible with the number of lines &
characters,
spacing. Python
will ignore them.
"""

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 31


Actions and data packaged in libraries
>>> import math as m
>>> m.sin(m.pi)
1.2246467991473532e-16

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 32


Exercise - 1
Given the list below, do the specified operations in Python.
my_list = [4, 11, 3, 45, 5, 1, 7, 0, 1, 1, 17]
 insert 23 after 45
 reverse the order of the list
 count the number of occurrences of 1, and print
 remove 0
 sort the list (ascending order)
 print the number of elements in the list
 remove 45
 print the list

you may use the following methods: index(), insert(), reverse(), count(), remove(), sort(), len()

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 33


Exercise - 2
Given the cutomer_data dictionary, do the following operations:
customer_data = {

'name': "alexandra",

'age': 29,

'is_premium_member': True

 read a key from the user and print the corresponding value
 add a new entry with the 'orders' key which is a list of tuples that contains ordered items
and their prices, e.g. [('pen', 10) , ('book', 15)]
 update the value of age

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 34


Thank You!
QUESTIONS?

M. ÇAĞRI KAYA - LECTURE 4 - DIVE INTO PYTHON 35

You might also like