Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Module2 Notes Sharmila

Module 2 covers the basics of Python programming, including variables, operators, data types, type conversions, and decision constructs. It explains how to declare and manipulate variables, the different types of operators, and the various data types available in Python. Additionally, it introduces decision-making constructs such as if statements and their variations for controlling program flow.

Uploaded by

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

Python Module2 Notes Sharmila

Module 2 covers the basics of Python programming, including variables, operators, data types, type conversions, and decision constructs. It explains how to declare and manipulate variables, the different types of operators, and the various data types available in Python. Additionally, it introduces decision-making constructs such as if statements and their variations for controlling program flow.

Uploaded by

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

Module 2

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

1.1 Rules for Python variables:


 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 A variable name cannot be any of the Python keywords.

Examples of Valid Variable Names:


myvar my_var _my_var myVar MYVAR myvar2
Examples of Invalid Variable Names:
2myvar my-var my var

1.2 Variable Declaration and Initialization (or) Creating Variables


• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• A variable can be declared and initialized in one line, and Python will infer the type
dynamically
Example:
x=5
y = "John"
print(x)
print(y)
Output:
5
John
1.3 Assigning and Reassigning Python Variables
To assign a value to Python variables, you don’t need to declare its type.
Syntax: <variable name>=<value>
Example:
# declare, initialize or assign a variable
age=7
print(age)
Output:
7
# Redeclare or reassign a variable
age=17
print(age)
Output:
17

1.4 Assigning One Value to Multiple Variables


Python allows assigning a single value to several variables with ‘=’ operators.
Example:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output:
Orange
Orange
Orange

1.5 Assigning Many Values to Multiple Variables


Python allows adding different values in a single line using separators “,”.
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output:
Orange
Banana
Cherry
Example:
age, city=21,'Bengaluru'
print(age, city)
Output:
21 Bengaluru

1.6 How does + operator work with variables?


The Python plus operator + provides a convenient way to add a value if it is a number and
concatenate if it is a string.
If a variable is already created it assigns the new value back to the same variable.
Example:
a = 10
b = 20
print(a+b)
a = "Hello"
b = "Python"
print(a+b)
Output
30
HelloPython
Example:
a = 10
b = "Python"
print(a+b)
Output :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
1.7 Global and Local Python Variables
1.7.1 Local variables
Local variables in Python are those which are initialized inside a function and belong only
to that particular function. It cannot be accessed anywhere outside the function.
 Declaration: Defined inside a function or block.
 Scope: Accessible only within the function or block where they are defined.
 Lifetime: Exists only during the function’s execution.

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

1.7.2 Global Variables


These are those which are defined outside any function and which are accessible throughout
the program, i.e., inside and outside of every function.

 Declaration: Defined outside any function or class


 Scope: Accessible throughout the entire program or script, including all functions.
 Lifetime: Exists for the duration of the program’s execution.

a) Defining and accessing Python global variables


Example:
# This function uses global variable s
def f():
print("Inside Function: ", s)

# 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

c) How Can We Change a Global Variable from Inside a Function in


Python?
The global Keyword
The global keyword in a function is used to do assignments or change the value of a global
variable. Global keyword is not needed for printing and accessing.
Example:
# to modify a global value inside a function using global keyword.
def change(): # function definition
global x # using a global keyword
x=x+5 # updating a global variable
print("Value of x inside a function : ", x)

#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

2.1 Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical
operations.
2.2 Python Assignment Operators
Assignment Operators are used to perform operations on values and variables.

2.3 Python Comparison Operators


Comparison operators are used to compare two values.
2.4 Python Logical Operators
Logical operators are used to combine conditional statements.

2.5 Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location.

2.6 Python Membership Operators


Membership operators are used to test if a sequence is presented in an object.
2.7 Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers.

2.8 Operator Precedence


Operator precedence describes the order in which operations are performed.
Rules:
 Parentheses has the highest precedence, meaning that expressions inside parentheses
must be evaluated first.
 Multiplication * has higher precedence than addition +, and therefor multiplications
are evaluated before additions.
 Addition + and subtraction - has the same precedence, and therefore we evaluate the
expression from left to right.
3. DATA TYPES
In Python, data types are fundamental to understanding what kind of data we are working with,
as they dictate the operations that can be performed on data and the structure it follows. Since
Python treats everything as an object, these data types are classes, and variables are instances
of these classes.
3.1. Numeric Types
Numeric data types in Python store numeric values and are further divided into three main
types:
 int: Stores integer values, which are whole numbers without a decimal point.
Example: 5, -10, 0.
 float: Stores floating-point numbers, which are numbers with a decimal point.
Example: 3.14, -2.7.
 complex: Stores complex numbers, represented as a + bj, where a is the real part and b
is the imaginary part.
Example: 3 + 4j.
Note:Python does not have an inbuilt char, double data type

3.2. Sequence Types


Sequence types are ordered collections of items, meaning items are stored in a specific order
and can be accessed using their index.
 str: Stores text (string) data. Strings are sequences of Unicode characters and are
immutable.
Example: "Hello, World!"
 list: Stores an ordered collection of items, which can be of any type. Lists are mutable,
meaning their contents can be modified.
Example: [1, 2, 'hello', 3.5]
 tuple: Similar to lists but immutable, meaning once created, elements cannot be
changed.
Example: (1, 2, 'world', 4.2)
3.3. Boolean Type
bool: Represents two values, True and False. This is typically used in conditional statements
and evaluations.
Example: is_valid = True

3.4. Set Types


 set: Stores an unordered collection of unique items. Sets are mutable, and duplicate
values are automatically removed. They are commonly used for membership testing
and eliminating duplicate entries.

Example: {1, 2, 3, 4}
 frozenset: Similar to set but immutable, meaning the items in a frozenset cannot be
modified after creation.

Example: frozenset([1, 2, 3, 4])


3.5. Dictionary Type
dict: Stores a collection of key-value pairs, allowing for quick lookup of values based on keys.
Dictionaries are mutable, and keys must be unique and immutable types.
Example: {'name': 'Alice', 'age': 25}

3.6. Binary Types


Binary types are used for handling binary data, such as files and data streams.
 bytes: Immutable sequence of bytes, used to store binary data.
Example: b'hello'
 bytearray: Mutable sequence of bytes, similar to bytes but allows modification.
Example: bytearray(b'hello')
 memoryview: Provides a view on binary data without copying it, used for efficient
manipulation of data buffers.
Example: memoryview(b'hello')

4. Implicit/Explicit Type conversions in python


In Python, type conversions (also known as type casting) allow values of one data type to be
converted into another. This is especially useful when working with different data types in
calculations, comparisons, or other operations. Python supports two types of type conversions:

4.1. Implicit Type Conversion


Implicit type conversion happens automatically when Python converts data types. This occurs
when Python promotes data types to avoid data loss in operations involving different data types.
For example, if an integer and a float are involved in a calculation, Python will convert the
integer to a float automatically:
Example:
# Implicit Type Conversion Example
num_int = 10 # Integer
num_float = 3.5 # Float
result = num_int + num_float # Python automatically converts 'num_int' to a float
print(result) # Output: 13.5
print(type(result)) # Output: <class 'float'>
In the above code:
Python converts num_int (an integer) to float to match num_float during the addition. The
result is a float, preserving precision without data loss.
Note: Implicit conversion generally occurs between compatible data types and avoids data loss.
It’s commonly used in arithmetic operations.

4.2. Explicit Type Conversion


Explicit type conversion, or type casting, is when we manually convert one data type to another
using specific functions. Explicit type conversion is essential when combining incompatible
data types or for specific formatting. For example, converting a float to an integer, or a string
to an integer, requires explicit conversion.

Common Explicit Type Conversion Functions:

 int(): Converts a number or string to an integer (truncates decimals for floats).


 float(): Converts a number or string to a float.
 str(): Converts an object to a string.
 bool(): Converts values to Boolean (True or False).
Example:
# Explicit Type Conversion Example
num_float = 7.8 # Float
num_int = int(num_float) # Convert float to int explicitly
print(num_int) # Output: 7 (decimal part is truncated)
print(type(num_int)) # Output: <class 'int'>
num_str = str(num_int) # Convert integer to string explicitly
print(num_str) # Output: '7'
print(type(num_str)) # Output: <class 'str'>
In this code:
int(num_float) explicitly converts the float 7.8 to integer 7, discarding the decimal part.
str(num_int) converts the integer 7 to a string '7'.
5. Decision Constructs
In procedurally written code, the computer usually executes instructions in the order
that they appear. However, this is not always the case. In Python, decision constructs (also
known as conditional statements or selection control statements) provide the ability to check
conditions and change the behaviour of the program accordingly.

The main decision constructs in Python are


 if statement
 if-else Statement
 if-elif-else
 Nested if-else statements
5.1. if Statement
The if statement executes a block of code if the given condition is True.

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."

5.2. if-else Statement


The if-else statement provides an alternative path if the condition is False.
Syntax:
If test condition:
Statement(1) # executed if condition evaluates to True
else:
Statement(2) # executed if condition evaluates to False
Example of if-else statement
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
In this case, if age is less than 18, it prints "You are not an adult."

5.3. if-elif-else Statement


The if-elif-else statement is used when there are multiple conditions to check. The program
will evaluate conditions from top to bottom and execute the block associated with the first True
condition.
Syntax:
If test condition1:
Statement(1) # executed if condition1 evaluates to True
elif test condition2:
Statement(2) # executed if condition2 evaluates to True
else:
Statement(3) # executed if all condition evaluates to False

Example of if-elif-else statement


marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: D")

Here, the program checks the marks variable against multiple conditions, and the first condition
that is True determines the output.

5.4. Nested if-else Statements


In a nested if statement, we place one if statement inside another. This is useful for checking
additional conditions if the outer condition is True.
Syntax
if Test condition1:
if Test condition2:
Statements_B
else:
Statements_C
else:
if Test condition3:
Statements_D
else:
Statements_E

Example of nested if-else statement


a=10
b=20
c=5
if a>b:
if a>c:
print("Greatest number is ",a)
else:
print("Greatest number is ",c)
else:
if b>c:
print("Greatest number is ",b)
else:
print("Greatest number is ",c)

Output:
Greatest number is 20

6. Iteration Control structures (for, while)


Repeated execution of set of statements is called iteration. Iteration control structures in Python
are loops that allow a block of code to execute repeatedly until a specified condition is met or
until there are no more items to iterate over.
The two main types of loops in Python are:
1) for loop
2) while loop

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.

6.3 Examples of Nested Loops


You can nest for and while loops within each other to handle more complex scenarios.

6.3.1 Nested for Loop


Example:
for i in range(1, 4):
for j in range(1, 3):
print(f "i ={i}, j={j}")
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
6.3.2 Nested while Loop
Example:
i=1
while i <= 3:
j=1
while j <= 2:
print(f"i={i}, j={j}")
j += 1
i += 1

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. Break-Continue-Pass (Loop Control Statements)


Python provides additional statements to control the flow within loops:
1. break
2. continue
3. pass

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

8.1 Multiline Strings


If we need a string to span multiple lines then we can use triple quotes ‘’’or “””.
Example:
str1=’’’Hello!!!
How are you’’’
str2=””” I am doing I year
I am learning Python”””
Output:
Hello!!!
How are you
I am doing I year
I am learning Python
8.2 Accessing characters in Python Strings
Strings in Python are sequences of characters, so we can access individual characters
using indexing. Strings are indexed starting from 0 and -1 from end. This allows us to retrieve
specific characters from the string.
Python allows negative address references to access characters from back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.
C M R U n i v e r s i t Y
0 1 2 3 4 5 6 7 8 9 10 11 12 13
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

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

8.4 String Immutability


Strings in Python are immutable. This means that they cannot be changed after they are
created. If we need to manipulate strings then we can use methods like concatenation,
slicing, or formatting to create new strings based on the original.
Example:
s=’university’
# Trying to change the first character raises an error
s[0] = 'U' # this line will cause a TypeError
# Instead, create a new string
s = "U" + s[1:]
print(s)
Output:
University

8.5 Deleting a string


In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the del keyword.
Example:
s=’university’
del s #deletes entire string
After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.

8.6 Updating a string


To update a part of a string we need to create a new string since strings are immutable.
Example:
s1=’hello students’
s2=’H’ + s1[1:]
s3=s1.replace(“hello”,”dear”)
print(s2)
print(s3)
Output:
Hello students
dear students
For s2, the original string s1 is sliced from index 1 to end of string and then concatenate
“H” to create a new string s1.
For s3, we can created a new string s3 and used replace() method to replace ‘hello’ with
‘dear’.

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()

Converts the first character of each word to upper case.

text = "hello world"


print(text.title()) # Output: "Hello World"
12. isalpha()
Returns True if all characters in the string are alphabetic and False otherwise.
text = "Hello"
print(text.isalpha()) # Output: True
text2 = "Hello123"
print(text2.isalpha()) # Output: False
13. isdigit()
Returns True if all characters in the string are digits and False otherwise.
text = "12345"
print(text.isdigit()) # Output: True
text2 = "123abc"
print(text2.isdigit()) # Output: False
14. islower() and isupper()
islower(): Returns True if all alphabetic characters in the string are lowercase.
isupper(): Returns True if all alphabetic characters in the string are uppercase.
text = "hello"
print(text.islower()) # Output: True
text2 = "HELLO"
print(text2.isupper()) # Output: True
15. swapcase()
Swaps the case of each character in the string (uppercase to lowercase and vice versa).
text = "Hello, World!"
print(text.swapcase()) # Output: "hELLO, wORLD!"
16. center(width)
Centers the string within a specified width, padding it with spaces.
text = "hello"
print(text.center(10)) # Output: " hello "

You might also like