python chapter no 2 notes
python chapter no 2 notes
integer_number = 123
float_number = 1.23
output
Value: 124.23
Data Type: <class 'float'>
num_string = '12'
num_integer = 23
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
Statement Description
The if statement is used to test a specific condition. If the condition is true, a block of code
If Statement
(if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides the
Statement block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.
Nested if
The elif statement
Statement
Nested if statements enable us to use if - else statement inside an outer if statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
Example 1
Output:
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Output:
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
Output:
This type of loop executes a code block multiple times and abbreviates
2 For loop
the code that manages the loop variable.
1.While Loop
While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition changes to
false.
1. while <condition>:
2. { code block }
All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements together with
indentation.
Code
Output:
Python Loops
Python Loops
Python Loops
Python Loops
As discussed earlier in the for loop section, we can use the else statement with the while loop
also. It has the same syntax.
Code
1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
The loop can be declared in a single statement, as seen below. This is similar to the if-else block,
where we can write the code block in a single line.
Code
In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
Code
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
As already said, a for loop executes the code block until the sequence element is reached. The
statement is written right after the for loop is executed after the execution of the for loop is
complete.
Only if the execution is complete does the else statement comes into play. It won't be executed if
we exit the loop or if an error is thrown.
Code
Output:
P
y
t
h
If block
n
L
If block
If block
p
Syntax:
Code
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
With the help of the range() function, we may produce a series of numbers. range(10) will
produce values between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner range(start, stop, step size). If
the step size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an
iterator.
Code
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We can use
indexing to iterate through the given sequence by combining it with an iterable's len() function.
Here's an illustration.
Code
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
Continue Statement
Code
Output:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
1. # Python program to show how the break statement works
2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'L':
6. break
7. print('Current Letter: ', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.
Code
Output:
Last Letter: s
5.
6. Strings in python
Python String
Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings
are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Consider the following example in Python to create a string.
Syntax:
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string of
length 1.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python to access the substring from the given
string. Consider the following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if
str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character, which is
indicated as -1. The second rightmost index indicates -2, and so on. Consider the following
image.
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object
doesn't support item assignment i.e., A string can only be replaced with new string since its
content cannot be partially replaced. Strings are immutable in Python.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
However, in example 1, the string str can be assigned completely to a new content as specified
in the following example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
1. str = "JAVATPOINT"
2. del str[1]
Output:
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
It is also a membership operator and does the exact reverse of in. It returns true if a particular
not in
substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to print the
r/R actual meaning of escape characters such as "C://python". To define any string as a raw string,
the character r or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C
% programming like %d or %f to map their values in python. We will discuss how formatting is
done in python.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given
statement can be written in single quotes or double quotes but it will raise the SyntaxError as it
contains both single and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
Output:
We can use the triple quotes to accomplish this problem but Python provides the escape
sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a
special character and it interpreted differently. The single quotes inside the string must be
escaped. We can apply the same as in the double quotes.
Example -
Output:
print("Python1 \
Python2 \
1. \newline It ignores the new line. Python3")
Output:
\
print('\'')
3. \' Single Quotes Output:
'
print("\"")
4. \\'' Double Quotes Output:
"
5. \a ASCII Bell
print("\a")
print("Hello \b World")
6. \b ASCII Backspace(BS) Output:
Hello World
7. \f ASCII Formfeed print("Hello \f World!")
Hello World!
print("Hello \n World!")
8. \n ASCII Linefeed
Output:
Hello
World!
print("Hello \r World!")
9. \r ASCII Carriege Return(CR) Output:
World!
print("Hello \t World!")
10. \t ASCII Horizontal Tab Output:
Hello World!
print("Hello \v World!")
11. \v ASCII Vertical Tab Output:
Hello
World!
print("\110\145\154\154\157")
12. \ooo Character with octal value
Output:
Hello
print("\x48\x65\x6c\x6c\x6f")
13 \xHH Character with hex value. Output:
Hello
1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")
Output:
C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation
We can ignore the escape sequence from the given string by using the raw string. We can do this
by writing r or R in front of the string. Consider the following example.
1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
Output:
C:\\Users\\DEVANSH SHARMA\\Python32
Output:
1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My
value is %s"%(Integer,Float,String))
Output:
Method Description
It capitalizes the first character of the String. This function is
capitalize()
deprecated in python3
It returns a space padded string with the original string centred with
center(width ,fillchar)
equal number of left and right spaces.
endswith(suffix It returns a Boolean value if the string terminates with given suffix
,begin=0,end=len(string)) between begin and end.
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
index(subsring, beginIndex, It throws an exception if string is not found. It works same as find()
endIndex) method.
It returns true if all the characters are alphabets and there is at least
isalpha()
one character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
It returns true if all the characters are digits and there is at least one
isdigit()
character, otherwise False.
It returns the space padded strings with the original string left
ljust(width[,fillchar])
justified to the given width.
It searches for the separator sep in S, and returns the part before it,
partition() the separator itself, and the part after it. If the separator is not found,
return S and two empty strings.
Splits the string according to the delimiter str. The string splits
split(str,num=string.count(str)) according to the space if the delimiter is not provided. It returns the
list of substring concatenated with the delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.
It returns a Boolean value if the string starts with given str between
startswith(str,beg=0,end=len(str))
begin and end.
It is used to convert the string into the title-case i.e., The string
title()
meEruT will be converted to Meerut.