Class 12 - Chapter 1
Class 12 - Chapter 1
Fundamental of Python
Introduction of Python
Python is an interpreter, interactive, object-oriented, and high-
level programming language. It was created by Guido van Rossum in
1991 at National Research Institute for Mathematics and Computer
Science Netherlands.
Features of Python
Python IDLE
The python IDLE tool offers an interactive and a more efficient platform to write your code in
python. (Integrated Development Learning Environment)
Python IDLE comprise Python Shell (Interactive mode) and Python Editor (Script mode).
● Interactive Mode: The Python commands are directly typed at >>> command prompt and
as soon as we press the enter key, the interpreter displays the results immediately, which is
known as displaying. (We cannot save file or command)
>>>10+50
60
● Script Mode: We can write multiple line of code here and get output and errors are running
code. We can open script mode using CTRL+N
Syntax of print () in python:
print(value1,value1,…………,sep=’ ‘, end=’ ‘)
Displaying Vs Printing: Getting output without using print function in interactive mode is called
displaying, And getting output using print () in interactive or script mode.
Different types of files in python:
.py, .pyw, .pyc, .pyd, .pyo, .pyz
-----------------------------------------------------------------------------------------------------------------------------------
Python character set: Character set is a set of valid characters recognized by python. A character
by letter, digit or any other special symbol.
1. Letters: A-Z, a-z 2. Digits: 0-9 3. Special Symbols:+-/*&=!@_ etc.
4. Whitespaces: Blank space, tabs (‘\t’), carriage return (Enter key), newline, form feed (skips to
the start of the next page.)
5. Other Characters: All ASCII code and Unicode character.
Tokens: A token is the smallest element of a python script that is meaningful to the interpreter.
Variable:
A Variable is like a container that stores any value. x=3, age=30
Components of Variable/Object:
A). Identity of the Variable / Object: It refers to the Variable’s memory location address which is
unchanged once it has been created. We can check memory location using this method:
id()
*(None is a datatype with single value. It is used to signify the absence of value / Condition
evaluating to false in a situation.)
Multiple Assignments:
1) Assigning multiple values to multiple variables: x,y,z=2,3,4
2) Assigning same value to multiple variable: a=b=c=10
False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for,
from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
1. input(): Its used to get user input in string format. ex: input(“Enter any number”)
2. int(): This function converts the inputted string value into numeric value if possible.
3. eval(): Its used to evaluate string as a number if possible. eval(“10+50”)
Type Casting
The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.
1. Implicit Type Conversion: Python automatically converts one data type to another data
type. This process doesn't need any user involvement. Ex: type(5/2)
2. Explicit (forced) Type Conversion: In Explicit Type Conversion, users convert the data type
of an object to required data type. Ex: float(5), str(5),int(‘5’)
Binary Operators: Operators that operate on two operands are known as binary operators. Ex:
3+3
Unary Operators: Operators that operate on one operand are known as unary operators. Ex: -3
Types of Operators:
Arithmetic operators:
Comparison operators
Logical operators,
Shorthand /Augmented Assignment operators,
Membership operators.
Identity operators,
What is Functions?
A function is a block of code which only runs when it is called/invoke.
Advantages of Functions:
1. We can avoid rewriting the same logic/code again and again in a program.
2. We can call Python functions multiple times in a program.
3. Code becomes reusable.
def function_name():
statement
print(value)
Function Calling/invoking
function_name()
What is Debugging?
Debugging is the process of finding and fixing errors or bugs in the source code of any software.
Errors are of three types – • Compile Time Error • Run Time Error • Logical Error
1. Compile time error: These errors are basically of 2 types –
1. Syntax Error: Violation of formal rules of a programming language results in syntax error.
print(“hello)
2. Semantics Error: Semantics refers to the set of rules which sets the meaning of statements.
A meaningless statement results in semantics error.
x*y=z
2. Run time Error: These errors are generated during a program execution due to resource
limitation. Such type of error are also termed as exceptions.
Ex: Division by zero, using variable which has not been defined, accessing a list element which
doesn’t exist, try to access a file which doesn’t exit.
3. Logical Error: If a program is not showing any compile time error or run time error but not
producing desired output, it may be possible that program is having a logical error.
ex: Using wrong operators like using // in place of /, giving wrong operator precedence.
-----------------------------------------------------------------------------------------------------------------------------------
Conditional Statement and Looping Statement
1. Sequence: In this program executes in sequential order, one after another, without any jump in
the program.
a=10
b=20
c=a+b
print(c)
2. Selection/ Decision: In this program executes according to condition. If any condition in true
code will run if condition if false code will not run. Keyword If , else
1. if statement
2. if else statement
3. if elif else statement
4. Nested if-else statement
if statement:
The statements inside the body of “if” only execute if the given condition returns true. If the
condition returns false then the statements inside “if” are skipped.
Syntax:
if test expression:
statement(s)
statement(s)
if else statement:
The if/else statement executes a block of code if a specified condition is true. If the condition is
false, another block of code can be executed.
Syntax:
if test expression:
Body of if
else:
Body of else
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
3. Iteration / Looping: In this statement program executes multiple times according to condition.
Keyword while, for
1. for loop
2. while Loop
3. Nested for Loop
4. Nested while loop
For loop statement:
The for loop statement is used to iterate / repeat itself over a range of values or a sequence. (That
is either, a list, a tuple, a dictionary, or a string).
Syntax:
for iterating_var in sequence:
statements(s)
statements(s)
Use of range()
range(start, stop, step)
Syntax:
Body of while
Jump Statement:
1. break statement
2. continue statement
3. pass
Break Statement: Break statement in Python is used to terminate the loop when some external
condition is triggered.
Continue Statement: The continue statement is used to skip the rest of the code inside a loop for
the current iteration only.
l=[10,20]
for i in l:
pass
-----------------------------------------------------------------------------------------------------------------------------------
String in Python
What is String:
A string is a sequence of characters. We can enclose characters in quotes (single, double or triple.)
str1=’Hello world’
str2=”Python Programming”
str3=’’’Python
Programming’’’
*(An escape sequence character is represented as a string with one byte of memory.)
str=” ”, str=’ ‘
Multiple line String: Multiline strings are represented using triple quotes (‘’’ ‘’’) or even single or
double quotes.
Indexing in a string (Accessing Characters)
Accessing individual characters of the string by using the index value is called indexing.
Traversing a String: Traversing a string means accessing all the elements of the string one after the
other by using the subscript / index value.
For loop:
While loop:
Concatenation: Concatenation refers to creating a new string by adding two strings. + is the
operator to join two string. Some Example: “Hello ”+”world”
Repetition or Replicate: By repetition of string we can create multiple copies of any string.
* is the Operator for repetition. Some Example: “Hello” *3.
Membership: Membership operators used for checking whether a particular character exists in the
given string or not. Operators are: “in” and “not in”
Some Example:
“H” in “Hello” Gives True
“H” not in “Hello” Gives False.
Comparison Operators: Comparison operators are used to compare two strings. Python compares
strings using ASCII or UNICODE.
Some Example:
“Tim”==”tim” Gives False
“Freedom” > “Free” Gives True
String Slicing: Slicing is used to retrieve a subset of values. Chunk of characters can be extracted
from a string using slice operator. Example: var1 [start: end: step]
Some Example:
Str=”Save money”
str[1:3] gives “av”
str[:3] gives “Sav”
capitalize() – This method return the exact copy of the string with the first letter in uppercase.
Santax: str.capitalize()
split() – This method breaks up a string at the specified separator and returns a list of substrings.
Santax: str.split(separator,maxsplit)
replace() – This function replaces all the occurrences of the old string with the new string.
Santax: str.replace(old,new)
find() – This function is used to search the first occurrence of the substring in the given string.
find() returns the lowest index of the substring if it is found in the given string. If the substring is
not found it returns -1.
Santax: str.find(sub,start,end)
index() – This function is quite similar to find() but raises an exception if the substring is not
present in the given string.
Syntax: str.index(substring, start, end)
isalpha() – This function checks for alphabets in an inputted string. It returns True if the strings
contains only letters, otherwise returns False.
Syntax: str.isalpha()
isalnum() – The isalnum() method returns True if all the characters are alphanumeric, alphabet
letters(a-z) and numbers (0-9).
Syntax: str.isalnum()
isdigit() – This function returns True if the string contains only digits, otherwise False.
Syntax: str.isdigit()
title() – This function returns the string with first letter of every word in the string in uppercase
and rest in lowercase.
Syntax: str.title()
count() – This function returns number of times substring occurs in the given string.
Syntax: str.count(substring, start, end)
lower() – This function converts all the uppercase letters in the string into lowercase.
Syntax: str.lower()
upper() – This function converts lowercase letters in the string into uppercase.
Syntax: str.upper()
islower() – This function returns True if all the letters in the string are in lowercase.
Syntax: str.islower()
isupper() – This function returns True if all the letters in the string are in uppercase.
Syntax: str.isupper()
Chr() – This function returns the character represented by the inputted Unicode/ASCII number.
Example: chr(65) gives “A”
-----------------------------------------------------------------------------------------------------------------------------------
List in Python
What is List
A list is a collection of comma-separated values (items) within square brackets. Items in a list need
not of the same type. It stores data in ordered sequence.
Declaring/Creating List:
Empty list=[ ]
Traversing a list:
Traversing a list means accessing each element of a list. This can be done by using either for or
while looping statement.
4) Indexing: Index is nothing but there is an index value for each item present in the sequence or
list. Example of nested list also.
5) Slicing Operator: This operator used to slice a particular range of a list or a sequence. Slice is
used to retrieve a subset of values.
Syntax: list [start : stop : step]
What is Tuple:
Tuple is a sequence of immutable Python object. Tuples are sequences, just like lists. Tuples are
immutable it means we cannot perform insert, update and delete operation on them.
The only difference is that tuples are immutable , tuples use parentheses, and lists use square
brackets.
Tuple creation:
Nested Tuple:
Example: fruits= (10 , 20 , (‘Ram’ , ’Mohan’) , 40 , 50 , [‘Red’ , ’blue’] , 60)
Traversing a Tuple:
Traversing a tuple means accessing each element of a tuple. This can be done by using either for or
while looping statement.
What is Dictionary:
A python dictionary is a mapping of unique keys to values. It is a collection of key-value pairs.
Dictionaries are mutable which means they can be changed.
Creating a Dictionary:
Empty dictionary:
d={}
d=dict()
Accessing a Dictionary:
To access dictionary elements, you can use the square brackets along with the key to obtain its
value.
print(D[‘Output’])
It will give out: ‘Printer’
Traversing a Dictionary:
Traversing a dictionary means accessing each element of a Dictionary. This can be done by
using either for or while looping statement.