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

UNIT 2 Python

Unit 2 of the Class 11 CBSE curriculum introduces the basics of Python programming, covering execution modes, program structure, indentation, identifiers, keywords, constants, variables, and operators. It also discusses data types, statements, expressions, comments, input/output statements, data type conversion, debugging, control statements, loops, lists, and dictionaries. The document provides examples and methods for each topic to facilitate understanding and application.

Uploaded by

spam16543
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

UNIT 2 Python

Unit 2 of the Class 11 CBSE curriculum introduces the basics of Python programming, covering execution modes, program structure, indentation, identifiers, keywords, constants, variables, and operators. It also discusses data types, statements, expressions, comments, input/output statements, data type conversion, debugging, control statements, loops, lists, and dictionaries. The document provides examples and methods for each topic to facilitate understanding and application.

Uploaded by

spam16543
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Unit 2: Introduc on to Python – Informa cs Prac ces (Class 11 CBSE)

1. Basics of Python Programming

 Execu on Modes:

o Interac ve Mode:

 The user writes and executes Python code line by line in an interpreter
(like Python Shell or an IDE).

 Used for tes ng small snippets of code quickly.

o Script Mode:

 Code is wri en in a .py file and executed as a whole program.

 Used for larger programs that require saving and re-running.

 Structure of a Program:

o A Python program consists of a sequence of statements executed by the


Python interpreter.

o Common structure: Impor ng modules, func on defini ons, and the main
code logic.

 Indenta on:

o Python relies on indenta on (spaces or tabs) to define code blocks.

o Important: Ensure consistent indenta on in the program; otherwise, it will


throw an Indenta onError.

 Iden fiers and Keywords:

o Iden fiers: Names used for variables, func ons, classes, etc. Examples: x,
total_price, my_func on.

o Keywords: Reserved words that have special meanings in Python. Examples:


if, else, for, while, def.

 Constants and Variables:

o Constants: Values that do not change during the program execu on (e.g., PI =
3.14). Usually wri en in uppercase le ers.

o Variables: Names used to store data values which can change during the
program execu on.
 Types of Operators:

o Arithme c Operators: +, -, *, /, // (floor division), % (modulus), **


(exponen a on).

o Rela onal Operators: ==, !=, >, <, >=, <= (used to compare values).

o Logical Operators: and, or, not (used for logical condi ons).

o Assignment Operators: =, +=, -=, *=, /=, etc. (used to assign values).

o Bitwise Operators: &, |, ^, ~, <<, >> (used to perform bitwise opera ons).

 Precedence of Operators:

o Operators have different priori es (precedence) when evaluated.

o For example, * and / have higher precedence than + and -.

2. Data Types

 Mutable Data Types: Can be changed a er crea on.

o Examples: Lists, Dic onaries, Sets.

 Immutable Data Types: Cannot be changed once created.

o Examples: Integers, Floats, Strings, Tuples.

 Common Data Types:

o Integer (int): Whole numbers (e.g., 5, -7).

o Float (float): Decimal numbers (e.g., 3.14, -0.5).

o String (str): Sequence of characters enclosed in single or double quotes (e.g.,


"Hello", 'Python').

o Boolean (bool): Represents True or False.

3. Statements and Expression Evalua on

 Statements: Instruc ons that the Python interpreter executes (e.g., variable
assignments, func on calls).

 Expressions: A combina on of values, variables, and operators that Python evaluates


to produce a result (e.g., 5 + 3).
4. Comments

 Single-line Comment:

o Starts with a # and extends to the end of the line.

python

# This is a comment

 Mul -line Comment:

o Enclosed within triple quotes (''' or """).

python

'''This is a mul -line comment.

It can span mul ple lines.'''

5. Input and Output Statements

 Input: Accepts user input.

python

name = input("Enter your name: ")

o The input() func on always returns a string, which can be converted to other
data types.

 Output: Displays output to the user.

python

print("Hello", name)

o The print() func on can print strings, variables, or expressions.

6. Data Type Conversion

 Implicit Conversion (Type Coercion): Automa cally done by Python when


performing opera ons between compa ble data types (e.g., adding an integer and a
float).

python

num = 3 + 5.5 # num will be a float (8.5)


 Explicit Conversion (Type Cas ng): Explicitly conver ng one data type to another
using func ons like int(), float(), and str().

python

num = int("123") # Converts string to integer

7. Debugging

 Debugging: The process of iden fying and fixing errors in the program.

o Print Statements: Used to check the values of variables and follow the
program's flow.

o Use of IDEs: Many IDEs (like PyCharm) provide built-in debuggers to step
through code and inspect variables.

Control Statements

1. if-else and if-elif-else

 if Statement: Executes a block of code if the condi on is true.

python

if condi on:

# Code block

Example:-

age = 18

if age >= 18:

print("You are an adult.") # Output: You are an adult.

 else Statement: Executes a block of code if the condi on is false.

python

else:

# Code block
Example:-

age = 16

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.") # Output: You are a minor.

 elif Statement: Checks addi onal condi ons if the previous if condi on was false.

python

if condi on1:

# Code block

elif condi on2:

# Code block

else:

# Code block

Example:-

age = 25

if age < 13:

print("You are a child.")

elif age < 18:

print("You are a teenager.")

else:

print("You are an adult.") # Output: You are an adult.


2. Loops

 while Loop: Repeats the code as long as the condi on is true.

python

while condi on:

# Code block

Example:-

count = 0

while count < 5:

print(count)

count =count + 1 # Output: 0 1 2 3 4

 for Loop: Iterates over a sequence (like a list, string, or range).

python

for i in range(5):

# Code block

Example:-

for i in range(5):

print(i)

# Output: 0 1 2 3 4

Lists

 Crea ng and Ini alizing Lists:

python

list1 = [1, 2, 3]

list2 = ["apple", "banana", "cherry"]

 List Opera ons:

o Accessing Elements: list1[0] gives the first element.

o Modifying Elements: list1[1] = 5 changes the second element.


 List Methods:

o len(list): Returns the number of elements in the list.

o list.append(item): Adds an item to the end of the list.

o list.insert(index, item): Inserts an item at a specific index.

o list.remove(item): Removes the first occurrence of an item.

o list.pop(index): Removes the item at the specified index (default is last).

o list.reverse(): Reverses the list.

o list.sort(): Sorts the list.

o list.count(item): Counts occurrences of the item.

o list.index(item): Finds the index of an item.

o list.min(), list.max(), list.sum(): Finds the minimum, maximum, and sum of


elements.

Example:-
len(list):

python

my_list = [1, 2, 3, 4]

print(len(my_list)) # Output: 4

list.append(item):

python

my_list = [1, 2, 3]

my_list.append(4)

print(my_list) # Output: [1, 2, 3, 4]

list.insert(index, item):

python

my_list = [1, 2, 3]

my_list.insert(1, 6)

print(my_list) # Output: [1, 6, 2, 3]


list.remove(item):

python

my_list = [1, 2, 3, 4]

my_list.remove(3)

print(my_list) # Output: [1, 2, 4]

list.pop(index):

python

my_list = [1, 2, 3, 4]

popped_item = my_list.pop(2)

print(popped_item) # Output: 3

print(my_list) # Output: [1, 2, 4]

list.reverse():

python

my_list = [1, 2, 3, 4]

my_list.reverse()

print(my_list) # Output: [4, 3, 2, 1]

list.sort():

python

my_list = [4, 2, 3, 1]

my_list.sort()

print(my_list) # Output: [1, 2, 3, 4]

list.count(item):

python

my_list = [1, 2, 2, 3, 2]

print(my_list.count(2)) # Output: 3
list.index(item):

python

my_list = [1, 2, 3, 4]

print(my_list.index(3)) # Output: 2

list.min(), list.max(), list.sum():

python

my_list = [1, 2, 3, 4]

print(min(my_list)) # Output: 1

print(max(my_list)) # Output: 4

print(sum(my_list)) # Output: 10

Dic onary

 Key-Value Pair: A dic onary stores data as pairs of unique keys and values.

python

dict = {"name": "Alice", "age": 20}

 Dic onary Methods:

o dict.keys(): Returns a list of all keys.

o dict.values(): Returns a list of all values.

o dict.items(): Returns a list of key-value pairs.

o dict.update(): Updates a dic onary with new key-value pairs.

o del dict[key]: Deletes an item by key.

o dict.clear(): Removes all items from the dic onary.

Example:-

dict.keys():

python

my_dict = {"name": "Alice", "age": 20}

print(my_dict.keys()) # Output: dict_keys(['name', 'age'])


dict.values():

python

print(my_dict.values()) # Output: dict_values(['Alice', 20])

dict.items():

python

print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 20)])

dict.update():

python

my_dict.update({"city": "New York"})

print(my_dict) # Output: {'name': 'Alice', 'age': 20, 'city': 'New York'}

del dict[key]:

python

del my_dict["age"]

print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}

dict.clear():

python

my_dict.clear()

print(my_dict) # Output: {}

You might also like