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

Lecture 3

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

Lecture 3

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

• d.

keys()
• d.values()
• d.items()
• del(d)
• d.clear()
• del d[‘key’]
Tuples
Tuples are very similar to lists. However they have one key difference -
immutability.
Once an element is inside a tuple, it can not be reassigned.
Tuples use parenthesis: (1,2,3)
A Python tuple consists of a number of values separated by commas.
Unlike lists, however, tuples are enclosed within parentheses.
• cannot be updated. Tuples can be thought of as read-only lists
• len(t)
• type(t)
• # Use .index to enter a value and return the index
• t.index('one')
• # Use .count to count the number of times a value appears
• t.count('one')
• t[0]= 'change‘ ((Immutability))
• del t
• max(t)
• min(t)
• t.append('nope') ((AttributeError ))
Sets
Sets are unordered collections of unique elements.
Meaning there can only be one representative of the same object.
• x = set()
• # We add to sets with the add() method
• x.add(1)
• x.add(1)
• # Create a list with repeats
• list1 = [1,1,2,2,3,4,5,6,1,1]
• # Cast as set to get unique values
• set(list1)
Python Data Type Conversion

• Sometimes, you may need to perform conversions between the built-in


data types. To convert data between different Python data types, you
simply use the type name as a function.
• b = int(2.2)
• a = float(1)
• b = str(2.2)
• tuple(s)
• list(s)
• set(s)
• dict(d)
Types of Python Operators

Python language supports the following types of operators.


• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Arithmetic Operators
Python Comparison Operators
Python Assignment Operators
Python Logical Operators
Python Membership Operators
Python Bitwise Operators
• a = 0011 1100
• b = 0000 1101
• --------------------------
• a&b = 12 (0000 1100)
• a|b = 61 (0011 1101)
• a^b = 49 (0011 0001)
• ~a = -61 (1100 0011)
• a << 2 = 240 (1111 0000)
• a>>2 = 15 (0000 1111)
Decision Making

• We often only want certain code to execute when a particular


condition has been met.
● To control this flow of logic we use some keywords:
○ if
○ elif
○ else
• Control Flow syntax makes use of colons and indentation
(whitespace).
• This indentation system is crucial to Python.
If, elif , else Statements
● Syntax of an if statement
if some_condition:
# execute some code

● Syntax of an if/else statement


if some_condition:
# execute some code
else:
# do something else
● Syntax of an if/else statement
if some_condition:
# execute some code
elif some_other_condition:
# do something different
else:
# do something else
Loops

• statements are executed sequentially: The first statement in a


function is executed first, followed by the second, and so on. There
may be a situation when you need to execute a block of code several
number of times.
For Loops
• Many objects in Python are “iterable”, meaning we can iterate over every
element in the object.
• Such as every element in a list or every character in a string.
• We can use for loops to execute a block of code for every iteration.
● Syntax of a for loop
my_iterable = [1,2,3]
for item_name in my_iterable:
print(item_name)
>> 1
>> 2
>> 3
list1 = [1,2,3,4,5,6,7,8,9,10]
for num in list1:
print(num)
-----------------------------------
for num in list1:
if num % 2 == 0:
print(num)
else:
print('Odd number')
-------------------------------------------
# Start sum at zero
list_sum = 0
for num in list1:
list_sum = list_sum + num
print(list_sum)
While Loops
• While loops will continue to execute a block of code while some
condition remains True.
● Syntax of a while loop
while some_boolean_condition: #do
something
● You can combine with an else if you want
while some_boolean_condition: #do
something
else:
#do something different
x=0

while x < 10:


print('x is currently: ',x)
print(' x is still less than 10, adding 1 to x')
x+=1
Loop Control Statements

• Loop control statements change execution from its normal sequence.


example
S= 'This is a string.'
for letter in S:
print(letter)
-----------------------------------
S= 'This is a string.'
for letter in S:
pass
------------------------------------
S= 'This is a string.'
for letter in S:
if letter==‘i’:
continue
print(letter)
-------------------------------------
S= 'This is a string.'
for letter in S:
if letter==‘i’:
break
print(letter)
Useful Operators

• Range
• The range function allows you to quickly generate a list of integers,
There are 3 parameters you can pass, a start, a stop, and a step size.
Let's see some examples:
• list(range(0,11))
Zip
• We can use the zip() function to quickly create a list of tuples by
"zipping" up together two lists.
• mylist1 = [1,2,3,4,5]
• mylist2 = ['a','b','c','d','e']
• list(zip(mylist1,mylist2))
• enumerate
index_count = 0
for letter in 'abcde':
print("At index {} the letter is {}".format(index_count,letter))
index_count += 1
---------------------------------------------------------------------------------
for i,letter in enumerate('abcde'):
print("At index {} the letter is {}".format(i,letter))
• in operator
• we can also use it to quickly check if an object is in a list
• 'x' in ['x','y','z']
• not in
• We can combine in with a not operator, to check if some object or
variable is not present in a list.
• 'x' not in ['x','y','z']
• min and max
• Quickly check the minimum or maximum of a list with these
functions.
• mylist = [10,20,30,40,100]
• min(mylist)
• max(mylist)
• random
• Python comes with a built in random library. There are a lot of
functions included in this random library, so we will only show you
two useful functions for now.
from random import shuffle
shuffle(mylist)
from random import randint
randint(0,100)
List Comprehensions

mystring="Hello Word!"
List1=[]
for x in mystring:
List1.append(x)
print(List1)
-----------------------------------------------------------
mystring="Hello Word!"
mylist=[x for x in mystring ]
print (mylist)
-----------------------------------------------------------
mylist=[x**2 for x in range(1,20) ]
print (mylist)
If condition exercise
• SI, Metric Units:
• BMI = weight(kg)/height2 (m)
• BMI Categories:
Underweight = <18.5
Normal weight = 18.5–24.9
Overweight = 25–29.9
Obesity = BMI of 30 or greater
Test
• Use range() to print all the even numbers from 0 to 10.

• Use a List Comprehension to create a list of all numbers between 1


and 50 that are divisible by 3.
• Use List Comprehension to create a list of the first letters of every
word in the string below:
• st = 'Create a list of the first letters of every word in this string'
• Go through the string below and if the length of a word is even print
"even!“
• st = 'Print every word in this sentence that has an even number of
letters'
Use for, .split(), and if to create a Statement that will print
out words that start with 's':
st = 'Print only the words that start with s in this sentence'
Write a program that prints the integers from 1 to 100.
But for multiples of three print "Fizz" instead of the number,
and for the multiples of five print "Buzz". For numbers
which are multiples of both three and five print "FizzBuzz".
• Write a program to enter a number of two digit like (62) then it will
get the summation of the two digit (6+2)? And print the result
• Write a program to ask for your age then it is going to calculate how
many days and months and weeks are there until you reach to the age
of 90?
• Hints :
• Year =360days
• 12 months
• 52 weeks
Leap Year

• Write a program that works out whether if a given year is a leap year.
A normal year has 365 days, leap years have 366, with an extra day in
February. The reason why we have leap years is really fascinating, This
is how you work out whether if a particular year is a leap year.
• on every year that is evenly divisible by 4
• **except** every year that is evenly divisible by 100
• **unless** the year is also evenly divisible by 400
Leap Year

• e.g. The year 2000:


• 2000 ÷ 4 = 500 (Leap)
• 2000 ÷ 100 = 20 (Not Leap)
• 2000 ÷ 400 = 5 (Leap!)
• So the year 2000 is a leap year.
• But the year 2100 is not a leap year because:
• 2100 ÷ 4 = 525 (Leap)
• 2100 ÷ 100 = 21 (Not Leap)
• 2100 ÷ 400 = 5.25 (Not Leap)

You might also like