Python Module2 Notes Sharmila
Python Module2 Notes Sharmila
Basics of Python
_______________________________________________________________
Dr.G.Sharmila
Assistant Professor
CSE Department
Contents:
1. Variables
2. Operators
3. Data Types
4. Implicit/Explicit Type conversions
5. Decision Constructs
6. Iteration Control structures (for, while)
7. Break-Continue-Pass
8. Strings
9. String functions
1. Variables
A variable is a name that refers to a memory location and serves as a basic unit of storage in a
program. In Python, variables act as containers that store values. Based on the data type of a
value that is stored in a variable, the interpreter allocates memory for a variable.
Dynamic Values: The value stored in a variable can change during program execution.
Memory Reference: A variable is just a name given to a memory location. Any operations
performed on the variable affect that memory location.
Example:
var = "Python"
print(var)
Output:
Python
Example:
def my_function():
local_var = 5 # Local variable
print(“local variable= “,local_var) # Accessing local variable
my_function()
Output:
Local variable= 5
def my_function():
local_var = 5 # Local variable
print(local_var) # Accessing local variable
my_function()
print(local_var) # Raises an error because local_var is not accessible outside a function
# Global scope
s = "Python programming"
f()
print("Outside Function: ", s)
Output:
Inside Function: Python programming
Outside Function: Python programming
b) Python variable with the same name initialized inside a function as well
as globally
Example:
# function definition that use a variable with name same as global variable s
def f():
s = " Same name but local scope "
print(s)
# Global scope
s = "Same name but global scope"
f() #function call
print(s)
Output:
Same name but local scope
Same name but global scope
Example:
# function definition that update a local variable with name same as global variable s
def change(): # function definition
x=x+5 # updating a global variable
print("Value of x inside a function : ", x)
#global scope
x = 15
change() # function call
UnboundLocalError: cannot access local variable 'x' where it is not associated with a
value
#global scope
x = 15
print("Value of x outside a function before change : ", x)
change() # function call
print("Value of x outside a function after change : ", x)
Output:
Value of x outside a function before change : 15
Value of x inside a function : 20
Value of x outside a function after change : 20
2. Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
Example: {1, 2, 3, 4}
frozenset: Similar to set but immutable, meaning the items in a frozenset cannot be
modified after creation.
Syntax:
if test condition:
Statements #executed if condition evaluates to True
Example of if statement:
age = 20
if age >= 18:
print("You are an adult.")
In this example, the program checks if age is greater than or equal to 18. If it is, it prints "You
are an adult."
Here, the program checks the marks variable against multiple conditions, and the first condition
that is True determines the output.
Output:
Greatest number is 20
6. 1. for Loop
The for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or
any other iterable object. It executes the block of code for each item in the sequence.
Basic Syntax:
for variable in sequence:
# Code block to be executed
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
6.1.1 Using range() with for Loop
The range() function is often used with for loops to iterate over a sequence of numbers.
# Example of for loop with range()
for i in range(5):
print(i)
Output:
0
1
2
3
4
6.1.2 Specifying Start, Stop, and Step in range()
We can also specify a start and step value in range()
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
6. 2. while Loop
The while loop repeatedly executes a block of code as long as a given condition is True. Once
the condition becomes False, the loop stops.
Basic Syntax:
while condition:
# Code block to be executed
Example:
count = 1
while count <= 5:
print("Count:", count)
count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
In this example, count starts at 1 and increments by 1 with each loop iteration until count
reaches 5. The loop terminates when count exceeds 5.
Output:
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2
7.1 break:
Exits the loop immediately when encountered.
Example:
for i in range(1, 10):
if i == 5:
break
print(i)
Output:
1
2
3
4
● The loop stops once i reaches 5.
7.2 continue:
Skips the current iteration and moves to the next.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
● Inside the loop iteration, when i equals 3, continue skips the execution of statements after if
condition. Therefore in output printing 3 is skipped.
7.3 pass:
A null operation; it does nothing. . It’s often used as a placeholder. The difference between a
comment and pass statement in Python is that, while the interpreter ignores a comment
entirely, pass is not ignored.
Example:
for i in range(5):
if i == 2:
pass # Placeholder
print(i)
Output:
0
1
2
3
4
● The pass statement does nothing when i equals 2, but allows the loop to continue.
8. Strings
Python string is a sequence of Unicode characters that is enclosed in quotation marks. This
includes letters, numbers, and symbols. Python has no character data type so single character
is a string of length 1.
Example:
str1=’Hello’
str2=”10 is greater than 5, 10>5”
Output:
Hello
10 is greater than 5, 10>5
Example:
str1=’CMR University’
print(str[0])
print(str[3])
print(str[4])
print(str[13])
print(str[-1])
print(str[-13])
Output:
C
U
y
y
C
Accessing an index out of range will cause an IndexError. Only integers are allowed as
indices and using a float or other types will result in a TypeError.
8.3 String Slicing
Slicing is a way to extract portion of a string by specifying the start and end indexes. The
syntax for slicing is string[start:end], where start starting index and end is stopping index
(excluded).
Example:
str1=’CMR University’
print(str1[1:5]) #prints characters from index 1 to 4: 'MR U'
print(str1[:5]) #prints characters from index 0 to 4: 'CMR U'
print(str1[7:]) #prints characters from index 7 to end: 'versity’
Output:
MR U
CMR U
versity
9. String Functions
Python provides some built_in functions to operate on strings.
Note: Every string method in Python does not change the original string instead returns a new
string with the changed attributes.
1. len()
Returns the length (number of characters) of a string.
text = "Hello, World!"
print(len(text))
# Output:
13
2.lower() and upper()
● lower(): Converts all characters in the string to lowercase.
● upper(): Converts all characters in the string to uppercase.
Text = "Hello, World!"
print(text.lower())
# Output: "hello, world!"
print(text.upper())
# Output: "HELLO, WORLD!"
3.strip()
Removes any leading and trailing whitespace (or specified characters) from the string.
text = " Hello, World! "
print(text.strip()) # Output: "Hello, World!"
4. replace(old, new)
Replaces all occurrences of a substring (old) with another substring (new) in the string.
text = "Hello, World!"
print(text.replace("World", "Python")) # Output: "Hello, Python!"
5. split(delimiter)
Splits the string into a list of substrings based on a specified delimiter (default is any
whitespace).
text = "apple,banana,cherry"
print(text.split(",")) # Output: ['apple', 'banana', 'cherry']
6. join(iterable)
Joins the elements of an iterable (e.g., a list) into a single string, with each element separated
by the specified delimiter.
fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits)) # Output: "apple, banana, cherry"
7. find(substring)
Returns the index of the first occurrence of a substring in the string. Returns -1 if the
substring is not found.
text = "Hello, World!"
print(text.find("World")) # Output: 7
print(text.find("Python")) # Output: -1
8. count(substring)
Counts the number of occurrences of a substring in the string.
text = "banana"
print(text.count("a")) # Output: 3
9. startswith(prefix) and endswith(suffix)
startswith(prefix): Checks if the string starts with the specified prefix. Returns True or
False.
endswith(suffix): Checks if the string ends with the specified suffix.
text = "Hello, World!"
print(text.startswith("Hello")) # Output: True
print(text.endswith("!")) # Output: True
10. capitalize()
Capitalizes the first character of the string and converts the rest to lowercase.
text = "hello, world!"
print(text.capitalize()) # Output: "Hello, world!"
11. title()