lucknow public schoolsouthcity.thelps.edu.in/uploadedfiles/update... · by gajendra singh dhami,pgt...
TRANSCRIPT
LUCKNOW PUBLIC SCHOOL
SESSION-2019-20
STUDY MATERIAL
FRAGMENT 1
SUBJECT: INFORMATICS PRACTICES(065)
CLASS-XI
CHAPTERS INCLUDED:
CHAPTER 1: GETTING STARTED WIYH PYTHON
CHAPTER 2: PYTHON FUNDAMENTALS
CHAPTER 3: DATA HANDLING
CHAPTER 4: CONDITIONAL ITERATIVE STATEMENTS
TEACHERS’ CONTRIBUTORS:
GAJENDRA SINGH DHAMI, PGT (CS), SOUTH-CITY
MOHIT TANDON,PGT(CS),SECTOR-D
NEERU NIGAM,PGT(CS),SECTOR-I
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 1
Chapter 2: Getting Started With Python
Introduction:
Python is a widely used programming language. It was created by Guido van Rossum,
and released in 1991.
The language is named after the BBC show “Monty Python‟s Flying Circus” and has
nothing to do with reptiles. Python is a high-level, dynamically typed programming language. Python code is
often said to be almost like pseudo code (similar to programming code), since it allows you to express very powerful ideas in very few lines of code while being very
readable.
Features of python:
• Easy to use and Expressive language – Due to simple syntax rule less code to be
written as it itself express the purpose of the code.
• Interpreted language – Code execution & interpretation line by line
• Cross-platform language – It can run on windows, Linux, Macintosh etc. equally
and making it portable.
• Expressive language –Multi Paradigm programing language (Object Oriented
Programming, Procedural etc.)
• Completeness – Support wide range of libraries.
• Free & Open Source – Can be downloaded freely and source code can be
modified for improvement
• It is case sensitive i.e lower case and uppercase alphabets are treated differently
(like „a‟ is different from „A‟
Applications of Python:
• Python can be used on a server to create web applications.
• Python can be used for software development.
• Python can connect to database systems and access data.
• Python can be used to handle big data and perform complex mathematics.
• It is extensively used for data science and machine learning programming.
Execution of a program in various languages: As computer understands only binary
signals and any program written in high level language (c,c++,Python,java,etc) is
required to be translated into machine form .There are language processors that
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 2
converts a source written in high level language into machine code for execution by
hardware.
There are two main language processor used with different approach:
Compiler
interpreter
Interpreter Compiler
Translates program one statement at a
time.
Scans the entire program and translates it
as a whole into machine code.
It takes less amount of time to analyze
the source code but the overall execution time is slower.
It takes large amount of time to analyze
the source code but the overall execution time is comparatively faster.
No intermediate object code is generated, hence are memory efficient.
Generates intermediate object code which further requires linking, hence requires
more memory.
Continues translating the program until
the first error is met, in which case it stops. Hence debugging is easy.
It generates the error message only after
scanning the whole program. Hence debugging is comparatively hard.
Programming language like Python,
Ruby use interpreters.
Programming language like C, C++ use
compilers.
Case Of Interpreter
Case Of Compiler
Working with python:
We can use various software distribution(collection of packages) to use python for programming. Following are some popular software package distribution:
Cpython distribution : It is the provided by the python software foundation.
Anaconda distribution: It comes with preloaded packages and libraries.
SOURCE CODE IN HIGH
LEVEL LANGUAGE INTERPRETER OUTPUT
SOURCE CODE IN HIGH
LEVEL LANGUAGE COMPILER OBJECT CODE LINKING OUTPUT
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 3
You can use many more Interactive environment for rapid program development, after installing python. Following are some example of IDE‟s
IDLE: comes with default python installation. Spyder IDE: available with Anaconda distribution pyCharm IDE, Pyscripter IDE, etc.
(Integreted Development EnvironMent)IDE: Provides many user friendly interactive tools for rapid software development.
Install and use python(Cpython Distribution):
As python is open source you can download it freely from www.python.org and
install it on your system.
It comes with following:
Python Interpreter
Python IDLE
Pip (package installer)
IDLE: IDLE is Python‟s Integrated Development and Learning Environment for
writing python statement and programs using limited GUI tools.
You can work in Python IDLE in two ways:
Interactive mode: Writing one line command at a time and interpreting it
immediately by pressing enter key.
Script mode: It allows user to write one or more python statements and saving
them in the form of a program file( like abc.py).
Interactive mode: „>>>‟. This is a primary prompt indicating that the interpreter is expecting a
python command. There is secondary prompt also which is „…‟ indicating that interpreter is waiting for additional input to complete the current statement.
Let us now open python IDLE and start working
As you open Python IDLE it opens Python shell.
Click Start-> IDLE to open Python
shell
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 4
Python shell displays the prompt >>> and is ready to accept command from user.
Type some expression and see immediate response by Python Interpreter
Using python as a calculator (Interactive mode)
‘>>>’ type your command or statement here
+ for Addition
* for Multiplication
% for finding Remainder
** for Exponent i.e raise to power
/ for Division
- For subtraction
Immediate output
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 5
It is also possible to get a sequence of instructions executed through interpreter in Interactive mode also.
Note: Above program is not saved for future modification.
Use script mode for program naming and saving it for future modification
Script mode: In script mode, we type Python program in a file and then use
the interpreter to execute the content from the file.
You can see simple statements like mathematics
are used to find sum of two numbers
print( ) is used in Python to display data
In the next chapters you will get to know about
Python programming fundamentals
File-> New or press ctrl+N to open editor
and write statements in Python
File-> Save or press Ctrl+S to open save Dialog box
and give program name and press ok
Python script have .py extension
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 6
Understanding print(): it is one of the important statement that is used to
display the data on screen.
Syntax:
print(value1,value2,…,sep=’ ‘,end=’\n’)
value1,value2,.. : one or more values(eg. Message,variable,expression,literals
etc)
sep: reserved word that specifies the separator type, used to separate values
( when no separator is given by user, space ‘ ‘ will be used as default)
end: it sets the character to end the print statement; user can provide any
character (new line’\n’ is by default)
Let us understand print()using following examples:
Click Run-> Run module or press F5 to Execute program
Output is displayed in Python shell
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 7
Overview of Spyder IDE:
IDLE is the default IDE available with Python package when users download and
install Python from python.org. It is provided by the python software foundation.
There are other IDE‟s also available that can provide more user friendly features and
advance tools for Python programming. One such IDE is Spyder.
Spyder IDE comes preloaded with Anaconda distribution. When user installs
Anaconda package Spyder IDE is installed along with other software tools like Jupiter
notebook (web based environment for python programming).
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 8
Snapshot of Spyder IDE:
You can see script editor, console window (Interactive mode) and other features are
present in the same working area.
Note:
It is better to start with IDLE at the initial stages for Python programming and
later on switch to Spyder IDE.
Assignments:
1. Write four important features of python.
2. Name the creator of Python.
3. Write some areas where Python applications are used.
4. Define IDE. Give difference between IDLE and Spyder IDE’s.
5. Explain cross platform and open source features of Python.
6. What does Multi paradigm means in programming?
7. Give difference between Compiler and Interpreter.
8. Give advantage of script mode compared to Interactive mode.
Script Editor
window pane
Interactive mode
window pane
COMPUTER SCIENCE/XI-STUDY MATERIAL CHAPTER 2: Getting Started With Python
By GAJENDRA SINGH DHAMI,PGT CS, Lucknow Public School ,South City 9
9. Fill in the blanks:
a. _____ is the default IDE for Python.
b. Every Python script has ______ extension.
c. Spyder IDE is part of ______________ distribution package.
d. ________ feature of Python makes it portable to various operating
systems.
e. ______ statement is used to print data on output window.
f. In __________ mode we can save program.
g. Python ______ is the interface that accepts commands from user.
10. Write a statement to display the following outputs:
a. Welcome***to###Lucknow&&&
b. 3…4…5…6,,,
c. Write a script to display following:
Monty
Python
Flying Circus
11. What output the following statements will generate on output window?
a. >>>4+6/3-3
b. >>>3**3
c. >>>2**2**4
12. Give the output of following script:
R=12
W=15
S=W+R
print(W,”+”,R,”=”,S,sep=’%’,end=’!!!’)
Python Character Set
Python uses the character set to declare identifier as given below:
• Letters A-Z , a-z • Digits 0-9 • Special Symbols Space + - * / ^ \ ( ) [ ] { } = != < > . „ “ $ , ; : % ! & ? _ # <= >= @ • White Spaces Blank spaces, horizontal tab, carriage return newline, form feed etc.
BY: MOHIT TANDON PGT(CS) LPS SEC-D
• Other characters: Python can process all characters of ASCII and UNICODE.
Tokens in Python
The smallest individual unit of the program is known as Token.There are five types of Tokens in Python:
1. Keywords 2. Identifiers 3. Literals 4. Delimiters 5. Operators
Keywords
Keywords are those words which provides a special meaning to interpreter.
These are reserved for specific functioning.
These can not be used as identifiers, variable name or any other purpose.
Available keywords in Python are-
Study Material – IP-XI Chap-3 : Python Fundamentals 1
CHAPTER – 3 : PYTHON FUNDAMENTALS
Study Material – IP-XI Chap-3 : Python Fundamentals 2
Identifiers
These are building blocks of a program and are used to give names to different
parts/blocks of a program like - variable, objects, classes,functions.
• An identifier may be a combination of letters and numbers.
• An identifier must begin with an alphabet or an underscore( _ ).Subsequent letters may
be numbers(0-9).
• Python is case sensitive. Uppercase characters are distinct from lowercase characters
(P and p are different for interpreter).
• Length of an Identifier is unlimited.
• Keywords can not be used as an identifier.
• Space and special symbols are not permitted in an identifier name except an
underscore( _ ) sign.
• Some valid identifiers are –
– Myfile, Date9_7_17, Z2T0Z9, _DS, _CHK FILE13.
• Some invald identifiers are –
– DATA-REC, 29COLOR, break, My.File.
Literals / Values
• Literals are often called Constant Values. • Python permits following types of literals –
– String literals - “Pankaj”
– Numeric literals – 10, 13.5, 3+5i
– Boolean literals – True or False
– Special Literal None
– Literal collections
String Literals
• String Literal is a sequence of characters that can be a combination of letters, numbers and special symbols, enclosed in quotation marks, single, double or triple(„ „or “ “ or “”” “””).
• In python, string is of 2 types- – Single line string
• Text = “Hello World” or Text = “Hello World – Multi line string
• Text = “hello\ or Text = “””hello World” world “””
Study Material – IP-XI Chap-3 : Python Fundamentals 2
Study Material – IP-XI Chap-3 : Python Fundamentals 3
Numeric Literals • Numeric values can be of three types - – int (signed integers)
• Decimal Integer Literals – 10, 17, 210 etc. • Octal Integer Literals - 0o17, 0o217 etc. • Hexadecimal Integer Literals – 0x14, 0x2A4, 0xABD etc.
– float ( floating point real value) • Fractional Form – 2.0, 17.5 -13.5, -.00015 etc. • Exponent Form - -1.7E+8, .25E-4 etc.
– complex (complex numbers) • 3+5i etc.
Boolean Literals • It can contain either of only two values – True or False
A= True B=False
Special Literals • None, which means nothing (no value).
X = None
Delimiters
Delimiters are symbols that perform three special roles in python like grouping, punctuation and assignment/ binging of objects to names. Grouping and punctuation delimiters are all written as one character symbols.
Delimiters Classification
( ) { } [ ] Grouping
. , ; : @ Punctuation
= += - = *= /= etc Arithmetic assignments
&= != ^= <<= >>= Bitwise assignment binding
Study Material – IP-XI Chap-3 :: Python Fundamentals 3
Study Material – IP-XI Chap-3 :: Python Fundamentals 4
Operators
Operators are special symbols which represents computation. They are applied on
operand(s), which can be values or variables. Same operator can behave differently on
different data types. Operators when applied on operands form an expression. Operators
are categorized as Arithmetic, Relational, Logical and Assignment. Value and variables
when used with operator are known as operands.
Types of Operators
• Python supports following types of operators -
– Unary Operator
• Unary plus (+)
• Unary Minus (-)
• Bitwise complement (~)
• Logical Negation (not)
– Binary Operator
• Arithmetic operator (+, -, *, /, %, **, //)
• Relational Operator(<, >, <=, >=, ==, != )
• Logical Operator (and, or)
• Assigment Operator (=, /=, +=, -=, *=, %=, **=, //=)
• Bitwise Operator (& bitwise and, ^ bitwise xor, | bitwise or)
• Shift operator (<< shift left, >> shift right)
• Identity Operator (is, is not)
• Membership Operator (in, not in)
Study Material – IP-XI Chap-3 :: Python Fundamentals 4
Study Material – IP-XI Chap-3 :: Python Fundamentals 5
Arithmetic Operators:
Study Material – – IP-XI Chap-3 :: Python Fundamentals 5
Study Material – CS-XI Chap-2 : Python Fundamentals 6
Relational Operators
Study Material – IP-XI Chap-3 :: Python Fundamentals 6
Study Material – CS-XI Chap-2 : Python Fundamentals 7
Logical Operators
Assignment Operators
Study Material – IP-XI Chap-3 :Python Fundamentals 7
Study Material – IP-XI Chap-3 :Python Fundamentals 8
Study Material – IP-XI Chap-3 :: Python Fundamentals 8
Study Material – IP-XI Chap-3 :: Python Fundamentals 9
Associativity
An operator may be Left-associative or Right – associative. In left associative, the operator falling on left side will be evaluated first, while in right associative operator falling on right will be evaluated first.
In python "=" and "**" are Right Associative.
Python print() Function
The print() function prints the specified message to the screen, or other
standard output device.
The message can be a string, or any other object, the object will be converted into a string before written to the screen.
The print() function inserts a new line at the end, by default.
Example
To Print a message onto the screen:
print("Hello”) print(“World")
output:- Hello
World
In Python 3, "end=' '" appends space instead of newline.
print(x, end=" ")
Example
print("Hello”,end=” “) print(“World")
output:-
Hello World
Example:- Print more than one object: print("Hello", "how are you?")
output:- Hello how are you?
Study Material – IP-XI Chap-3 :: Python Fundamentals 9
Study Material – – IP-XI Chap-3 :Python Fundamentals 10
Example Print two messages, and specify the separator: print("Hello", "how are you?", sep=" ---")
output:-
Hello --- how are you?
Python input() Function
The input() function allows user to give input of data. Syntax <variable>=input(“message”)
Example x = input('Enter your name:') print('Hello ' , x)
NOTE: input() returns the entered value in the form of string , so if you want to perform some arithmetic operation then you have to convert this numeric string to integer or float value using int() or float() functions respectively
Example:-
>>> num = input('Enter a number: ') Enter a number: 10 >>> num '10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.
a=int(input('enter first number')) b=int(input('enter second number')) c=a+b print(c)
Example-2:
radius=float(input('enter radius of a circle)) area=3.14*radius*radius print(area)
Study Material – IP-XI Chap-3 :Python Fundamentals 10
Study Material – IP-XI Chap-3 :: Python Fundamentals 11
A PYTHON Program Structure
A python program may contain the following components: – Expressions like a+b, a>b etc. – Statements like a=10, c=a+b etc. – Comments, lines starting with #. – Function, block starting with def keyword – Blocks and indentation like if and else blocks
Study Material – IP-XI Chap-3 :: Python Fundamentals 11
Study Material – IP-XI Chap-3 :: Python Fundamentals 12
SOLVED QUESTIONS
Q1. How many types of sequences are supported in Python? Ans: Three Types of Sequences are supported in python:
(i) String
(ii) List
(iii) Tuple
Q.2 What factors guide the choice of identifiers in program? Ans: (i) An identifier must start with a letter or underscore followed by any number of
digits and/or letters.
(ii) No reserved word or standard identifier should be used.
(iii) No special character (Other than underscore) should be included in the identifier.
Q.3 What is the difference between an expression and a statement in Python? Ans: A statement is an instruction that the Python interpreter can execute. We have only
seen the assignment statement so far. Some other kinds of statements are while
statements, forstatements, if statements, and import statements.
An expression is a combination of values, variables, operators, and calls to functions.
Expressions need to be evaluated. If you ask Python to print an expression, the
interpreter evaluates the expression and displays the result.
Q.4 What are operators? What is their function? Give examples of some unary and binary operators. Ans: Operators are those symbols used with operands, which tells compiler which
operation is to be done on operands. In other words – “operators are tokens that
trigger some computation/action when applied to variables and other objects in an
expression.”
Operators are of following types:
Unary operators like (+) Unary Plus, (-) Unary Minus, not etc.
Binary Operators like (+) addition, (*) multiplication, and etc.
Q.5 What is block/code block/suit in Python?
Ans: Sometimes a group of statements is part of another statement of function. Such a group of one or more statements is called block or code-block or suit in python. e.g.
Study Material – – IP-XI Chap-3 :Python Fundamentals 12
Study Material – – IP-XI Chap-3 :Python Fundamentals 13
Q.6. What is the role of indentation in Python? Ans: Indentation plays a very important role in Python. Python uses indentation to create blocks of code. Statements at same indentation level are part of same block/suit. You cannot unnecessarily indent a statement; python will raise an error for that.
Q.7.What will be the sizes of following constants?
(a) “\a‟ (b) “\a” (c) “Kumar\‟s” (d) “\”‟ (e) “it‟s”
Ans: (a) 50 (b) 50 (c) 56 (d) 50 (e) 53
OUTPUT SCREEN:
Q.8 Which of the following are syntactically correct strings? State reason. (a) ”Python is nice Language”
(b) „He called me “Friend!” when he came‟
(c) “Very Good‟
(d) „This is a good book‟ (e) “Namaste
(f) “I liked „Harry Potter‟ very much”
Ans: (a) Correct (b) Correct (c) Incorrect (d) Correct (e) Incorrect (f) Correct
Q.9 What is the error in following Python program with one statement? print(“My name is : “, name) suggest a solution
Ans: Error is : “name 'name' is not defined”. And the solution is to declare the variable- name before this statement.
Study Material – – IP-XI Chap-3 :: Python Fundamentals 13
Study Material – IP-XI Chap-3 :: Python Fundamentals 14
Q.10 Predict the output of the following:
Ans: Output: 17 5
Q.11 What will be the output of the following code:
Ans: Output: Hari , you are 18 now but You will be 19 next year Ans: Output: 17 5
Q.12 WAP to read todays date (only date Part) from user. Then display how many days are left in the current month.
Q.13 WAP to find area of a triangle.
Study Material – IP-XI Chap-3 :: Python Fundamentals 14
Study Material – CS-XI Chap-2 : Python Fundamentals 15
Q.14 What will be the output of the following ?
Ans: 4 4.25 1 4
ASSIGNMENT
Q.1 What is the difference between a keyword and an identifier?
Q.2 How many types of strings are supported by Python?
Q.3 How can you create multi-line strings in Python?
Q.4 Write a Program to obtain temperature in Celsius and convert it into Fahrenheit using formula – C X 9/5 + 32 = F
Q.5 Predict the output:
Q.6 WAP to print the area of circle when radius of the circle is given by user.
Q.7 WAP to print the volume of a cylinder when radius and height of the cylinder is given by user.
Q.8 WAP that asks your height in centimeters and converts it into foot and inches.
Q.9 WAP to input principal amount, rate of interest and time (in years) and
calculate (i) SIMPLE INTEREST (ii) COMPOUND INTEREST
Q.10 WAP to read a number n and prints n2, n3, n4
Q.11 What will be the output of the following
(a)12/4 (b)14//14
(c)14%4 (d) 14.0/4
(e) 14.0//4 (f)14.0%4
Study Material – IP-XI Chap-3 :: Python Fundamentals 15
Study Material – IP-XI Chap-3 :: Python Fundamentals 16
Q.12 Predict the output of the following code:
Days=int(input(“Enter Days”))*3600*24
Hours=int(input(“Enter Hours”))*3600
Minutes=int(input(“Enter minutes”))*60
Seconds=int(input(“Enter Seconds”))
Time=Days+Hours+Minutes+Seconds
print(“The amount of seconds=”,time)
if the inputs are given in this order: 1,2,3,4
Q.13 WAP to take the temperatures of all 7 days of the week and displays the average
temperature of that week.
Q.14 WAP to take value of x,y,z from the user and calculate the equation
Q.15 What will be the output of the following?
MULTIPLE CHOICE QUESTIONS Question 1 What is the output of the following code :
print 9//2
a. 4.5
b. 4.0
c. 4
d. Error
Question 2 Which function overloads the >> operator?
a. more()
b. gt()
c. rshift()
d. None of the above
Question 3 Which operator is overloaded by the or() function?
a. ||
b. |
c. //
d. /
Study Material – IP-XI Chap-3 :Python Fundamentals 16
Study Material – CS-XI Chap-2 : Python Fundamentals 17
Question 4
What is the output of the following program : i = 0 while i < 3:
print i i++ print(i+1)
a. 0 2 1 3 2 4
b. 0 1 2 3 4 5
c. Error
d. 1 0 2 4 3 5
Question 5
Which is the correct operator for power(xy)? a) X^y b) X**y c) X^^y d) None of the mentioned
Question 6
Which one of these is floor division?
a) /
b) //
c) %
d) None of the mentioned
Question 7
What is answer of this expression, 22 % 3 is?
a) 7
b) 1
c) 0
d) 5
Question 8
Mathematical operations can be performed on a string. State whether true or
false.
a) True
b) False
Study Material – IP-XI Chap-3 :: Python Fundamentals 17
Study Material – CS-XI Chap-2 : Python Fundamentals 18
Question 9
Operators with the same precedence are evaluated in which manner?
a) Left to Right
b) Right to Left
c) Can’t say
d) None of the mentioned
Question 10
What is the output of this expression, 3*1**3?
a) 27
b) 9
c) 3
d) 1
Question 11
Which one of the following have the same precedence?
a) Addition and Subtraction
b) Multiplication and Division
c) Both Addition and Subtraction AND Multiplication and Division
d) None of the mentioned
Question 12
The expression Int(x) implies that the variable x is converted to integer. State
whether true or false.
a) True
b) False
Question 13
Which one of the following have the highest precedence in the expression?
a) Exponential
b) Addition
c) Multiplication
d) Parentheses
Study Material – IP-XI Chap-3 :: Python Fundamentals 18
Study Material – IP-XI Chap-3 :Python Fundamentals 19
Question 14
Is Python case sensitive when dealing with identifiers?
a) yes
b) no
c) machine dependent
d) none of the mentioned
Question 15
Which of the following is an invalid variable? a) my_string_1 b) 1st_string c) foo d) _
Question 16
Which of the following is not a complex number?
a) k = 2 + 3j
b) k = complex(2, 3)
c) k = 2 + 3l
d) k = 2 + 3J
Question 17
Which of the following is incorrect? a) x = 0b101 b) x = 0x4f5 c) x = 19023 d) x = 03964
Question 18
What does 3 ^ 4 evaluate to? a) 81 b) 12 c) 0.75 d) 7
Question 19
The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same. State whether
true or false.
a) True
b) False
Study Material – IP-XI Chap-3 :: Python Fundamentals 19
Study Material – CS-XI Chap-2 : Python Fundamentals 20
Question 20
The value of the expression:
4 + 3 % 5 a) 4
b) 7
c) 2
d) 0
Question 21
Which of the following operators has its associativity from right to left?
a) +
b) //
c) %
d) **
Question 22
What is the value of the following expression?
2+4.00, 2**4.0 a) (6.0, 16.0)
b) (6.00, 16.00)
c) (6, 16)
d) (6.00, 16.0)
Question 23 Which of the following is the truncation division operator?
a) /
b) %
c) //
d) |
Question 24
What is the output of the following expression:
print(4.00/(2.0+2.0))
a) Error
b) 1.0
c) 1.00
d) 1
Study Material – IP-XI Chap-3 :: Python Fundamentals 20
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
1
Notes By: NEERU NIGAM,PGT(CS), LUCKNOW PUBLIC SCHOOL,SECTOR-I
CHAPTER 4: DATA HANDLING
Data types in any computer language, actually provides the flexibility or restriction of working. Data type
means the type of values one can have under a specific computer language. The more data types a
computer language offers, the more flexible user feels to work in that computer language.
To learn the basics of any computer language, it is a must to know the different data types offered or
available in that computer language.
Let us learn to know the different data types available in Python language.
Python has five standard Data Types, they are as follows:-
1. NUMBERS
2. STRING
3. LIST
4. TUPLE
5. DICTIONARY
NUMBERS : - As the name suggests, Numbers data type is used to interact with numeric type of
values. The numbers in Python have following core data types :
Integers : Integers are whole numbers . They have no fractional parts. Integers can be positive or
negative.
There are three types of integers in Python
i. Plain Integers : It is the normal intger representation and it uses 32 bits ( 4 bytes ) to store a
value. It can hold numbers from -2147483648 to 214783647.
ii. Long Integers : The numbers larger than the range of plain integers are known as long
integers. There is no size limit to store a long integer in Python. This means long integers
have an unlimited range, subject to available memory only.
iii. Booleans : These represent the truth values False and True. The Boolean type is a subtype of
plain integer, and Boolean values False and True behave like the values 0 and 1.
2. Floating Point Numbers : A number having fractional part is a floating-point
number,For example, 23.455 ,The decimal point signify that it is a floating point
integer.
3. Complex Numbers : A complex number is made up of both real and imaginar
componenets. Python represents complex numbers in the form A + B j. That is, to
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
2
represent imaginary number, Python uses j in place of conventional i. That means, in
Python j = √-1 .
Example :
Here a and b are storing two complex numbers in Python
a = 4 + 3.5 j
b = 4.5 + 7 j
in the above example ,in a complex number, 4 is the real component and 3.5 is
the imaginary component of the complex number a.
2. STRINGS : Strings are sequences of character data. The string type in Python is
called str. Python offers two string types: [1] ASCII strings – normal strings [2] UNICODE
strings.String literals may be delimited using either single or double quotes. All the
characters in between the quotes are the contents of the string.
1. ASCII string : also known as str type strings. This string type holds string of zero or more
ASCII characters. For example:
‘lucknow’ , “big453”, “ good morning”
2. UNICODE string : This string type can hold strings containing Unicode characters. Unicode
strings are written as – normal strings prefixed with letter u. for example
u ‘lucknow’ , u “big453”
3. LIST : Lists are a very useful variable type in Python. A list can contain a series of values. List
variables are declared by using square [ ] brackets. A list in Python represents a list of comma-
seprated value of any datatype between square brackets.All lists in Python are zero-based indexed.
When referencing a member or the length of a list the number of list elements is always the number
shown plus one.
For example :
A = [ ] it is a blank list variable
B =[ 1, 23, 55, 66 ] # it is a list of numbers
Name = * ‘ABHAY’ ,’ BABITA’,’CHARU’,’DILIP’,’MAMTA’+ # is a list of strings
X = * ‘ Neha’, 45,89,88,89+ # is a list of mixed values
Print name[2] will print the name at index 2, that is CHARU
NOTE : The elements of a list can be
a. Appended
b. Removed
c. Edited
How to change values of a list :-
Let us consider a list M =[ 45, 87,34, 23,88]
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
3
1. If the second element has to be changed then,
>>> M[1] = 50 , will replace/ change 87 from 50
4. TUPLE : Tuples are a group of values like a list and are manipulated in similar ways. But , tuples
are fixed in size, once they are assigned. In Python the fixed size is considered immutable as compared
to a list that is dynamic and mutuable, or in other wors tuples are those lists which can not be changed
or modified. Tuples are represented as a list of comma-separated values of any data type within
parenthesis.
Tuples are defined in parenthesis ( )
City = ( ‘ KANPUR’, ‘ LUCKNOW’, ‘ AGRA’, ‘ ALLAHABAD’ )
Some advantages of tuples over lists :
1. Tuples have no append or extend method .
2. Elements cannot be removed from a tuple.
3. One can use the IN operator, to check if an element exists in the tuple or not
4. Tuples are faster than the lists
5 DICTIONARY : Dictionary is an unordered set of comma-seprated key : value pairs with { }, with the
requirement that ithin a dictionary, no two keys can be same.
Example :
V = ,‘a’ : 1 , ’e’ : 2 , ’I’ : 3 , ’o’ : 4 , ’u’ :5 -
>>> V ,‘o’-
Will print 4
MUTABLE AND IMMUTABLE TYPES
The Python data objects can be broadly categorized in to two – mutable and immutable types, or in
simple words modifiable and non-modifiable types.
Immutable types : The immutuable types are those that can never change their value. In
Python, following types are immutable : integers, floating –point numbers, Boolean, strings
and tuples.
Mutable Types : The mutable types are those whose values can be changed . Lists and
dictionary are mutable type.
Python is an object oriented language, hence every entity that stores any values is called
as an object. That means all data or values are referred as object in Python. Every Python object
has three key attributes associated to it:
1. The type of an object : The type of an object determines the operations that can be performed on
the object. Built-in function type ( ) returns the type of an object :
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
4
Example :
>>> x = 10
>>> type (x)
< class’int’>
>>> type (5)
<class ‘int’>
2. The value of an object : it is the data-contained in the object.
for example :
>>> z = 78
>>> print z
78 will print the content of z, ie 78
>>>print 78
78
3. The id of an object : it is generally the memory location of the object
example :
>>> x =5
>>> id (x)
30876543 will print the memory location of the variable x.
OPERATORS IN PYTHON : Python offers these types of operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Membership operators
6. Identity operators
ARITHMETIC OPERATOR : These operators are used for doing calculations. Following are the
arithmetic operators in Python :
Operator sign Objective
+ Addition
- Subtraction
* Multiplication
/ Division
// Floor division
% Remainder
** exponenetiation
For example :
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
5
1. 4 + 6 results 10
2. X + 5 (x=9) results 14
3. X + y ( x= 6, y = 3) results 9
4. 10 – 3 results 7
5. A – 7 ( A =3 ) results -4
6. 4 * 3 results 12
7. A * B ( A=5, B=3) results 15
8. 20 / 4 results 5
9. X / y ( x= 35, y = 5 ) results 7
10. 15.9 / 3 results 5.3
11. 15.9 // 3 results 3.0, the fractional part is discarded
12. 23 % 5 results 3
13. 7.2 % 3 results 1.2
14. 2 ** 4 results 16 ( 24 )
Relational Operators : These operators are used to compare two entities or quantities. They are
used for decision making. The result returned from comparison is either true or false. Following
are the relational operators:
Sign meaning
< less than
<= less than or equal to
>= greater than or equal to
> greater than
= = equals to
!=, <> not equal to
3 Logical operators : These operators are used in conjunction with relational operators.
Whenever two or more conditions are to be checked, than logical operators are used with
relational operators. There are only three logical operators, they are
Or, and , not
When either of the condition should be true , than we must use or operator
When both of the conditions should be true, thanwe must use and operator
Not operator always negates the condition.
Point to remember
Let use consider two variables X and Y, in case of OR
X y result
T T T
T F T
F T T
F F F
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
6
When AND operator is used:
X Y result
T T T
T F F
F T F
F F F
Use of NOT
Not true = false
Not false = true
For example : if variable x = 5, and y = 7 then
X > 3 and y < 8 will result true
X > 3 and y > 8 will result false
X > 3 or y > 8 will result true
! x >3 will result false
Operator precedence
Operator description
( ) parenthesis
** exponentiation
*, / , // , % multiplication, division, floor division, remainder
+ , - addition, subtraction
<,<=,>,>=,<>,!=,== relational operators
Not logical operator
And logical operator
Or logical operator
Expressions : An expression in Python is any valid combination of operators, literals and
variables. An expression is composed of one or more operations. Following are the types of expressions,
we can have
i. Arithmetic Expression : when numbers and arithmetic operators are used, forms and
arithmetic expression. Following are the categories of the arithmetic expressions
1. Pure Expressions : when any expression has all operands of numeric type, then it forms
a pure expression
1.1 Integer expression : all operands are integer. Ex a+b , x ** y, where a , b, x and y are
integer variables
1.2 Real expression : when all operands are real numbers. For ex : a +b , x / y , where a, b, x
and y all are floating point variables
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
7
1.3 Complex number expression : when all the operands are complex numbers. For ex : 10
+ 2J * ( 3 + 3.5 j)
2. Mixed Expressions : when an expression has different types of operands, then it is
mixed expressions. For ex : a + 3.5 ,
a. Relational Expressions: An expression having literals/ variables and relational operators,
form a relational expression
P > q , p < = q , p >=q, p == q, p!=q
b. Logical Expression: An expression having literals and/ or variables and a logical
operator forms a logical expression
x or y , p and q , not p , not a or not b
ii. String Expression: Python has two string operators + and *, where + is called the
concatenation operator and * is known as replication operator.
“good”+”morning” would result ‘goodmorning’
“good”*3 would result “goodgoodgood”
ASSIGNMENT
Q.1 What will be the output of the following statement when the inputs are :
1. a =10, b= 23, c=23
2. a=23, b=10, c=10
Print a < b
Print b <= c
Print a< b <=c
Answer (1) for input combination given as (1), the result would be
True
True
True
For input combination given as (2), the result would be
False
True
False
Q.2 Identify the data types of the values given below:
5 , 34.9, u”34”, ( 3 , 2, 4) , 4j , *12,45,33+
Answer
5 plain integer
34.9 floating-point number
U “34” Unicode string
(3,2,4) tuple
4j complex number
[12,45,33] list
Q.3 What will be the output of the following code
7 < 8 or 10
6 < ( 12 0r 6 )
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
8
5 < ( 5 or 10 )
Answer
True true or 10 = true
True 6 < 12 = true
False 5 < 5 = false
Q.4 Write the output of the following
a. print (“ MyPython” * 3)
print( 3 * “MyPython”)
b. print ( not ( 3 < 4 and 4 < 5 ))
print ( not ( 3 < 4 or 4< 5 ))
answer
a. MyPythonMyPythonMyPython
MyPythonMyPythonMyPython
b. False
false
Q.5 Write the output of the following
x , y = 5 , 6
Print ( 1, x == 5)
Print( 2, x == 6)
Print (3, x == 5 and y == 6 )
Print ( 4, x==6 and y == 6 )
Print (5, not x == 6 and y == 6 )
Answer. The output is
1 True
2 False
3 True
4 False
5 True
Q.6 What will be the output of the following
a. a = 5 b. a, b, c = 1, 2, 4
a = 25 + 4 – 4 a+ = 4
print ( a) print (int(a/2))
STUDY MATERIAL/CLASS-XI/CS CHAPTER 4: DATA HANDLING
9
answer
a. 25 b. 2
Q.7 Write a program to input total number of days and find total number of months
and remaining days after months.
Q.8 Write a program to calculate the volume and surface area of sphere .
Q.9 Write a program to find the simple intrest of an investment amount. The
formula is SI = PRT/100
Q.10 Write a program to convert rupee into paisa .
Q.11 Write a program to convert meter into inhes.
Q.12 Write a program to concatenate two strings.
Introduction
• Generally a program executes from starting point to end point.
• Some program does not execute in order.
• As per the requirement, execution order of the program can be changed and it is also
possible to execute a program repeatedly.
• Python provides control structures to manage the order of execution of a program,
which are if-else, for, while and jump statements like break, continue
Types of statements
• In Python, statements are of 3 types-
» Empty Statements
• pass
» Simple Statements (Single Statement)
• name=input (“Enter your Name “)
• print(name) etc.
» Compound Statements
• <Compound Statement Header>:
<Indented Body containing multiple simple statements/compound statements>
• Here, Header line starts with the keyword and ends at colon (:).
• The body consists of more than one simple Python statements or compound statements.
Statement Flow Control
• In a program, statements executes in sequential manner or in selective manner or in
iterative manner.
BY:
MOHIT TANDON
PGT(CS)
LPS SEC-D
CHAPTER - 5 : CONDITIONAL AND ITERATIVE
STATEMENTS
Program Logic Development Tool
A program has following development stages-
1. Identification of the problem 2.Analysis of problem 3.Writing Algorithm or Designing Flowchart 4. Writing Code 5.Testing and Debugging 6.Implementation 7.Maintenance
Algorithm
• A process or set of rules to be followed in problem solving operations is an algorithm. For ex- Algorithm to add two numbers is as under-
1. Input First Number 2. Input Second Number 3. Add First Number with Second Number and store into Third number. 4. Display Third number
Flowcharts
• A flowchart is a graphical representation of an algorithm, workflow or process. The flowchart shows the steps as boxes of various kinds, and their order by connecting the boxes with arrows. For ex- flowchart to calculate simple interest is as under-
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 2
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 2
if Statement
• In Python, if statement is used to select statement for processing. If execution of a statement is to be done on the basis of a condition, if statement is to be used. Its syntax is: if <condition>: statement(s) like –
if-else Statement
• If out of two statements, it is required to select one statement for processing on the basis of a condition,if-else statement is to be used. Its syntax is if <condition>: statement(s) when condition is true else: statement(s) when condition is false example:
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 3
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 3
if-elif Statements
• If out of multiple statements, it is required to select one statement for processing on the basis of a condition, if-elif statement is to be used. Its syntax is
Nested If –else
Loop/ Repetition/ Iteration
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 4
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 4
These control structures are used for repeated execution of statement(s) on the basis of a condition. Loop has 3 main components- 1. Start (initialization of loop) 2. Step (moving forward in loop ) 3. Stop (ending of loop) Python has following loops- – for loop – while loop
range () Function
• In Python, an important function is range( ). Its syntax is range( <lower limit>,<upper limit>) If we write - range (0,5 ) Then a list will be created with the values [0,1,2,3,4] i.e. from lower limit to the value one less than ending limit. range (0,10,2) will have the list [0,2,4,6,8]. range (5,0,-1) will have the list [5,4,3,2,1]. in and not in operator
• in operator- 3 in [1,2,3,4] will return True. 5 in [1,2,3,4] will return False. – not in operator- 5 not in [1,2,3,4] will return True.
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 5
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 5
Syntax of For Loop for <var> in <sequence>: <statements to repeat> Example:- WAP to print the table of a number using For loop
Output
Syntax of While Loop While <LogicalExpression>: <loop body with increment or decrement>
Example:- WAP to print the table of a number using while loop.
Output
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 6
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 6
Jump Statements
break Statement
continue Statement
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 7
Study Material – IP– XI Chap-5:Conditional and Iterative Statements 7
Nested Loop
OUTPUT
SOLVED QUESTIONS
Q.1 WAP to check the given year is leap year or not.
Ans:-
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 8
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 8
Q.2 WAP to take two numbers and check that the first number is fully divisible by
second number or not.
Q.3. To print the greatest of two numbers.
Ans:- a=int(input('first no.'))
b=int(input('second no.'))
if a>b:
print (a)
else:
print (b)
Q.4 To check even or odd number.
Ans:-
n=int(input("enter no. "))
if n%2==0:
print ("even")
else:
print ("odd")
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 9
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 9
Q.5 To print all even numbers between1 and 10 in reverse order.
Ans:- for n in range(10, 0, -2):
print(n, '', end='')
Q.6 Rewrite the following code fragment using for loop.
Ans:
Q.7 Rewrite the following code fragment using while loop.
Ans:
Q.8 What is the error in following code. Rewrite the correct code.
Correct Code:
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 10
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 10
Q.9 WAP to test if given number is prime or not. Ans:-
Q.10 WAP that prints prime numbers from 15 through 25.
Ans:-
Q.11 WAP to calculate the roots of a given quadratic equation.
Ans:
Q.12 WAP to find the average of the list of the numbers entered through keyboard.
Ans:
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 11
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 11
ASSIGNMENT
1.WAP to find the greatest among ‘N’ numbers.
2.WAP to print the result on the basis of marks entered of a student.
3.WAP to print the frequency of perfect numbers from 1 to N.
4.WAP to print Fibonacci series upto ‘n’ terms.
5.WAP to print different patterns.
6. WAP to print the second largest number in a given list of numbers.
7.WAP to input a digit(0-9) and print it in words.
8.WAP to check whether square root of a given number is prime or not.
9.WAP to print first n odd numbers in descending order.
10.WAP to print the following series – (i) 1 4 7 10 . . . . . . .40 (ii) 1 -4 7 -10 . . . . . . . . -40
11.WAP to find the smallest number from the list of the numbers entered through keyboard. 12. WAP to print the following triangular patterns:
(i) 12345 1234 123 12 1
(ii) 54321 5432 543 54 5
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 12
Study Material – IP– XI Chap-5:Conditional and Iterative Statements 12
(iii) 1 22 333 4444 55555
(iv) A BA CBA DCBA EDCBA (v) ###### #### ### ## #
(vi) 1 2 3 4 5 6 7 8 9 10 (vii) ABCDE ABCD ABC AB A
MULTIPLE CHOICE QUESTIONS Question-1
What is the output of the following? i = 1 while True: if i%3 == 0: break print(i) i + = 1
a) 1 2
b) 1 2 3
c) error
d) none of the mentioned
Question-2
What is the output of the following? i = 0 while i < 5: print(i) i += 1 if i == 3: break else: print(0)
Study Material – IP– XI Chap-5:Conditional and Iterative Statements 13
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 13
a) 0 1 2 0
b) 0 1 2
c) error
d) none of the mentioned
Question-3
What is the output of the following? x = 'abcd' for i in range(x): print(i)
a) a b c d
b) 0 1 2 3
c) error
d) none of the mentioned
Question-4
The word True is ________. A. a Python keyword B. a Boolean literal C. same as value 1 D. same as value 0
Question-5 What is the output of the following code? x = 0 if x < 4: x = x + 1 print("x is", x) A. x is 0 B. x is 1 C. x is 2 D. x is 3 E. x is 4
Question-6 Analyze the following code: even = False if even = True: print("It is even!")
A. The program has a syntax error in line 1 (even = False) B. The program has a syntax error in line 2 if even = True is not a correct condition. It should be replaced by if even == True: or if even:. C. The program runs, but displays nothing. D. The program runs and displays It is even!.
Question-7
Suppose x = 1, y = -1, and z = 1. What will be displayed by the following statement?
Study Material – IP– XI Chap-5:Conditional and Iterative Statements 14
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 14
if x > 0: if y > 0: print("x > 0 and y > 0") elif z > 0: print("x < 0 and z > 0")
A. x > 0 and y > 0 B. x < 0 and z > 0 C. x < 0 and z < 0 D. nothing displayed
Question-8 The following code displays ___________. temperature = 50 if temperature >= 100: print("too hot") elif temperature <= 40: print("too cold") else: print("just right")
A. too hot B. too cold C. just right D. too hot too cold just right
Question-9 Assume x = 4 and y = 5, Which of the following is true?
A. x < 5 and y < 5 B. x < 5 or y < 5 C. x > 5 and y > 5 D. x > 5 or y > 5
Question-10 How many times will the following code print "Welcome to Python"? count = 0 while count < 10: print("Welcome to Python") count += 1
A. 8 B. 9 C. 10 D. 11 E. 0
Question-11 What is the output of the following code? x = 0 while x < 4: x = x + 1 print("x is", x)
A. x is 0
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 15
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 15
B. x is 1 C. x is 2 D. x is 3 E. x is 4
Question-12 Which of the following function returns a sequence 0, 1, 2, 3? A. range(0, 3) B. range(0, 4) C. range(3) D. range(4)
Question-13 The following loop displays _______________. for i in range(1, 11): print(i, end = " ") A. 1 2 3 4 5 6 7 8 9 B. 1 2 3 4 5 6 7 8 9 10 C. 1 2 3 4 5 D. 1 3 5 7 9 E. 2 4 6 8 10
Question-14 What is the output for y? y = 0 for i in range(0, 10): y += i print(y) A. 10 B. 11 C. 12 D. 13 E. 45
Question-15 What is the output for y? y = 0 for i in range(10, 1, -2): y += i print(y) A. 10 B. 40 C. 30 D. 20
Question-16 How many times is the print statement executed? for i in range(10): for j in range(10): print(i * j) A. 100 B. 20
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 16
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 16
C. 10 D. 45
Question-17 What is sum after the following loop terminates? sum = 0 item = 0 while item < 5: item += 1 sum += item if sum >= 4: continue print(sum)
A. 15 B. 16 C. 17 D. 18
Question-18 Will the following program terminate? balance = 10 while True: if balance < 9: continue balance = balance - 9 A. Yes B. No
Question-19 What is the number of iterations in the following loop: for i in range(1, n + 1): # iteration
A. 2*n B. n C. n - 1 D. n + 1
Question-20 What is sum after the following loop terminates? sum = 0 item = 0 while item < 5: item += 1 sum += item if sum > 4: break print(sum)
A. 5 B. 6 C. 7 D. 8
Study Material – IP – XI Chap-5:Conditional and Iterative Statements 17
Study Material – IP– XI Chap-5:Conditional and Iterative Statements 17