Python Introduction 11 TH Chapter
Python Introduction 11 TH Chapter
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum
and first released in 1991 It is used in many applicaions like Software Development,Web Development,System
Scripting,Mathematics etc.
Features of Python
• Easy to use: Due to simple syntax, it is very easy to implement
• Interpreted Language: In python, every code is executed line by line.
• Cross-platform Language : Python program can run on any platform Windows, Linux, Macintosh, Rasp-
berry Pi, etc.
• Expressive Language : It supports a wide range of library
• Free & Open Source : It can be downloaded free of cost
• GUI: It supports Graphical user interface
Disadvantages:
• Lesser Libraries : As compared to other programming languages like c++, java, .Net, etc. it has a lesser
number of libraries
• Slow Language : Since being an interpreted language, the code is executed slowly
• Weak on Type-Binding : A variable that is initially declared int can be changed to string at any point in the
program without any typecasting.
Applications of Python
Clearly, Python is a popular and in-demand skill to learn. It is the fastest-growing programming language and
can develop any application. Some of the globally known applications such as YouTube, Facebook,Google,
Amazon etc. use Python to achieve their functionality
Here, we are specifying application areas where Python can be applied.
Web Development
Game Development
Machine Learning and Artificial Intelligence
Data analytics
Data visualisation
Search Engine Optimisation (SEO)
Software Development
Python Character Set
Image Processing Application
Letters : A – Z, a – z
Digits : 0–9
Special Symbols Space : + – * / % // ( ) [ ] { } \ # , ; :: ‘ ‘ “ “ @ _ < > = & ** != ==
Whitespaces : Blank Space, tabs, carriage return (enter sign), newline, formfeed
Other characters : Python can process all ASCII and UNICODE characters.
Variables in Python
A variable is a named location used to store data in the memory. For example in the follwing statement a variable
‘n’ is created and assigned the value 10 to n.
n=10
Because n is holding numeric value 10 so we can say n is Integer type variable. In python,variables do not need
to be declared with any particular data type, and type can be changed after they have been set.
n=”Hello”
n is now of string type.
It is complusory to assign any value to variable before using it, see the following code fragement
print(a) #statement 1
a=30 #statement 2
Statement 1 will give an error message “name ‘a’ is not defined” because no value has been assigned to variable
a before printing.To remove this error, assign the value to a before print statement.
a=30
print(a)
Here, an integer object is created with the value 10, and all three variables are assigned to the same memory loca-
tion. The value 10 is assigned to all variables a,b and c.
Assigning multiple values to multiple variables: Suppose you want to assign 10,20 and 30 to a,b,c and you have
written the folowing code
a=10
b=20
c=”School”
Here, two integer objects with values 10 and 20 are assigned to variables a and b respectively, and one string ob-
ject with the value “School” is assigned to the variable c.
In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of vari-
ables.Consider the following program:
x=5 #statement 1
x,y=15,x+20 #statement 2
print(x,y) #statement 3
In statement 1 the integer object 5 is assigned to variable x. In statement 2 the integer object 15 is assigned to x
and value x+20 is assigned to y but one question aries here which value of x will be used here 5 ro 15. Answer
is 5 because in assignment statement the right hand side is evaluated fully without taking the effect of changes
of value of variable in current statement. Result of statement 3 is 15,25. To understand this concept see the fol-
lowing two codes.
Code 1 Code 2
x=1 x=1
y=2 y=2
x,y = y,x+y x=y
print(x,y) y = x+y
output print(x,y)
2,3 output:
2,4
Q1 What is variable?
Ans: A variable is a named location used to store data in the memory. For example in the follwing statement a
variable ‘n’ is created and assigned the value 10 to n.
n=10
Q2 How can multiple values be assigned to multiple variables and same value to differnt variables.
Ans: Assigning multiple values to multiple variables:
a,b,c=10,20,”hello”
Q3 Write code to create a variable num and assign 100 value to num.
Ans num=100
Statements :
Every expression which does some action is called statement. Every instruction in program like assigning some
value or comparing some value is called statement. For example
a=10 #this statement assigning value 10 to variable a
print(a) #this statement printing the value of variable a
In this example, both lines assigning value and printing value are called statement.
Expression:
An expression is an instruction that combines values and operators and always evaluates to a single value. For
example, this is an expression: >>> 2 + 5 where 2 and 5 are integer values and the + is the mathematical opera-
tor which gives the result as single value i.e. 7. They are different from statement in the fact that statements do
something while expressions are representation of value
Comments :
A Python comment is a line of text in a program that is not executed by the interpreter. Comments are used during
debugging to identify issues and to explain code. Commenting your code helps explain your thought process, and
helps you and others to understand later on the intention of your code
Comments are in the source code for humans to read, not for computers to execute.
In the following program 1st line is a comment line and will not be executed.
output:
hello
Inline comments
Inline comments occur on the same line of a statement, following the code itself. Like other comments, they begin
with a hash mark and a single whitespace character.
Everything that comes after # is ignored. So, we can also write the above program in a single line as:
print(“hello”) #This program display “hello” message
(i)using # :We can use # at the beginning of each line of comment on multiple lines, see the follwing example
# it is a example
# of multiline
# comment
(ii) using string literals :we can use triple quotes(without space) at the begining and end of block to
write multiline comments.
‘‘‘
it is a example
of multiline
comment
‘‘‘
A block is a group of statements in a program. Usually, it consists of at least one statement and declarations for the
block, depending on the programming language. A block in a program functions as a means to group statements
to be treated as if they were one statement.
Python programs get structured through indentation, i.e. code blocks are defined by their indentation.Python uses
the colon symbol (:) and indentation for showing where blocks of code begin and end
So, how does it work? All statements with the same distance to the right belong to the same block of code, i.e. the
statements within a block line up vertically. The block ends at a line less indented or the end of the file. If a block
has to be more deeply nested, it is simply indented further to the right.
s=0 #statement 1
for i in range(1,10): #statement 2
a=int(input(“enter no”)) #statement 3
s=s+a #statement 4
print(s) #statement 5
In the above example 3 and 4 statements are part of for loop block. This block will be executed 9 times but state-
ment 5 is not the part of blcok and will be executed once.
Beginners are not supposed to understand the above example, because we haven’t introduced most of the used
structures, like conditional statements and loops.
Rvalues are the literals and expressions that are assigned to lvalues. Rvalues can come on RHS of an assignment
statement.
For example:
x = 50 #here x is Lvalue and 50 is Rvalue
y = x + 20 #here x and y are Lvalue and 20 is Rvalue
ID
Everything in Python is an object, even all variables or literal values are objects. id() function takes a single pa-
rameter object.id() function returns the identity of the object. This is an integer that is unique for the given object
and remains constant during its lifetime.
Syntax:
id(object)
The identity of the two same values is the same, as shown below.
Example:
num = 10
print(“Id of num is: “, id(num))
print(“Id of 10 is: “,id(10))
Output
Id of num is: 8791113061700
Id of 10 is: 8791113061700
In the above example, the id of 10 and variable num are the same because both have the same literal value.
Hence, integer 5 has a unique id. The id of the integer 5 remains constant during the lifetime. Similar is the case
for float 5.5 and other objects.
Type()
The type() function in Python returns the data type of the object passed to it as an argument.
Syntax
The syntax of the type() function in Python is:
type(object)
a=10
b=”Computer”
print(type(a))
print(type(10))
print(type(b))
print(type(“Computer”))
output
<class ‘int’>
<class ‘int’>
<class ‘str’>
<class ‘str’>
TOKENS
The smallest individual unit in a program is known as a Token or a lexical unit.There are five types of tokens al-
lowed in Python. They are :
• Keywords
• Identifiers
• Literals
• Operators
• Punctuators
(i)Keywords: Keywords are the reserved words in Python. We cannot use a keyword as a variable name, func-
tion name or any other identifier. They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
(ii)Identifier:
An identifier is a name given to entities like class, functions, variables etc.
Rules for writing identifiers
• Identifier must always start with either a letter or an underscore (_). For example: _str, str, num, _num are all
valid name for the variables.
• Identifiers cannot start with a number. For example: 9num is not a valid variable name.
• The identifier cannot have special characters such as %, $, #.- etc, they can only have alphanumeric characters
and underscore (A to Z, a to z, 0-9 or _ ).
• An identifier can not contain space
• Identifier is case sensitive in Python which means num and NUM are two different variables in python.
• Keywords cananot be used as identifier
Example: Out of the following, find those identifiers, which can not be used for naming Variable or Functions in
a Python program:
Total*Tax, While, class, switch, 3rdRow, finally, Column31, _Total
Example: Identify invalid variable names out of the following. State reason if invalid.
(i) for
(ii) –salary
(iii) salary12
(iv) product
Q7 Identify invalid variable name(s) out of the following. State reason if invalid [comptt 16]
(i) While
(ii) 123salary
(iii) Big
(iv) Product
Ans : 123Salary
Q8 Help Manish in identifying the incorrect variable name with justification from the following:
i. unit@price ii. fee iii. userid iv. avg marks [SP 18]
Ans : i. unit@price; // Special symbols like „@‟ is not allowed in variable name
iv. avg marks;// Spaces are not allowed in variable name
Q9 Identify the invalid variable names. State the reason if invalid.
(i) Marks Unit(ii) Product_1(iii) Sales123 (iv) 2Marks 1 [2018]
Ans Invalid variable names are :
(i) Marks Unit
Reason : Variable Name should not contain space
(iv) 2Marks
Reason : Variable Name should not start with digit
Q11Which of the following can be used as valid variable identifier(s) in Python ? 2 [compt 17]
(i) elif
(ii) BREAK
(iii) in
(iv) _Total
Ans: (i)BREAK (iv)_Total
Q12 Which of the following can be used as valid variable identifier(s) in Python?
(i) 4thSum (ii) Total (iii) Number# (iv) _Data [OD 17]
Q13 Out of the following, find those identifiers, which can not be used for naming Variable or Functions in a
Python program: [D 16]
_Cost, Price*Qty, float, Switch, Address One, Delete, Number12, do 2
Q14 Find the correct identifiers out of the following, which can be used for naming vaeiable, constants or func-
tions in a python program:
While, for, Float, new, 2ndName, A%B, Amount2, _Counter
Ans: While, Float, Amount2, _Counter
Q15 Find the correct identifiers out of the following, which can be used for naming Variable, Constants or Func-
tions in python program: [OD 2015]
For, while, INT, NeW, del, 1stName, Add+Subtract, name1
Ans For, INT, NeW, name1
Q16 Out of the following, find those identifiers, which can not be used for naming Variable, Constants or Func-
tions in a python program:
Total*Tax, double, Case, My Name, NeW, switch, Column31, _Amount
Ans Total*Tax
Q17 Write the type of python keywords and user defined identifiers from the following:
(i) For
(ii) del
(iii) else
(iv) Value
Ans (i) For - user defined identifier
(ii) del - keyword
(iii) else - keyword
(iv) Value - user defined identifier
Q18 Write the type of python keywords and user defined identifiers from the following :
(i) case
(ii) _delete
(iii) while
(iv) 21stName
Q19 Write the type of python keywords and user defined identifiers from the following:
(i) in
(ii) While
(iii) and
(iv) Num_2
Ans (i) in - Keyword
(ii) While - User defined Identifier
(iii) and - Keyword
(iv) Num_2 - User defined Identifier
Q20 Write the type of python keywords and user defined identifiers from the following:
(i) else (ii) Long (iii) break (iv) _count
Ans (i) keyword (ii) Identifier (iii)keyword (iv) Identifier
(iii)Literal/Values: Literals are the raw data that are assigned to variables or constants while programming.
In python, there are different types of literals in python such as string literals, numeric literals, boolean literals
and a special literal None
Numeric Literals: Numeric Literals are immutable (unchangeable).Three types of numeric literals available in
python :integer, float and complex.
Integers literals: The numbers that don’t have any fractional parts are known as Integers. It can be positive,
negative, or zero. Some examples of integers are 125, -893, 0,453 etc.
Float literals: The number that contain values with fractional parts is called float literals. It has values both
before and after the decimal point. Examples of floating-point numbers are 1.29, -8.7, 0.7, etc.
Complex literals: In the form of a+bj where a forms the real part and b forms the imaginary part of the com-
plex number. eg: 2+3j
String literals :A string literal is a sequence of characters surrounded by quotes. We can use single, double or
triple quotes for a string. Triple quotes can also be used to give multiple line comments. For examples
a= ‘hello’ or a=”hello” or a=’’’hello’’’ all are string literals. There are two types of string in python
(i) Single line Strings: The string which is terminated in one line by using single quotes or double quotes. for
example:
a=”You are reading python book”
b=’ India is Great’
By using triple quotes: If you put triple quotes(‘‘‘) at the begining and ending of string, you can write string in
multiple lines without using blackslash at the end of line.
a=’’’hello
hi
bye’’’ #statement 1
print (a) #statement 2
print(len(a)) #statement 3
output:
hello
hi
bye
12
In statement 1, the value of string is stored in variable a. In statement 2 the value of a is printed and you can see
the string is displayed on different lines as stored. In statement 3, length of string is displyed and you will be
surprised to see the length i.e. 12 because no of characters in string are 10. The reason behind this is ‘\n’ (new
line character) is added at the end of each line of string (except last line) and it is also counted when calculating
the length of string.
Ans (i) String data type (ii) No, 321 is a Number/Integer while “321” is a String.
Boolean literals : A Boolean literal can have any of the two values: True or False
Special literal :Python contains one special literal i.e. None. None is just a value that commonly is used to sig-
nify ‘empty’, or ‘no value’, for example in variable a we store None value.
a=None
print(a)
When we give the print statement to print the value of a, None will be displayed.
output
None
Later you can replace any data type value with None
a=10
print(a)
output
10
But if you try to add any datatype with None, you will get an error message.
a=None
b=a+10 #will display an error message.
Literal Collections :There are other different literal collections List literals, Tuple literals and Dictionary liter-
als. These will be discussed at later chapters in details.
(iv)Punctuators: Punctuators, also known as separators give a structure to code. They are mostly used to
define blocks in a program. Most commonly used punctuators in Python are:
single quotes – ‘ ‘ , double quote – ” ” , parenthesis – ( ), brackets – [ ], Braces – { }, colon – ( : ) , comma ( , ),
etc.
(v)Python Operators
Python operator is a symbol that performs an operation on one or more operands. An operand is a variable or a
value on which we perform the operation.Python provides a variety of operators described as follows.
Unary Operators: This type of operators needs only one operands to operate, some unary operators are
+ Unary plus, - Unary minus. For examples +5,-3
Binary Operators : This type of operators needs two operands to operate upon. Following are some binary op-
erators:
• Arithmetic operators
• Relational operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes +(addition), -
(subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**).
a. Addition(+)It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
b. Subtraction(-)It is used to subtract the second operand from the first operand. For example, a=30, b=20>>>
a-b=10
c. Multiplication(*) It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b =
200
d. Division(/)It returns the quotient after dividing the first operand by the second operand. For example, if a =
20, b = 10 => a/b = 2.If quotient is coning in float value then division results in a floating-point value.for ex-
ample a=11,b=2 >>> a/b Output: 5.5
e. Exponentiation(**)It returns the second operand power to first operand. a=2,b=3,a**b i.e. ab=8
f. Floor Division(//)It returns the integer value of the quotient. It dumps the digits after the decimal. a = 10,b =
3 => a//b = 3
g. Modulus(%)It returns the remainder after dividing the first operand by the second operand. For example, a =
20,b = 10 => a%b = 0
Relational Operators
Relational Operators are used to comparing the value of two operands It checks whether an operand is greater than
the other, lesser, equal, or a combination of those and returns the Boolean value i.e. True or False.
When the condition for a relative operator is fulfilled, it returns True. Otherwise, it returns False. This return
value can be used in a further statement or expression.
a. Less than(<) This operator checks if the value of first operand is less than the second operand. (i) 3<4 Out-
put True (ii)15<10 Output False
b. Greater than(>)It checks if value of first operand is Greater than the second operand.
>>> 3>4 Output: False
c. Less than or equal to(<=)It checks if the value of first operand is Less than or equal to the
second operand.>>> 7<=7 Output: True
d. Greater than or equal to(>=) It checks if the value of first operand is Greater than or equal to the second
operand. >>> 0>=0 Output: True
e. Equal to(= =)
It checks if the value of first operand is Equal to the second operand.1 is equal to the Boolean value True, other
than 1 is equal to False. (i) 5= =5 Output: True (ii)5= =8 Output: False
f. Not equal to(!=) It checks if the value of two operands is not equal.
(i) 5! =5 Output: False (ii)3!=2 Output: True
a. Assign(=) It assigns the the value of the right expression to the left operand., = = is used for comparing and =
is used for assigning.
a=10
print(a)
output :10
b. Add and Assign(+=) It increases the value of the left operand by the value of the right operand and assign
the modified value back to left operand.
a+ = b equal to a = a+ b
a+=10 equal to a=a+10
a=10 a=10 a=20
a+=20 b=20 a+=5*2
print(a) a+=b print(a)
output :30 print(a,b)
output:30
output:30,20
c. Subtract and Assign(-=)It subtracts the value of the left operand by the value of the right operand and as-
signs the modified value back to left operand.
a-= b equal to a = a- b
a-=10 equal to a=a-10
a=20 a=10 a=20
a-=5 b=50 a-=5*2
print(a) a-=b print(a)
output :15 print(a,b) output:10
output:-40,50
d. Divide and Assign(/=):It divides the value of the left operand by the value of the right operand and assigns
the modified value back to left operand.
a/= b equal to a = a/ b
a/=10 equal to a=a/10
e. Multiply and Assign(*=):It multiply the value of the left operand with the value of the right operand and as-
signs the modified value back to left operand.
a*= b equal to a = a*b
a*=10 equal to a=a*10
a=20 a=10 a=20
a*=5 b=20 a*=5*2
print(a) a*=b print(a)
output :100 print(a,b) output:200
output:200,20
f. Modulus and Assign(%=):It divide the value of the left operand by the value of the right operand and as-
signs the remainder value back to left operand.
a%= b equal to a = a% b
a%=10 equal to a=a%10
a=20 a=10
a%=5 b=20
print(a) a%=b
output :0 print(a,b)
output:10,20
g. Exponent and Assign(**=) :It performs exponentiation(power) the value of the left operand by the value of
the right operand and assigns the modified value back to left operand.
a**= b equal to a = a** b i.e. a=ab
a**=10 equal to a=a**10
a=2 a=5
a**=3 b=2
print(a) a**=b
output :8 print(a,b)
output:25,2
h. Floor-Divide and Assign(//=) :It Performs floor-division the value of the left operand by the value of the
right operand and assigns the modified value back to left operand.
a//= b equal to a = a// b
a//=10 equal to a=a//10
a=20 print(10//3)
a//=5 output:3
print(a)
output :4
Logical Operators
The logical operators are conjunctions that can be used to combine more than one condition. There are three
Python logical operator – and, or, and not that come under python operators.
a. and
If all the expressions are true, then the condition will be true.
a=10 a=10
b=20 b=20
a<b and b>15 c=40
output : True a>b and b<c and c= =40
output: False
b. or
If one of the expressions is true, then the condition will be true.
a=10 a=10 a=10
b=20 b=20 b=20
a<b or b>15 c=40 a>b or b>20
output : True a>b or b<c or c= =40 output : False
output: True
c. not
This inverts the Boolean value of an expression. It converts True to False, and False to True. If an expression a is
true then not (a) will be false and vice versa.
a=10 not 0 not “xyz” = =”xyz”
b=20 Output: True output: False
not a>b
output : True
in : It is evaluated to be true if the first operand is found in the second operand (string,list, tuple or dictionary).
“x” in “xyz” 5 in [10,20,30]
Output: True Output: False
not in: It is evaluated to be true if the first operand is not found in the second operand (string,list, tuple or dic-
tionary).
“x” not in “xyz” 5 not in [10,20,30]
Output: False Output: True
is: ’is’ operator returns true if both the operand point to same memory location. The variable having same value
point to same memory location; So, for them this operator returns a ‘true’.
a=10 a=”xyz” “x” is “xyz”
b=10 b=”xyz” Output: False
a is b a is b
Output :True output:True
is not : is not operator returns true if both the operand point to different memory location. It is the opposite of
‘is’ operator.
2 is not 2 “x” is not “xyz” 2 is not 2.0
Output :False Output: True Output:True
Identify operators compares the memory locations not the value. It is possible that objects has the same value
but not the same memory location. Assigning the value to string and taking the same value of string from con-
sole will have the different memory location.. For example
a=”abc”
b=”abc”
c=input(“enter name”)
print(id(a))
print(id(b))
print(id(c))
print(a is b)
print(b is c)
print(a is c)
Output:
enter name abc
5292768
5292768
39973344
True
False
False
In the above example the id of a and b is same but id of c is different even having the same value “abc”. If is
operator is used with a and c it will return False as shown in above example
Bitwise Operators
& | ^
Binary AND Binary OR Binary XOR
~ Binary << Binary >> Binary
Ones Comple- Left Shift Right Shift
ment
Q21 Which of the following are valid operators in Python ? 2 [comptt 19]
(i) +=
(ii) ^
(iii) in
(iv) &&
(v) between
(vi) */
(vii) is
(viii) like
Ans: (i) += (ii) ^ (iii) in (vii) is
Operator Precedence: The precedence of the operators is important to know which operator should be evalu-
ated first The precedence table of the operators in python is given below:
Operator Description
** The exponent operator is given priority over all the others used in the expression.
~+- The negation, unary plus and minus.
* / % // The multiplication, divide, modules, reminder, and floor division.
+- Binary plus and minus
>> << Left shift and right shift
& Binary and.
^| Binary xor and or
<= < > >= Comparison operators (less then, less then equal to, greater then, greater then
equal to).
<> == != Equality operators.
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Ex: Write the value that will be assigned to variable x after executing the following statement :
x = 3 + 36/12 + 2*5
Ans 16.0
Ex: Write the value that will be assigned to variable C after executing the following statement:
C = 25-5*4/2-10+4
Ans 9.0
Ex: Write the value that will be assigned to variable x after executing the following statement:
x = 20 -5 + 3 * 20/5
Ans 27.0
Data Types
The data type of a variable or object determines which operations can be applied to it. Once a variable is as-
signed a data type, it can be used for computations in the program.Python is a dynamically typed language;
hence we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the
value with its type.
Python has six standard Data Types:-
• Numbers
• String
• List
• Tuple
• Set
• Dictionary
Numbers: In Python, number data type represents the data that has a numeric value. The numeric value can be
an integer, floating number, or even complex number.
(i)Integers: It consists of positive or negative whole numbers (without fraction or decimal). In Python, there’s
no limit to how long integer values are often. Some examples of integers are 65 -76, 0,78 etc.
(ii)Float : The number that contain values with fractional parts is called float . It has values both before and
after the decimal point. Examples of floating-point numbers are 1.29, -8.7, 0.7, etc.
(iii)Complex: In the form of a+bj where a forms the real part and b forms the imaginary part of the complex
number. eg: 2+3j
String Data Type :A string is a sequence of characters surrounded by quotes. We can use single, double or triple
quotes for a string. For examples a= ‘hello’ or a=”hello” or a=’’’hello’’’ all are string.
List Data Type: The list is a most versatile datatype available in Python which can be written as a list of comma-
separated values (items) between square brackets([ ]). It can have any number of items and they may be of dif-
ferent types (integer, float, string etc.). Python lists are mutable type its mean we can modify its element after it
created.
Tuple Data Type: A Tuple is a collection of Python objects separated by commas.Tuples are written with round
brackets(parentheses are optional), whereas lists use square brackets.Tuple is immutable unlike lists which are mu-
table. we cannot change the elements of a tuple once it is assigned whereas, in a list, elements can be changed.
Dictionary Data Type: A dictionary in Python is just like a dictionary in the real world. Python Dictionary are
defined into two elements Keys and Values. Keys are unique within a dictionary while values may not be.
Set Data Type : A set is an unordered collection of items. Every set element is exclusive (no duplicates) and
must be immutable (cannot be changed).
Ex: Write the names of any four data types available in Python. 2[2019]
Ans Numbers
Integer
Boolean
Floating Point
Complex
Strings
Tuple
List
Sets
Dictionary
Q27 Write the data type of variables that should be used to store: (i) Marks of students (ii) Grades of
students(Grade can be ‘A’ or ‘B’ or ‘C’) 1[2018]
Ans (i) float/int (ii) string
Print Function
The print function in Python is used to display the output of variables: string, lists, tuples, range etc.
Following is the syntax of using the print function:
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
Where:
•The object can be strings, lists, tuple etc.
•The sep = ‘’ parameter specifies a space between multiple objects. You can use other than space by using this
parameter.
•The end=’\n’ means in each call, the print function will end at a new line, you can change that.
•The file=sys.stdout specifies where the print function should send the output. The default
•The flush keyword argument specifies whether to flush or not the output stream. The default value is false.
Ans (i)20$
(ii)40*50*60!
(iii)hello,hi,bye!
(iv)hello*hi*bye!
(v)False True@
(vi) 2*3,6*5
(vii)6+11
input() function
The input() method reads a line from input(usually user), converts into a string and returns it.
The syntax of input() method is:
input([prompt])
The input() method takes a single optional argument:
prompt (Optional) - prompt is the string we wish to display on the screen. It is optional
for example if you want to take a name(string value) from the user then you can use following code:
n=input(“enter name :”)
print (n)
output:
enter name: Raman
Raman
Remember that input() function always returns a string type value. What’s about the input of other data
types like int, float etc.? You have to use the same function to input any data type value from user at run time
but every value will be treated as string value.
age=input(“enter age”)
for example if you take age from user and user enter 18 value as age, this “18” will be treaetd as string value.
Any arthematic calculation like addition, substraction, multiplication etc can not be done with this value.
if you give command print(age+2), an error message will be raised because we can not add “18”+2 .
To overcome this problem we use type conversion function like int(),float() etc when taking these type of val-
ues.If you want to take age as integer type, you will write like this
age=int(intput(“enter age”))
The int() function convert sting value into integer . Similarly you can use float() or any other data conversion
method to convert value from string to other data type.
Ex: Ankur has written python code to accept cost price and add 25 to make it sale price. But when adding he is
getting some error message, help Ankur and rectify the code to remove the error message.
cost_price=input(“enter price”)
sale_price=cost_price+25
Ans
cost_price=int(input(“enter price”))
sale_price=cost_price+25
Implicit type conversion: In Implicit type conversion, Python automatically converts one data type to another
data type during compilation or during the run time. Python handles the implicit data type conversion, so we
don’t have to explicitly convert the data type into another data type.
Let’s take an example:
a=89.5
b=50
c=a+b
print(“sum=”,c)
print(type(c))
output
sum= 139.5
<class ‘float’>
In the above example, we have taken two variables a(float type) and b(integer type). We added a and b and
stored the result in another varibale named ‘c’. When we checked the data type of the c variable, we can see that
the data type of the c variable has been automatically converted into the float data type by the Python compiler.
This is called implicit type conversion. But one question arise here why was the c converted into float data type
integer instead?
Why was the float value not converted to integer instead?
Because the python complier follows the defense mechanism that allows to perform operations whenever pos-
sible by converting data into a different supertype without the loss of information.
That’s the reason c is not converted into integer,If c is converted into integer then the compiler will need to
remove the fractional part leading to the loss of information
Explicit type conversion : In Explicit Type Conversion, users convert the data type of an object to required
data type(forecefully). There are predefined functions like int(), float(), str(), etc to perform explicit type conver-
sion.
This type of conversion is also called type casting because the user casts (changes) the data type of the objects.
Syntax :
<required_datatype>(expression)
Let’s go over the following examples for explicit type conversion in Python.
# adding string and integer data types using explicit type conversion
a = 100
b = “200”
sum = a +int( b)
print(sum)
Output:
300
In the above example, the variable a is of the number data type and variable b is of the string data type. When
we try to add these two variables (a+b) without converting string into integer, a TypeError will occur So, in
order to perform this operation, we have to use explicit type casting.
As we can see in the above code block, we have converted the variable b into int type and then added variable a
and b. The sum is stored in the variable named sum, and when printed it displays 300 as output.
Q33 Write the output of the following Python code: 2 [SP 18]
i=5
j=7
x=0
i=i+(j-1)
x=j+1
print(x,”:”,i)
j=j**2
x=j+i
i=i+1
print (i,”:”,j)
Ans
8 : 11
12 : 49
Q34 Give the output if a=10 and b=20
a=input(“enter no”)
b=input(“enter 2nd no”)
print(a+b)
Ans 1020
Q35 write a program to take two nos and swap the nos
Ans:
a=int(input(“enter a”))
b=int(input(“enter b”))
a,b=b,a
print(a,b)
Q36 Write a program to take two numbers and show 2nd number is power of 1st . For example if 1st number is
5 and 2nd number is 3 then result is 53 = 125
Ans:
a=int(input(“enter 1st no “))
b=int(input(“enter power”))
print(a**b)
Q37write a program to take two nos and show the sum of these two nos
Ans:
a=int(input(“enter a”))
b=int(input(“enter b”))
print(a+b)
Q38 write a program to take two float numbers and show the sum of these two.
Ans:
a=float(input(“enter a”))
b=float(input(“enter b”))
print(a+b)
Q39 Write a program to take first name and last name from user and show full name. For example if first name is
“Aman” and last name is “Sharma” then it will display “AmanSharma”(without space).
Ans:
first=input(“enter 1st name”)
last=input(“enter last name”)
print(first+last)
(ii)a=20
b=30
a,c=b*10,a/10
print(a,b,c)
(iii) a=10
b=a*20
b,c=b*10,a%10
print(a,b,c)
Ans : 10 2000 0
MCQ(Python Fundamentals)
Q1 Identify invalid variable name out of the following.
a. salary_123, b. 123salary, c. salary123, d._123salary
Q4 17//3=
a. 5.666666666666667 b.2 c.5.67 d.5
Q6.** is a ___________
a. Arithmetic operator b.Relational operator c.Assignment Operator d. Logical Operator
Q7 “and” is a ________________
a. Arithmetic operators b.Relational operators c.Assignment Operators d.Logical Operators
10.“18,0” is __________
a. int literal b. float literal c.string literal d.none literal
Ans : 1(b) 2(d) 3(a) 4(d) 5(d) 6(a) 7(d) 8(d) 9(c) 10(c)
Q Write a program to take input marks of 3 subjects and show the sum and percentage.
Q Write a program to take input Basic, DA and HRA of an employee and show the total salary. Total Salary is
the sum of Basic+DA+HRA
Q Write a Program to take Price and Qty as input and show the total price.
Q Write a Program to take income as input and calcluate the 40% tax. Show the tax and income after tax.
Q Write a Program to take Principal, Rate and Time as input and show the Simple Interest.
Q Write a Program to take Salary as input and calculate the followings:
HRA : 20% of Salary
DA : 10% of Salary
Gross Salary : Salary+DA+HRA
Tax : 20 % of Gross Salary
Net Salary= Gross Salary-Tax