Python Chap2 Notes (6)
Python Chap2 Notes (6)
Control Statements
• Sequence Control : Precedence of operators, Type conversion
• Conditional Statements: if, if-else, nested if-else,
• Looping- for, while, nested loops, loop control statements (break,
continue, pass)
• Strings: declaration, manipulation, special operations, escape
character, string formatting operator, Raw String, Unicode
strings, Built-in String methods.
Precedence and Associativity of Operators in
Python
• Operator Precedence: This is used in an expression with more than
one operator with different precedence to determine which
operation to perform first.
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
or Logical OR
Type Conversion in Python
• Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming. This
article is aimed at providing information about certain conversion functions.
• There are two types of Type Conversion in Python:
• Implicit Type Conversion
• In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user
involvement. To get a more clear view of the topic see the below examples.
• Example
1. x = 10
2. print("x is of type:",type(x))
3. y = 10.6
4. print("y is of type:",type(y))
5. x = x + y
6. print(x)
7. print("x is of type:",type(x))
• Output
• x is of type: <class 'int'>
• y is of type: <class 'float'>
• 20.6
• x is of type: <class 'float'>
• Explicit Type Conversion
• In Explicit Type Conversion in Python, the data type is manually changed by
the user as per their requirement. Various forms of explicit type conversion
are explained below:
• Example
X=int(input("Enter the number "))
The value in string will be converted to integer.
Conditional Statements
• There comes situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next. Similar situations
arise in programming also where we need to make some decisions and based on
these decisions we will execute the next block of code. Decision-making statements
in programming languages decide the direction of the flow of program execution.
• In Python, if else elif statement is used for decision making.
• if statement
• if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
# python program to illustrate If statement
1. i = 10
2. if (i > 15):
3. print("10 is less than 15")
4. print("I am Not in if")
• Output:
I am Not in if
if condition:
statement1
statement2
Output :
Positive or Zero
• Nested-if
A nested if is an if statement that is the target of another if
statement. Nested if statements mean an if statement inside another
if statement. Yes, Python allows us to nested if statements within if
statements. i.e, we can place an if statement inside another if
statement.
• Syntax:
• if (condition1):
• # Executes when condition1 is true
• if (condition2):
• # Executes when condition2 is true
• # if Block is end here
# if Block is end here
• Example
• '''In this program, we input a number
• check if the number is positive or
• negative or zero and display
• an appropriate message
• This time we use nested if statement'''
•
• num = float(input("Enter a number: "))
• if num >= 0:
• if num == 0:
• print("Zero")
• else:
• print("Positive number")
• else:
print("Negative number")
• Output
• Enter a number: 5
• Nested if-elif-else
• Here, a user can decide among multiple options. The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be
executed.
• Syntax:
• if (condition):
• statement
• elif (condition):
• statement
•.
•.
• else:
• statement
• Example
• '''In this program,
• we check if the number is positive or
• negative or zero and
• display an appropriate message'''
•
• num = 3.4
• if num > 0:
• print("Positive number")
• elif num == 0:
• print("Zero")
• else:
print("Negative number")
• Output
Control Statements
• While Loop
• while expression:
statement(s)
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
• Input
# prints Hello Geek 3 Times
count = 0
while (count < 3):
count = count+1
print("Hello Geek")
• Outout :
• Hello Geek
• Hello Geek
• For in Loop
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop.
Syntax:
for iterator_var in sequence:
statements(s)
• Example
• # Measure some strings:
• words = ['cat', 'window', 'defenestrate']
• for w in words:
print(w, len(w))
• output
• cat 3
• window 6
defenestrate 12
• The range() Function
If you do need to iterate over a sequence of numbers, the built-in
function range() comes in handy. It generates arithmetic
progressions:
• Example :
• for i in range(5):
• print(i)
• Output
•0
•1
•2
•3
• Range() Continue.....
• Example2
• list(range(5, 10))
[5, 6, 7, 8, 9]
Example 3
• list(range(0, 10, 3))
[0, 3, 6, 9]
•
Example3
list(range(-10, -100, -30))
[-10, -40, -70]
Nested Loops
Python programming language allows to use one loop inside another loop.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Example
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
2 2
• Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
• Continue Statement
It returns the control to the beginning of the loop.
• Example
• for num in range(2, 10):
• if num % 2 == 0:
• print("Found an even number", num)
• continue
• print("Found an odd number", num)
Output
• # An empty loop
• for letter in 'ebooks':
pass
print 'Last Letter :', letter
• Output:
Last Letter : s
• Python String
In Python, Strings are arrays of bytes representing Unicode
characters. Unicode was introduced to include every character in all
languages and bring uniformity in encoding.
However, Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access
elements of the string
Strings are not mutable in Python. Strings are a immutable data
types which means that its value cannot be updated.
• Creating a String
Strings in Python can be created using single quotes or double quotes or
even triple quotes.
• Defining strings in Python
• Example1
my_string = 'Hello'
print(my_string)
• Output
Hello
• Example2
• my_string = "Hello"
print(my_string)
Hello
• Example 3
my_string = '''Hello'''
print(my_string)
• Output
Hello
• Example 4
• # triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
• Output
Hello, welcome to
the world of Python
• Accessing characters in Python
In Python, individual characters of a String can be accessed by using the method
of Indexing. Indexing allows negative address references to access characters
from the back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character, and so on.
• String Slicing
To access a range of characters in the String, the method of slicing is used.
Slicing in a String is done by using a Slicing operator (colon).
• While accessing an index out of the range will cause an IndexError. Only
Integers are allowed to be passed as an index, float or other types that will
cause a TypeError.
• Example • Output
• #Accessing string characters in str = program
Python str[0] = p
• str = 'program' str[-1] = m
str[1:5] = rogr
• print('str = ', str) str[5:-1] = am
•
• #first character
• print('str[0] = ', str[0])
•
• #last character
• print('str[-1] = ', str[-1])
•
• #slicing 2nd to 5th character
• print('str[1:5] = ', str[1:5])
•
Deleting/Updating from a String
In Python, Updation or deletion of characters from a String is not allowed. This
will cause an error because item assignment or item deletion from a String is not
supported. Although deletion of the entire String is possible with the use of a
built-in del keyword. This is because Strings are immutable, hence elements of a
String cannot be changed once it has been assigned. Only new strings can be
reassigned to the same name.
>>> my_string = 'programiz'
>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item
assignment
>>> my_string = 'Python'
>>> my_string
'Python'
• Deleting Entire String:
Deletion of the entire string is possible with the use of del keyword. Further, if
we try to print the string, this will produce an error because String is deleted and
is unavailable to be printed.
>>> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
• NameError: name 'my_string' is not defined
• Python String Operations
• Concatenation of Two or More Strings
• oining of two or more strings into a single one is called concatenation.
• The + operator does this in Python. Simply writing two string literals together
also concatenates them.
• Example
• # Python String Operations
• str1 = 'Hello'
• str2 ='World!'
•
• # using +
print('str1 + str2 = ', str1 + str2)
• Output
str1 + str2 = HelloWorld!
• Repeating String By Using * operator
The * operator can be used to repeat the string for a given number of times.
• Example
• # Python String Operations
• str1 = 'Hello'
• str2 ='World!'
•
• # using *
print('str1 * 3 =', str1 * 3)
• Output
str1 * 3 = HelloHelloHello
• Iterating Through a string
We can iterate through a string using a for loop. Here is an example to count the number of
'l's in a string.
• Example
• count = 0
• for letter in 'Hello World':
• if(letter == 'l'):
• count += 1
print(count,'letters found')
• Output
3 letters found
• String Membership Test
We can test if a substring exists within a string or not, using the keyword in
• Example
• >>> 'a' in 'program'
• Built-in functions to Work with Python
• Various built-in functions that work with sequence work with strings as well.
• Some of the commonly used ones are enumerate() and len().
• The enumerate() function returns an enumerate object. It contains the index and value of all
the items in the string as pairs. This can be useful for iteration.
• Similarly, len() returns the length (number of characters) of the string.
• Example
• str = 'cold'
• # enumerate()
• list_enumerate = list(enumerate(str))
• print('list(enumerate(str) = ', list_enumerate)
• #character count
print('len(str) = ', len(str))
• Output
• list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
len(str) = 4
Escape Sequence Description
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
• The format() method that is available with the string object is very versatile and powerful in formatting
strings. Format strings contain curly braces {} as placeholders or replacement fields which get replaced.
• Example
• # Python string format() method
# default(implicit) order
• Output
--- Default Order ---
John, Bill and Sean
• Python String Formatting
• Escape Sequence
• If we want to print a text like He said, "What's there?", we can neither use single quotes
nor double quotes. This will result in a SyntaxError as the text itself contains both single and
double quotes.
• Here is a list of all the escape sequences supported by Python.
• Example
• >>> print("C:\\Python32\\Lib")
• C:\Python32\Lib
•
• >>> print("This is printed\nin two lines")
• This is printed
• in two lines
•
• >>> print("This is \x48\x45\x58 representation")
• This is HEX representation
• Example
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)
• Output
--- Positional Order ---
Bill, John and Sean
Example
# order using keyword argument
keyword_order = "{s}, {b}
and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
• Output
--- Keyword Order ---
Sean, Bill and John
• Old style formatting
• We can even format strings like the old printf() style used in C programming
language. We use the % operator to accomplish this.
• Example
• >>> x = 12.3456789
• >>> print('The value of x is %3.2f' %x)
• The value of x is 12.35
• >>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
• Common Python String Methods
• There are numerous methods available with the string object.
Method Description
>>> "PrOgRaMiZ".upper()
• 'PROGRAMIZ'
•
• >>> "This will split all words into a list".split()
• ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
•
• >>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a',
'string'])
• 'This will join all words into a string'
•
• >>> 'Happy New Year'.find('ew')
• 7
•
• >>> 'Happy New Year'.replace('Happy','Brilliant')
• 'Brilliant New Year'
• Raw String to ignore escape sequence
• Sometimes we may wish to ignore the escape sequences inside a string. To do
this we can place r or R in front of the string. This will imply that it is a raw
string and any escape sequence inside it will be ignored.
• Example
• >>> print("This is \x61 \ngood example")
• This is a
• good example
• >>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example