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

Lecture 3

Uploaded by

Niso Sharifzoda
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)
16 views

Lecture 3

Uploaded by

Niso Sharifzoda
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/ 21

Lecture -3

Programing in Python
Instructor : AALWAHAB DHULFIQAR Advisor : Dr. Tejfel Mate

What you will learn:


Making decisions (if statement)
loops
logic and bitwise operations
lists in Python
Functions, tuples and dictionaries
Questions and answers Comparison: equality operator

Question: are two values equal?


Fortunately, computers know only two kinds of
answers: To ask this question, you use the == (equal equal) operator.
It is a binary operator with left-sided binding. It needs two
yes, this is true; arguments and checks if they are equal.
no, this is false.
Example : A==B or A!=B

Comparison operators: greater than


How to ask python a question

Question: are two values equal?


To ask questions, Python uses a set of very You can also ask a comparison question using the > (greater than)
special operators. operator.
black_sheep > white_sheep # Greater than
Comparison operators: greater than or equal to
Priority Operator

>= (greater than or equal to). 1 +, - unary


< (less than) operator . 2 **
<= (less than or equal to) 3 *, /, //, %
4 +, - binary
5 <, <=, >, >=
Making use of the answers 6 ==, !=

Conditions and conditional execution

if a condition is met, and not do it if it isn’t.


store it in a variable make a decision
about the future of if true_or_not:
A = B == D the program do_this_if_true
if sheep_counter >= 120:
make_a_bed()
Ex:
take_a_shower()
if the_weather_is_good:
sleep_and_dream()
go_for_a_walk()
feed_the_sheepdogs()
have_lunch()
Conditional execution: the if-else statement The elif statement

if the_weather_is_good:
go_for_a_walk()
if true_or_false_condition:
elif tickets_are_available:
perform_if_condition_true
go_to_the_theater()
else:
elif table_is_available:
perform_if_condition_false
go_for_lunch()
if the_weather_is_good:
else:
if the_weather_is_good: if nice_restaurant_is_found:
play_chess_at_home()
go_for_a_walk() have_lunch()
else: else:
go_to_a_theater() eat_a_sandwich()
have_lunch() else:
if tickets_are_available:
if the_weather_is_good: go_to_the_theater()
go_for_a_walk() else:
have_fun() go_shopping()
else:
go_to_a_theater()
enjoy_the_movie()
have_lunch()
Pseudocode and introduction to loops An infinite loop

How you think when you want to write a program?


1- largest_number = -999999999 while True:
2- number = int(input()) print("I'm stuck inside a loop.")
3- if number == -1:
4- print(largest_number)
5- exit()
6- if number > largest_number: # Store the current largest number here.
7- largest_number = number largest_number = -999999999
8- # Go to line 02
# Input the first value.
number = int(input("Enter a number or type -1 to stop: "))
Looping your code with while # If the number is not equal to -1, continue.
while number != -1:
while # Is number larger than largest_number?
if number > largest_number:
conditional_expression:
while there is something to do # Yes, update largest_number.
instruction_one largest_number = number
do it
instruction_two # Input the next number.
instruction_three number = int(input("Enter a number or type -1 to stop: "))
while conditional_expression:
:
instruction
: # Print the largest number.
instruction_n print("The largest number is:", largest_number)
Looping your code with for The break and continue statements

i=0 break - exits the loop immediately, and unconditionally ends the loop's
while i < 100: operation; the program begins to execute the nearest instruction after
# do_something() the loop's body;
i += 1 continue - behaves as if the program has suddenly reached the end of
-------------------------------------------------- the body; the next turn is started and the condition expression is tested
for i in range(100): immediately.
# do_something()
pass # break - example

print("The break instruction:")


for i in range(10): for i in range(1, 6):
if i == 3:
print("The value of i is currently", i) break
print("Inside the loop.", i)
print("Outside the loop.")
for i in range(2, 8):
print("The value of i is currently", i) # continue - example
Warning ! Donot do this Example:
for i in range(1, 1): power = 1 print("\nThe continue instruction:")
print("The value of i is currently", i) for expo in range(16): for i in range(1, 6):
Or this if i == 3:
print("2 to the power of", expo, "is", power) continue
for i in range(2, 1):
power *= 2 print("Inside the loop.", i)
print("The value of i is currently", i) print("Outside the loop.")
The while loop and the else branch Computer logic

i=1 Argument A Argument B A and B


1
while i < 5: False False False
2
print(i) False True False
i += 1 3
else: 4 True False False
print("else:", i) else: 5 True True True

Argument A Argument B A or B
for i in range(5): False False False
print(i) False True True
else: 0
True False True
print("else:", i) 1
2 True True True
i = 111 3
for i in range(2, 1): 4
print(i) else: 4
else: else: 111 Argument not Argument
print("else:", i) False True
True False
Logical expressions

not (p and q) == (not p) or (not q)


not (p or q) == (not p) and (not q)

Bitwise operations (~)


Logical values vs. single bits
Argument ~ Argument
0 1
i=1 1 0
j = not not i

Bitwise operators

Bitwise operations (&, |, and ^)


Argument A Argument B A&B A|B A^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Logical vs. bit operations How to deal with single bits?

i = 15 i: 00000000000000000000000000001111 flag_register = 0x1234


j = 22 j: 00000000000000000000000000010110
flag_register = 0000000000000000000000000000x000
log = i and j logneg = not I
True False x&1=x
x&0=0 if flag_register & the_mask:
# My bit is set.
bit = i & j the_mask = 8 else:
i 00000000000000000000000000001111 # My bit is reset.
j 00000000000000000000000000010110 x|1=1
bit = i & j 00000000000000000000000000000110 x|0=x

x=x&y x &= y
x ^ 1 = ~x
x=x|y x |= y
x^0=x
x=x^y x ^= y
Binary left shift and binary right shift

var = 17
var_right = var >> 1
var_left = var << 2
print(var, var_left, var_right)
The len() function
Why do we need lists?

var1 = int(input()) The length of a list may vary during execution. New elements may be added to the list, while
var2 = int(input()) others may be removed from it. This means that the list is a very dynamic entity.
var3 = int(input())
If you want to check the list's current length, you can use a function named len() (its name
var4 = int(input()) comes from length).
var5 = int(input())
var6 = int(input()) The function takes the list's name as an argument, and returns the number of elements currently
stored inside the list (in other words - the list's length).
:
:
list is a collection of elements, but each
element is a scalar.

numbers = [10, 5, 7, 2, 1]

How do you change the value of a chosen element in the list? Negative indices are legal

numbers = [10, 5, 7, 2, 1] Removing elements from a list numbers = [111, 7, 2, 1]


del numbers[1] print(numbers[-1]) 1
numbers[0] = 111 <- indexing print(numbers[-2]) 2
numbers[1] = numbers[4] You can't access an element which
print(numbers) doesn't exist
print(numbers[0]) print(numbers[4])
print("\nList length:", len(numbers)) numbers[4] = 1
Functions vs. methods
my_list = [] # Creating an empty list.
result = function(arg)  Function
result = data.method(arg)  Method for i in range(5):
my_list.append(i + 1)

Adding elements to a list: append() and insert() print(my_list)

numbers = [111, 7, 2, 1] my_list = [10, 1, 8, 3, 5]


print(len(numbers)) total = 0
print(numbers)
### for i in range(len(my_list)):
numbers.append(4) total += my_list[i]
list.append(value)
print(len(numbers))
list.insert(location, value) print(total)
print(numbers)
###
numbers.insert(0, 222)
my_list = [10, 1, 8, 3, 5]
print(len(numbers))
length = len(my_list)
print(numbers)
for i in range(length // 2):
my_list[i], my_list[length - i - 1] = my_list[length - i - 1],
my_list[i]
print(my_list)
Sorting a list The inner life of lists

my_list = [] list_1 = [1]


swapped = True list_2 = list_1
num = int(input("How many elements do you want to sort: ")) Output = 2?
list_1[0] = 2
print(list_2)
for i in range(num):
val = float(input("Enter a list element: "))
my_list.append(val) slices

while swapped: my_list[start:end]


swapped = False
for i in range(len(my_list) - 1): # Copying the entire list.
list_1 = [1]
if my_list[i] > my_list[i + 1]:
list_2 = list_1[:]
swapped = True
list_1[0] = 2
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
print(list_2)
# Copying some part of the list. my_list = [10, 8, 6, 4, 2]
print("\nSorted:")
my_list = [10, 8, 6, 4, 2] new_list = my_list[-1:1]
print(my_list)
new_list = my_list[1:3] print(new_list)
print(new_list)
my_list = [8, 10, 6, 2, 4] my_list = [10, 8, 6, 4, 2] []
my_list.sort() new_list = my_list[1:-1]
print(my_list) print(new_list)
The in and not in operators

elem in my_list board = [[EMPTY for i in range(8)] for j in range(8)]


elem not in my_list
my_list = [0, 3, 12, 8, 2]

print(5 in my_list)
print(5 not in my_list) EMPTY = "-"
print(12 in my_list) ROOK = "ROOK"
board = []
for i in range(8):
Lists in lists row = [EMPTY for i in range(8)]
board.append(row)
row = [] board[0][0] = ROOK
for i in range(8): board[0][7] = ROOK
row.append(‘_____’) row = ["-------" for i in range(8)] board[7][0] = ROOK
print (row) board[7][7] = ROOK
print(board)

for i in board:
List comprehensive print (i)

squares = [x ** 2 for x in range(10)]


Functions: Why do we need functions?
It often happens that a particular piece of code is repeated many times in your program.
if a particular fragment of the code begins to appear in more than one place, consider the possibility of isolating it in the form
of a function

Decomposition

Your first function

def function_name():
function_body

def message():
print("Enter a value: ")
How functions work
Donot do these:

print("We start here.")


message()
print("We end here.")

def message():
print("Enter a value: ")

def message():
print("Enter a value: ")

message = 1

Parameterized functions

def function(parameter):
def message(number):
###
print("Enter a number:", number)
def message(number):
message()
print("Enter a number:", number)
Parametrized functions: Positional parameter passing
def my_function(a, b, c):
print(a, b, c)

my_function(1, 2, 3)

def introduction(first_name, last_name):


print("Hello, my name is", first_name, last_name)

introduction("Luke", "Skywalker")
introduction("Jesse", "Quick")
def message(what, number): introduction("Clark", "Kent")
print("Enter", what, "number", number)

message("telephone", 11) Keyword argument passing


message("price", 5)
message("number", "number") def introduction(first_name, last_name):
print("Hello, my name is", first_name, last_name)

introduction(first_name = "James", last_name = "Bond")


introduction(last_name = "Skywalker", first_name = "Luke")
Mixing positional and keyword arguments

positional argument passing keyword arguments


def adding(a, b, c):
print(a, "+", b, "+", c, "=", a + b + c)
adding(c = 1, a = 2, b = 3)
adding(1, 2, 3)

1+2+3=6 2+3+1=6

adding(3, c = 1, b = 2) 3+2+1=6

adding(3, a = 1, b = 2) 3+2+1=6

adding(4, 3, c = 2) TypeError: adding() got multiple values for


argument 'a'

def introduction(first_name, last_name="Smith"): introduction("James", "Doe")


introduction(first_name="William")
print("Hello, my name is", first_name, last_name)
introduction("Henry“)
Effects and results: the return instruction

return without an expression

def happy_new_year(wishes = True):


print("Three...")
print("Two...")
print("One...")
if not wishes:
return
def boring_function():
print("Happy New Year!") print("'Boredom Mode' ON.")
return 123

print("This lesson is interesting!")


happy_new_year() boring_function()
Three... happy_new_year(False) print("This lesson is boring...")
Two... Three...
One... Two...
Happy New Year! One...
None lists and functions
None is a keyword
def strange_list_fun(n):
strange_list = []
value = None
if value is None: for i in range(0, n):
print("Sorry, you don't carry any value") strange_list.insert(0, i)
[4, 3, 2, 1, 0]

TypeError: unsupported operand return strange_list


print(None + 2)
type(s) for +: 'NoneType' and 'int'
print(strange_list_fun(5))
def strange_function(n):
True
if(n % 2 == 0):
return True Functions and scopes
print(strange_function(2))
None
print(strange_function(1))

def my_function(): def scope_test():


print("Do I know that x = 123
NameError: name 'x' is not defined
variable?", var) scope_test()
var = 1 print(x)
my_function()
print(var)
the global keyword simple functions: Fibonacci numbers

global name
global name1, name2, ...
def fib(n):
if n < 1:
return None
if n < 3:
def my_function(): return 1
global var
var = 2 elem_1 = elem_2 = 1
print("Do I know that variable?", var) the_sum = 0
for i in range(3, n + 1):
the_sum = elem_1 + elem_2
var = 1 elem_1, elem_2 = elem_2, the_sum
my_function() return the_sum
print(var)

for n in range(1, 10): # testing


print(n, "->", fib(n))
See you in the Lab ☺

You might also like