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

Python Lect 2

Introduction to Python programming -02

Uploaded by

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

Python Lect 2

Introduction to Python programming -02

Uploaded by

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

Python Basics

Cont…
ITC
CBS
While Loop (Indefinite Loop)
• Flow of Execution:

• Evaluate the condition, yielding True or False.


• If the condition is false, exit the while statement and continue
execution at the next statement.
• If the condition is true, execute the body and then go back to step 1.
While Loop Cont…
• Example: a simple program that counts down from five and then says
“While loop!“
• n=5
while n > 0:
print(n)
n=n–1
print(‘While loop!’)
• You can almost read the while statement as if it were English. It
means, "While n is greater than 0, display the value of n and then
reduce the value of n by 1. When you get to 0, exit the while
statement and display the word while loop!"
Infinite Loops
• Sometimes you don't know it's time to end a loop until you get half
way through the body. In that case you can write an infinite loop on
purpose and then use the break statement to jump out of the loop.
Infinite loops Cont…
• For example, suppose you want to take input from the user until they
type done. You could write:
• while True:
line = input('> ‘)
if line == 'done’:
break
print(line)
print('Done!')
• The loop condition is True, which is always true, so the loop runs
repeatedly until it hits the break statement.
Infinite loops Cont…
• Here is another example of a loop that copies its input until the user
types "done", but treats lines that start with the hash character as
lines not to be printed.
• while True:
line = input('> ‘)
if line[0] == '#’:
continue
if line == 'done’:
break
print(line)
print('Done!')
For Loop (Definite Loop)
• When we want to loop through a set of things such as a list of words,
the lines in a file, or a list of numbers.
• When we have a list of things to loop through, we can construct a
definite loop using a for statement.
• The syntax of a for loop is similar to the while loop in that there is a
for statement and a loop body:
For Loop Cont…
• Example:
• friends = [‘John', ‘Jane', ‘Doe’]
for friend in friends:
print('Happy New Year:', friend)
print('Done!')

• Looking at the for loop, for and in are reserved Python keywords, and
friend and friends are variables.
Loop Patterns
• We call the while statement an indefinite loop because it simply loops
until some condition becomes False, whereas the for loop is looping
through a known set of items so it runs through as many iterations as
there are items in the set.
• Often we use a for or while loop to go through a list of items or the
contents of a file and we are looking for something such as the largest
or smallest value of the data we scan through.
Loop Patterns Cont…
• These loops are generally constructed by:

• Initializing one or more variables before the loop starts.


• Performing some computation on each item in the loop body, possibly
changing the variables in the body of the loop.
• Looking at the resulting variables when the loop completes
Compound Data Types
• These are data types in which the values are made up of elements
that are themselves values.
• Strings
• Tuples
• Lists
• Dictionaries
Compound Data Types Cont…
• Strings and Tuples are immutable, which means that once you create
them, you can not change them.
• Lists are mutable because you can change the order of items in a list
or reassign an item in a list.
• The assignment operator (=) is used to make a variable point to
strings or tuples just like simple data types; Examples
• myString = “This is a string”
myTuple = (1, 3.7, True, “hello world”)
Strings
• A string is a sequence of characters. You can access the characters
one at a time using the square bracket operator:
• fruit = ‘mango’
letter = fruit[3]
print(letter)
• The second statement extracts the character at index position 3 from
the fruit variable and assigns it to the letter variable.
• The second statement extracts the character at index position 3 from
the fruit variable and assigns it to the letter variable.
Strings Cont…
• Example: This loop traverses the string and displays each letter on a
line by itself. The loop condition is index < len(fruit), so when index is
equal to the length of the string, the condition is false, and the body
of the loop is not executed. The last character accessed is the one
with the index len(fruit)-1, which is the last character in the string.
• fruit = ‘mango’
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
Strings Cont…
• String slices: A segment of a string is called a slice. Selecting a slice is
similar to selecting a character.
• The operator [n:m] returns the part of the string from the "n-th"
character to the "m-th" character, including the first but excluding the
last. For example
• >>> fruit = 'banana’
>>> fruit[:3]
'ban’
>>> fruit[3:]
'ana’
>>> fruit[3:3]
‘'
Strings Cont…
• String methods: Python has a function called dir which lists the
methods available for an object. The type function shows the type of
an object and the dir function shows the available methods.
• >>> dir(string)
['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Strings Cont…
• Calling a method is similar to calling a function (it takes arguments and
returns a value) but the syntax is different. We call a method by appending
the method name to the variable name using the period as a delimiter.
• For example, the method upper takes a string and returns a new string
with all uppercase letters.
• Instead of the function syntax upper(word), it uses the method syntax
word.upper().
• >>> word = 'banana’
>>> new_word = word.upper()
>>> print(new_word)
BANANA
Strings Cont…
• Formatted String Literals: A formatted string literal (often referred to
simply as an f-string) allows Python expressions to be used within
string literals. This is accomplished by prepending an f to the string
literal and enclosing expressions in curly braces {}.
• F-strings are important because an expression can appear anywhere
in the string, so you can embed a value in a sentence. Example;
• >>> fruits = 17
>>> f ‘I have bought {fruits} fruits.’
'I have bought 17 fruits.'
Tuples
• A Tuple is a sequence of values much like a list. The values stored in a
tuple can be any type, and they are indexed by integers.
• Tuples are also comparable and hashable so we can sort lists of them
and use tuples as key values in Python dictionaries.
• Tuple is the name of a constructor, you should avoid using it as a
variable name.
• Most list operators also work on tuples. The bracket operator indexes
an element:
• >>> t = ('a', 'b', 'c', 'd', 'e’)
>>> print(t[0])
'a'
Tuples Cont…
• Syntactically, a tuple is a comma-separated list of values, example;
• >>> tpl = ('a', 'b', 'c', 'd', 'e’)
• To create a tuple with a single element, you have to include the final
comma:
• tpl = ('a’,)
• Using the slice operator to selects a range of elements.
• print(tpl[1:3])
('b', 'c')
Tuples Cont…
• You can't modify the elements of a tuple, but you can replace one
tuple with another:
• >>> tpl = ('A',) + t[1:]
>>> print(t)
('A', 'b', 'c', 'd', 'e’)
• When you try to modify one of the elements of the tuple, you get an
error;
• >>> tpl[0] = 'A’
TypeError: object doesn't support item assignment
Lists
• A list is a sequence of values that can be any type. The values in list
are called elements or sometimes items.
• [10, 20, 30, 40, 50, 60, 70]
[‘hello’, ‘python', ‘python programming']
• The elements of a list don't have to be the same type.
• The following list contains a string, a float, an integer, and another list
• [‘hello’, 3.0, 7, [11, 25]]
• A list within another list is called a nested list.
Lists Cont…
• The syntax for accessing the elements of a list is the same as for
accessing the characters of a string: the square bracket operator. The
expression inside the brackets specifies the index. Remember that the
indices start at 0:
• >>>fruits = [‘mango’, ‘banana’, ‘apple’]
>>>print (fruits[0])
mango
Lists Cont…
• You can think of a list as a relationship between indices and elements.
This relationship is called a mapping; each index "maps to" one of the
elements.
• List indices work the same way as string indices:
• Any integer expression can be used as an index.
• If you try to read or write an element that does not exist, you get an
IndexError.
• If an index has a negative value, it counts backward from the end of the list.
Lists Cont…
• List Operations:
• The + operator concatenates lists:
• >>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
• The * operator repeats a list a given number of times
• >>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Lists Cont…
• List Slices:
• >>> t = ['a', 'b', 'c', 'd', 'e', 'f’]
>>> t[1:3]
['b', 'c’]
>>> t[:4]
['a', 'b', 'c', 'd’]
>>> t[3:]
['d', 'e', 'f']
• If you omit the first index, the slice starts at the beginning. If you omit
the second, the slice goes to the end. So if you omit both, the slice is a
copy of the whole list
• >>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Lists Cont…
• List Methods:
• The append method adds a new element to the end of a list:
• >>> t = ['a', 'b', 'c’]
>>> t.append('d’)
>>> print(t)
['a', 'b', 'c', 'd’]
• The extend method takes a list as an argument and appends all of the
elements. List t2 will be unmodified.
• >>> t1 = ['a', 'b', 'c’]
>>> t2 = ['d', 'e’]
>>> t1.extend(t2)
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
Lists Cont…
• The sort method arranges the elements of the list from low to high
• >>> t = ['d', 'c', 'e', 'b', 'a’]
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e’]
Dictionaries
• A dictionary is like a list, but more general. In a list, the index positions
have to be integers; in a dictionary, the indices can be (almost) any type.
• Dictionaries are associative data types.
• You can think of a dictionary as a mapping between a set of indices
(which are called keys) and a set of values. Each key maps to a value.
• The association of a key and a value is called a key-value pair or
sometimes an item.
• The function dict creates a new dictionary with no items. Because dict is
the name of a built-in function, you should avoid using it as a variable
name.
Dictionaries Cont…
• Examples: we can use a dictionary to associate integer keys (the
numbers 1-5) with strings (their Roman numeral representation) like
this:
• arabic2roman = { 1 : “I”, 2 : ”II”, 3 : “III”, 4 : “IV”, 5 : “V” }

• >>> eng2esp = {'one': 'uno', 'two': 'dos', 'three': 'tres’}


>>> print(eng2esp)
{'one': 'uno', 'two': 'dos', 'three': 'tres'}
Dictionaries Cont…
• Dictionaries;
• Are enclosed in curly brackets
• The elements are separated by commas
• Key : value pairs are separated by colons
• Keys can be any immutable data type
• Values can be any data type:
Assignment
• Write an essay about Python Dictionaries not less than 2 pages
• Read about Deleting Elements in a List
Thank You!

You might also like