Introduction :
Python is a General-Purpose object-oriented programming language, which
means that it can model real-world entities. The distinctive feature of Python is that it is an
interpreted language. The Python IDLE (Integrated Development Environment) executes
instructions one line at a time. This also lets us use it as a calculator.
Guido van Rossum named it after the comedy group Monty Python Flying Circus a Comedy
Serial of BBC.
Python Features :
Easy
Interpreted
Object-Oriented
Free and Open Source
Portable
Large Python Library
Interpreter : It executes / converts high level code into machine code (source to target code)
line by line, and slow compare to compiler.
Compiler : It executes / converts code in one go and faster compared to Interpreter.
MODES OF PYTHON WORKING
Interactive Mode : Interactive mode is running blocks or a single line of Python code. The
code executes via the Python shell. Interactive mode is handy when you just want to execute
basic Python commands or you are new to Python programming.
Script Mode: If you need to write a long piece of Python code or your Python script spans
multiple files, interactive mode is not recommended. Script mode is the way togo in such
cases. In script mode, You write your code in a text file then save it with a .py extension
which stands for "Python". This file can be executed byPython Interpreter later on.
PYTHON KEYWORDS: Python keywords are special reserved words that have specific
meanings and purposes and can’t be used for anything but those specific purposes. An
example of something you can’t do with Python keywords is assign something to them.
Examples of keywords are : False, else, import, pass, in, is, True, and continue etc.
Python Identifiers: Identifiers are names given to different entities such as constants,
variables, structures, functions, etc. Example: int, amount; True, totalbalance; In the above
example, amount and totalbalance are identifiers and int, and double are keywords.
Rules for Identifiers
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore _ .
An identifier cannot start with a digit.
Keywords cannot be used as identifiers. ...
We cannot use special symbols like !, @, #, $, % etc. ...
An identifier can be of any length.
BUILT-IN DATA TYPES: In programming, data type is an important concept. Variables can
store data of different types, and different types can do different things. Python has the
following data types built-in by default, in these categories:
Text Type Str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types Set
Boolean Type Bool (Only True and False Value)
None Type None
PYTHON OPERATORS:
Operators are used to perform operations on variables and values. In the example below, we
use the + operator to add together two values: Python divides the operators in the following
groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
PYTHON ARITHMETIC OPERATORS: Arithmetic operators are used with numeric values
to perform common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x**y
// Floor division x//y
PYTHON ASSIGNMENT OPERATORS: Assignment operators are used to assign values
to variables:
PYTHON LOGICAL OPERATORS: Logical operators are used to combine conditional
statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
PYTHON MEMBERSHIP OPERATORS: Membership operators are used to test if a
sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified value 5 in [5,10,25] True
is present in the object(List, String,Tuple)
not in Returns True if a sequence with the specified value 5 not in [5,10,25] False
is not present in the object(List, String,Tuple)
WHAT ARE MUTABLE AND IMMUTABLE DATA TYPES IN PYTHON?
Python Mutable data types are those whose values can be changed in place whereas
Immutable data types are those that can never change their value in place. Here are :
Mutable data types : Immutable data types in Python:
1. Lists 1. Integers
2. Dictionaries 2. Floating-Point numbers
3. Sets 3. Booleans
4. Strings
5. Tuples
SAMPLE QUESTION AND ANSWERS
[Link] developed python programming language? Write any two name(s) of IDE
for python language.
Ans: Guido Van Rossum in 1990 developed python programming language
[Link] Names of any two Python IDE
Ans. IDE- Spyder, Pycharm, IDLE
3. Identify the valid identifiers from following-
f@name , as , _tax , roll_no , 12class , totalmarks , addr1
Ans: _tax, roll_no, totalmarks, add1
4. What is difference between equality (==) and identity (is) operator?
Ans: Equality (==) compares values while identity (is) compares memory address of
variables/objects.
5. Write python code to convert the time given in minutes into hours and minutes.
Ans:
min=int(input(“Enter time in minutes &”))
h=min//60
m=min%60
print(“Hours=”, h)
print(“Minutes=”, m)
6. Evaluate (to true or false)each of the following expression:
14<=14, 14<14, -14 > -15, -15 >=15
1. True, False, True, False
2. False, False , True, True
3. True, False, True, True
4. False, True, False, False
Ans: True, False, True, True
7 What will be the output of the following python statements?
a,b,c = 10,40,20
a,c,b = b+10, a+20, c-10
print(a,b,c)
print(a+b//c**2)
CONTROL FLOW STATEMENTS IN PYTHON
A program’s control flow is the order in which the program’s code executes. The
control flow of a Python program is regulated by conditional statements, loops,
and function calls.
Python has three types of control structures:
Sequential - Sequential statements are a set of statements whose execution
process happens in a sequence (step by step).
Selection/Conditional/Decision - The selection statement allows a program
to test several conditions and execute instructions based on which condition is
true.
Some Decision Control Statements are:
Simple if
if-else
nested if
if-elif-else
Repetition/Iteration/Loop - A repetition statement is used to repeat a
group(block) of programming instructions. Repetition based on condition . If it
true the block will execute.
In Python, we generally have two loops/repetitive statements:
for loop
while loop
STRINGS DATA TYPES :
A sequence of characters is called a string. Strings are used by programming languages to
manipulate text such as words and sentences. String is immutable data type. It is ordered
data type.
Strings literal in Python are enclosed by double quotes or single quotes. String literals can
span multiple lines, to write these strings triple quotes are used.
>>> a = ‘’’ Python Empty string can also be created in Python .
Programming >>> str = ‘ ‘
Language’’’
Accessing Valuesin Strings: Each individual character in a string can be assessed using a
technique called indexing .Python allows both positive and negative indexing. Suppose to
S = “Python Language”
We can access element from string using index value. For example :
String Slicing : To access some part of a string or substring, we use a method called slicing.
Syntax: string_name[start : stop]
>>> str1 = " Python Program "
>>> print ( str1[ 3: 8])
OutPut : hon P
>>> print ( str1 [ : -4 ] )
OutPut :Python Pro
>>> print ( strl [ 5 : ] )
OutPut :n Program
Strings are also provide slice steps which used to extract characters from string that are not
consecutive. Syntax string_name [ start : stop : step ]
>>> print ( stri [ 2 : 12 : 3 ] )
OutPut : tnrr
We can also print all characters of string in reverse order using [ : : -1 ]
>>> print ( strl [ :: - 1 ] )
OutPut : margorP nohtyP
String Operations
String Concatenation Operator (+): To concatenate means to join. Python allows us to join
two strings using the concatenation operator plus which is denoted by symbol +.
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings 'HelloWorld!'
OutPut : 'HelloWorld!'
String Replication Operator ( * )
Python allows us to repeat the given string using repetition operator which is denoted by
symbol (*) .
>>> a = 3 * " Hello "
>>> print ( a )
OutPut :HelloHelloHello
Membership Operators: are used to find out whether a value is a member of a string or not .
(i) in Operator: (ii) not in Operator:
>>> a = "Python Programming Language" >>> a = "Python Programming Language"
>>> "Programming" in a >>> "Java" not in a
True True
LIST DATA TYPE
List is an ordered sequence, which is used to store multiple data at the same time. List
contains a sequence of heterogeneous elements. Each element of a list is assigned a number
to its position or index. The first index is 0 (zero), the second index is 1 , the third index is 2
and so on .
Creating a List In Python,
a = [ 34 , 76 , 11,98 ]
b=['s',3,6,'t']
d = [ ] # Known a empty list we can also create empty list using list() method.
Creating List From an Existing Sequence: list ( ) method is used to create list from an
existing sequence .
Syntax: new_list_name = list ( sequence / string )
You can also create an empty list . eg . a = list ( ) .
Similarity between List and String
• len ( ) function is used to return the number of items in both list and string .
• Membership operators as in and not in are same in list as well as string .
• Concatenation and replication operations are also same done in list and string.
Difference between String and List
Strings are immutable which means the values provided to them will not change in the
program. Lists are mutable which means the values of list can be changed at any time.
Accessing Lists
To access the list's elements, index number is used.
S = [12,4,66,7,8,97,”computer”,5.5,]
How to access elements of List : example
List Operations
1. Concatenate Lists: List concatenation is the technique of combining two lists . The use
of + operator can easily add the whole of one list to other list . Syntax list list1 + list2
e.g. >>> L1 = [ 43, 56 , 34 ]
>>> L2 = [ 22 , 34 , 98 ]
>>> L = L1 + L2
OutPut : >>> L [ 43, 56, 34, 22 , 34 , 98 ]
2. Replicating List: Elements of the list can be replicated using * operator .
Syntax list = listl * digit e.g. >>> L1 = [ 3 , 2 , 6 ]
>>> L = L1 * 2
OutPut : >>> L [ 3 , 2 , 6 , 3 , 2 , 6 ]
3. Slicing of a List: List slicing refers to access a specific portion or a subset of the list for
some operation while the original list remains unaffected .
Syntax:- list_name [ start: end ]
Syntax: list_name [ start: stop : step ]
TUPLES DATA TYPE
A tuple is an ordered sequence of elements of different data types. Tuple holds a
sequence of heterogeneous elements, it store a fixed set of elements and do not allow
changes. It is immutable data type (can’t change).
Tuple vs List
Elements of a tuple are immutable whereas elements of a list are mutable.
Tuples are declared in parentheses ( ) while lists are declared in square brackets [ ].
Creating a Tuple
To create a tuple in Python, the elements are kept in parentheses ( ), separated by
commas or using tuple() method.
a = ( 34 , 76 , 12 , 90 )
b=('s',3,6,'a')
Tuple Operations
1. Concatenate tuples: Tuple concatenation is the technique of combining two tuples .
The use of + operator can easily add the whole of one tuple to other tuple . Syntax
tuple1+ tuple2 e.g. >>> T1 = ( 43, 56 , 34 )
>>> T2 = ( 22 , 34 , 98 )
>>> T = T1 + T2
OutPut : >>> T ( 43, 56, 34, 22 , 34 , 98 )
2. Replicating Tuple: Elements of the list can be replicated using * operator .
Syntax tuple = tuple * digit e.g. >>> T1 = ( 3 , 2 , 6 )
>>> T = T1 * 2
OutPut : >>> T ( 3 , 2 , 6 , 3 , 2 , 6 )
3. Slicing of Tuple: Tuple slicing refers to access a specific portion or a subset of the
tuple for some operation while the original list remains unaffected .
Syntax:- tuple_name [ start: end ]
Syntax:- tuple_name [ start: end : stop]
DICTIONARY DATA TYPE
Dictionary is an unordered collection of data values that store the key : value pair
instead of single value as an element . Keys of a dictionary must be unique and of
immutable data types such as strings, tuples etc. Dictionaries are also called mappings
data type. It is mutable data type. It means Value can be change but keys are
immutable.
Creating a Dictionary: To create a dictionary in Python, key value pair is used .
Dictionary is list in curly brackets , inside these curly brackets , keys and values are
declared .
Syntax dictionary_name = { key1 : valuel , key2 : value2 ... } Each key is separated from
its value by a colon ( :) while each element is separated by commas . example :
>>> Employees = { " Abhi " : " Manger " , " Manish " : " Project Manager " , " Aasha " : "
Analyst " , " Deepak " : " Programmer " , " Ishika " : " Tester "}
Accessing elements from a Dictionary:
Syntax: dictionary_name[keys]
>>> Employees[' Aasha ']
OUTPUT: ' Analyst '
Adding elements to a Dictionary: We can add element in dictionary with key.
Syntax: dictionary_name[new_key] = value
>>> Employees['Neha'] = "HR"
>>> Employees
{' Abhi ': ' Manger ', ' Manish ': ' Project Manager ', ' Aasha ': ' Analyst ', ' Deepak ': '
Programmer ', ' Ishika ': ' Tester ', 'Neha': 'HR'}
Updating elements in a Dictionary:
Syntax: dictionary_name[existing_key] = value
>>> Employees
{' Abhi ': ' Manger ', ' Manish ': ' Project Manager ', ' Aasha ': ' Analyst ', ' Deepak ': '
Programmer ', ' Ishika ': ' Tester ', 'Neha': 'HR'}
Now following statement change the value of key Neha
>>> Employees['Neha'] = " Progammer "
>>> Employees
{' Abhi ': ' Manger ', ' Manish ': ' Project Manager ', ' Aasha ': ' Analyst ', ' Deepak ': '
Programmer ', ' Ishika ': ' Tester ', 'Neha': ' Progammer '}
Membership operators in Dictionary:
Two membership operators are in and not in. Themembership operator inchecksifthe
key is present in the dictionary.
>>>Employees
{' Abhi ': ' Manger ', ' Manish ': ' Project Manager ', ' Aasha ': ' Analyst ', ' Deepak ': '
Programmer ', ' Ishika ': ' Tester ', 'Neha': 'HR'}
>>> " Ishika " in Employees
True
>>> ' Analyst ' not in Employees
True
The range()function : The range() function in Python generates a list which is a special sequence type.
A sequence in Python is a succession of values bound together by a single name. Some Python
sequence types/ iterablesare: strings, lists, tuplesetc.
The function in the form range(L,U,S)will produce a list having values starting from L,L+1,L+2
……..(U-1)
# L and U being integers # both limits should be integers. # Step as increment/decrement
#Write a program to print sum of two numbers.
a=int(input("Enter First Number"))
b=a=int(input("Enter Second Number"))
c=a+b
print("Sum =",c)
#Write a program to print Multiply of two numbers.
a=int(input("Enter First Number"))
b=a=int(input("Enter Second Number"))
c=a+b
print("Sum =",c)
#Write a program to print sum of two numbers.
a=int(input("Enter First Number"))
b=a=int(input("Enter Second Number"))
c=a+b
print("Sum =",c)
#Write a program to Calculate Compound Interest and Total amount.
P=float(input("Enter Principal amount"))
R=float(input("Enter Rate %"))
T=float(input("Enter Time "))
total=P*((1+R/100)**T)
CI=total-P
print("Total Amount=",total)
print("Interest Amount=",CI)
#Write a program to Calculate Simple Interest and Total amount.
P=float(input("Enter Principal amount"))
R=float(input("Enter Rate %"))
T=float(input("Enter Time "))
SI=P*R*T/100
total=P+SI
print("Total Amount=",total)
print("Interest Amount=",SI)
# Write a Program to check entered number is Even or Odd.
n=int(input("Enter number to check Even or Odd"))
if n%2==0 :
print("Entered Number",n, " is Even")
else:
print("Entered Number",n, " is Odd")
# Write a Program to check entered Year is Leap year or not.
yr=int(input("Enter Year to check"))
if yr%4==0 :
print("Entered Year",yr, " is Leap Year")
else:
print("Entered Year",yr, " is Not Leap Year")
#Write a program to check number is Prime or not.
n=int(input("Enter number to check prime or not"))
c=0
for i in range(2,n):
if n%i==0:
c=c+1
if c==0:
print(n," is Prime Number")
else:
print(n," is Not Prime Number")
#Write a program to print table of entered number.
x=0
n=int(input("Enter Number for table"))
for i in range(1,11):
x=n*i
print(n," X ",i,"= ",x)
print("End")
#Write a program to Print factorial value of entered number.
f=1
n=int(input("Enter Number for Factorial"))
for i in range(n,1,-1):
f=f*i
print("Factorial of ", n, " is = ",f)