Python for CBSE Students

Python is a simple, yet powerful, object-oriented programming language. It was developed by Guido van Rossum in February 1991. The language was named after the BBC comedy show Monty Python’s Flying Circus.

Python isn’t as fast as C or C++. Python source codes are saved with .py file extension.

We use the print() function to display a message on the screen.
print('Hello World')

Python supports Unicode character encoding. Following are the variable naming rules in Python:

  • The first character can either be a letter or an underscore.
  • The remaining characters can be letters, digits, underscores.
  • Variables are case-sensitive.
  • Variables cannot be a keyword.

Escape Sequences (non-graphic characters) are special characters that are difficult to include directly in text. Following are some of the commonly used escape sequences used in Python:

  • The ‘\n’ is a newline character.
  • ‘\t’ is the horizontal tab character.
  • ‘\” is the single quote.
  • ‘\”‘ is double quote.

The single and double-quoted strings span only one line. The triple-quoted string can span multiple lines.

The len() function is used to find the length of a string.
count = len('hello')

The octal integers begin with 0o. The hexadecimal integers begin with 0x.

The floating-point literals can also be represented using the scientific notation. For example, 7.5 can be written as 0.75E1. Here, 0.75 is the mantissa part, and 1 is the exponent part. The exponent part must be an integer. Here, E1 means 101.

A numeric value separated with commas is treated as a tuple. A tuple is an immutable sequence in Python.

There are two Boolean literals (constants): True and False.

The None literal in Python indicates absence of a value.

Unary operators act on one operand. Binary operators act on two operands.

Arithmetic Operators:

  • + for Addition
  • – for Subtraction
  • * for Multiplication
  • / for Division
  • % for Remainder
  • ** for Exponentiation
  • // for Integer Division (Floor Division)

Relational Operators

  • < for less than
  • > for greater than
  • <= for less than or equal to
  • >= for greater than or equal to
  • == for equal to
  • != for not equal to

Membership Operators

  • in (to check if a value is present in the sequence)
  • not in (to check if a value is absent in the sequence)

Logical Operators

  • and (gives True when both the operands are True)
  • or (gives True when at least one operand is True)
  • not (changes True to False and vice-versa)

Comments

Comments are meant for the programmers to add notes/remarks in the programs. Comments are completely overlooked by the interpreter.

Single line comments begin with # sign.
s = a + b #adding two numbers

Multiline comments are enclosed within triple quotes. They are also known as docstrings.
'''Aim: Finding the sum of two numbers.
Date: July 29, 2024
Author: Robin Sir'''

The type() function can be used to find the data type of any value.
print(type(24))

The input() function is used to receive input from the user through the keyboard. It returns the value in the form of a string.
name = input('Enter your name please: ')
roll = int(input('Enter your roll number: '))
height = float(input('Enter your height in meters: '))

The str() function converts a value to string.
roll = 25
print('My roll number is ' + str(roll))

Complex Numbers can be written in the form a + bj, where j is square root of -1.
num = 5 + 2j
print(num.real)
print(num.imag)

The int, float, bool, str and tuple data type values are immutable types. They can’t be modified during program execution.

The id() function returns the memory location of an object.
x = 24
print(id(x))

The ord() function returns the ASCII code for a given character.
c = ord('A')

The chr() function returns the character equivalent to the given ASCII code.
ch = chr(65)

The is operator checks whether two variables refer to the same object or not.

Bitwise Operators

The bitwise operators work on the binary representations of data.
Bitwise AND is denoted by & symbol.
Bitwise OR is denoted by | symbol.
Bitwise XOR is denoted by ^ symbol.
Bitwise NOT is denoted by ~ symbol.

Operator Precedence in Python

  1. Parentheses
  2. Exponentiation (right to left associativity)
  3. Unary Operators
  4. Multiplication, Division, Modulus, and Floor Division
  5. Addition and Subtraction
  6. Bitwise Shift Operators
  7. Bitwise AND
  8. Bitwise XOR
  9. Bitwise OR
  10. Comparison Operators
  11. Logical NOT (right to left associativity)
  12. Logical AND
  13. Logical OR
  14. Assignment Operators (right to left associativity)
  15. Identity and Membership Operators
  16. Separators

The math Module

To use this module in your program:
import math

math.ceil(num) returns the smallest integer not less than num.
math.floor(num) returns the largest integer not greater than num.
math.sqrt(num) returns the square root of num.
math.exp(num) returns natural logarithm e raised to the power num.
math.fabs(num) returns the absolute value of num.
math.log(num) returns the natural logarithm of num. You can also provide the base as second argument, which is optional.
math.log10(num) returns the base 10 logarithm of num.
math.pow(a, b) returns a raised to the power b.
math.sin(r) returns the sine value of r radians.
math.cos(r) returns the cosine value of r radians.
math.tan(r) returns the tangent value of r radians.
math.degrees(r) returns the degree equivalent of r radians.
math.radians(d) returns the radian equivalent of d degrees.
math.pi is a constant that stores the value of π.
math.e is a constant that stores the Euler’s number.

The if Statement

It allows us to execute a set of statements only if the given condition is satisfied.
if n % 2 == 0:
print('Even')

The if else Statement

It allows us to execute a set of statements when the given condition is true and execute another set of statements when the given condition is false.
if n % 2 == 0:
print('Even')
else:
print('Odd')

The if elif Statement

It allows us to check another condition if the previous condition was false.
if score < 40:
print('FAIL')
elif score < 60:
print('AVERAGE')
elif score < 90:
print('GOOD')
else:
print('EXCELLENT')

The range() Function

It is used to generate a sequence of numbers.
range(5) generates sequence 0, 1, 2, 3, 4.
range(1, 5) generates sequence 1, 2, 3, 4.
range(1, 5, 2) generates sequence 1, 3.

The for Loop

It is an iterative statement that works on any sequence.
for i in range(1, 5):
print(i)

The while Loop

It is an iterative statement that repeatedly executes a set of statements as long as the given condition is true.
i = 1
while i <= 5:
print(i)
i = i + 1

The else Statement in Loops

This else statement executes only when the loop has completed and ends normally.
for i in range(10):
if i % 10 == 0:
break
print(i)
else:
print('None were divisible by 10')

The break Keyword

It is used to exit from a loop at any given point.
for i in range(10):
if i % 5 == 0:
break
print(i)

The continue Keyword

It is used to skip executing a portion of loop body in an iteration.
for i in range(1, 11):
if i % 3 == 0:
continue
print(i)

The random Module

The random module contains the randint() function which is used to generate a random integer in a given range.
import random
r = random.randint(1, 10)

String Concatenation

The + operator is used to concatenate two string values.
full_name = 'Guido' + ' van ' + 'Rossum'

String Replication

The * operator is used to replicate a string value.
laugh = 'ha ' * 3

String Slicing

String slicing means extracting a portion of a given string.
s = 'hello'
t = s[0:2]

r = s[::-1] //reverses the string

capitalize()

Returns a string with first character capitalized and the rest small.
s = 'Hello and Welcome'
t = s.capitalize()

find()

It returns the index of the first occurrence of a given substring in an existing string. It returns -1 if the substring is not found.
s = 'I am what I am'
i = s.find('am')
j = s.find('am', 4)
k = s.find('am', 4, len(s))

isalnum()

Returns True if the string is alphanumeric while having at least one character, otherwise it returns False.
s = 'Office 365'
print(s.isalnum())

isalpha()

Returns True if the entire string only contains alphabets while having at least one character. False otherwise.
s = 'Google'
print(s.isalpha())

isdigit()

Returns True if the entire string only contains digits while having at least one character. False otherwise.
s = '2024'
print(s.isdigit())

islower()

Returns True if all the letters in the string are in lowercase while having at least one character. False otherwise.
s = 'google.com'
print(s.islower())

isupper()

Returns True if all the letters in the string are in uppercase while having at least one character. False otherwise.
s = 'Y2K'
print(s.isupper())

isspace()

Returns True if all the characters are whitespaces while having at least one character. False otherwise.
s = ' '
print(s.isspace())

lower()

Returns a string with all the alphabets in lowercase.
s = 'Username'
s = s.lower()

upper()

Returns a string with all the alphabets in uppercase.
s = 'Happy New Year'
s = s.upper()

lstrip()

Removes leading characters (all possible combinations) from the string. Removes whitespace if no argument is provided.
s = ' hello'
s = s.lstrip()
s = s.lstrip('he')

rstrip()

Removes trailing characters (all possible combinations) from the string. Removes whitespace if no argument is provided.
s = 'hello '
s = s.rstrip()
s = s.rstrip('lo')

len()

Returns the length of the string.
s = 'hello world'
n = len(s)

Debugging is a process in which programmers find errors in code, rectify them and recompile until the code is error-free.

A program bug is an error that causes disruption in program’s execution or in getting the desired output. There are 3 types of errors:
1. Compile-time errors: They occur during program compilation. There are 2 types of compile-time errors:
a) Syntax errors: Occurs when the rules of the programming language are violated. Example:
if 4 = 5:
print('Yes')

b) Semantic errors: Occurs when the programming statements don’t make sense. Example:
a + b = s
2. Runtime errors: Occurs during program execution.
Example:
print(5 / 0)
3. Logical errors: Occurs when a program doesn’t yield desired output.
Example: * operator used when + operator was needed.

An exception is a runtime error, and the programmer has no control on it. Unhandled exceptions will lead to program termination. We can use the try-except clause to handle exceptions:
try:
x = 5
y = 0
print(x / y)
except:
print('Cannot divide by zero!')

The try block encloses code that may generate exceptions. The except block encloses code that handles those exceptions.

Python includes many built-in exceptions. The following table lists some of these exceptions:

EXCEPTION NAMEUSE
ZeroDivisionErrorDivide a number by 0
IndexErrorIndex is out of range
NameErrorIdentifier doesn’t exist
TypeErrorInvalid operation with wrong data type object
ValueErrorFunction receives wrong data type value
IOErrorInput/Output operation fails
ImportErrorModule is not found
OverflowErrorArithmetic operation exceeds the limits
KeyErrorDictionary key is not found
EOFErrorThe input() function hits EOF without data

Debugging Techniques:
1. Find the origin of the error.
2. Display the intermediate values of variables.
3. Using code tracing.
In code tracing, we execute the code line-by-line and observe the change in variables.

Python includes a debugger tool called pdb.
Add it as the first line in your program:
import pdb
Add this line just above the code from where you want to start tracing:
pdb.set_trace()
On execution, the following prompt will appear:
ipdb>
Use the following commands for further operations:

CommandsMeanings
pprint variable value
nnext
sstep inside a function
ccontinue
<Enter>repeat previous command
lrepeat nearby code
qquit
hhelp
h commandhelp on a specific command
b 25set break point on line 25
blist current break points
clclear all break points
cl 25clear break point 25

Break Points are temporary markers that halts the code execution until you clear the break points.

LIST MANIPULATION

A list is a data structure that allows us to store a collection of items in a single variable. Python lists are mutable.

To create an empty list:
x = []
OR
x = list()

To create a list of vowels in lowercase:
x = ['a', 'e', 'i', 'o', 'u']

To create a nested list:
x = [1, 2, [3, 5], 4]

To form a list of characters from a string:
x = list('hello')

To make a copy of an existing list:
x = [1, 2, 3]
y = list(x)

To input a list:
x = eval(input('Enter the list: '))

The eval() function is used to evaluate a Python expression.
result = eval('2 + 3 * 5')

To find the length of a list:
x = [1, 5, 7, 8]
print(len(x))

To access an element in a list:
x = [1, 2, 5]
print(x[2])

To slice a list:
x = [2, 3, 5, 7, 11]
y = x[1:3] #excluding element at index 3

z = x[::2]
r = x[::-1] #reverses the list

Membership Operators:
x = [2, 3, 5, 7, 11]
print(3 in x)
print(4 not in x)

Concatenating Lists:
x = [1, 2, 5]
y = [3, 4, 5]
z = x + y

Replicating Lists:
x = [3, 5]
y = x * 3

Comparing Lists:
x = [3, 5]
y = [3, 4, 2]
print(x > y)

List Modification
x = [2, 3, 5, 7, 11]
x[1:3] = [4, 8]
x[4] = 12

The append() function is used to add an element to the end of the list.
x = [1, 3, 5]
x.append(12)

The del keyword is used to delete an element from the list. It doesn’t return the deleted element.
x = [1, 3, 5]
del x[0]

del x #deletes the entire list

The pop() function deletes an element from the list and returns it. If no index is specified, it deletes the last element.
x = [1, 3, 5, 7]
x.pop() #deletes the last element
x.pop(1) #deletes the second element from the list

Leave a Reply

Your email address will not be published. Required fields are marked *