0% found this document useful (0 votes)
1 views189 pages

Ch-6 Python Fundamentals

This document provides an overview of Python programming fundamentals, including the character set, tokens, variables, and basic input/output. It explains the structure of Python programs, the types of tokens (keywords, identifiers, literals, operators), and the significance of each in programming. Additionally, it covers the use of escape sequences, operators, and the distinctions between various types of literals in Python.

Uploaded by

aghayush37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views189 pages

Ch-6 Python Fundamentals

This document provides an overview of Python programming fundamentals, including the character set, tokens, variables, and basic input/output. It explains the structure of Python programs, the types of tokens (keywords, identifiers, literals, operators), and the significance of each in programming. Additionally, it covers the use of escape sequences, operators, and the distinctions between various types of literals in Python.

Uploaded by

aghayush37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 189

Co d e -

083

PYTH
ON F
UNDA
MENT
ALS

Chapte
r-6
In This Chapter
6.1 Introduction
6.2 Python Character Set
6.3 Tokens
6.4 Barebones of a Python Program
6.5 Variables and assignments
6.6 Simple Input and Output
6.1 Introduction
Pre-Revise:

An ordered set of instructions to be executed by a computer to perform a specific task is


called Program.

Language used to specify this set of instruction to the computer is called Programming
Language.

Computer understand the language of 0s and 1s is called machine language or low level
language.

However, It is difficult for humans to write instructions using 0s and 1s.

To avoid this difficulty high level programming languages are invented like C++, Java, PHP,
Python etc. That are easier to manage by humans.

Again It is not directly understood by the computer.


Conversion of High level language

Interpreter
• Program Instruction • Converted language 0s
written in High level and 1s that are easily
Language called Source • Python virtual machine understood by the
consist of inbuilt interpreter
code computer.
which converts the high level
languages(source code) to low
level language or machine
language (Byte code) that are
easily understood by the
Source code computer.
Byte code

Python is an interpreted language, which means the source code of a Python program is
converted into bytecode that is then executed by the Python virtual machine. Python is
different from major compiled languages, such as C and C + +, as Python code is not
required to be built and linked like code for these languages.
6.2 Python character set :
A set of valid characters recognized by python.
Python uses the traditional ASCII character set. The latest version recognizes the Unicode
character set. The ASCII character set is a subset of the Unicode character set.
ü Letters :– A-Z,a-z
ü Digits :– 0-9
ü Special symbols :– space = + - * / ** \ ( ) [ ] { } // =! = == < , > . ‘ “ ‘’’ ; : % ! & # <= >= @
_(underscore) etc.
ü White spaces:– blank space,tab,carriage return,new line, form feed
ü Other characters:- All ASCII and Unicode Characters as part of data or literals.
6.3 Tokens in Python
Token:
The Smallest individual unit in a program is known as a Token or a lexical unit.

Python has following tokens :

i. Keywords : A Keywords are predefined words with a special meaning reserved by programming
language. Example: False, True, def, break, is, in, return, continue, for, if, while, elif, else etc.
ii. Identifiers (Names) : Identifiers are the names given to different parts of the program like
variables, objects, classes, functions, lists, dictionaries etc. Example: Myfile, Data_file, _CHK,
DATE_9_2_2024 etc.

iii. Literals :Literals are data items that have a fixed value/constant value. Python allows
several kinds of Literals: String, Numeric, Boolean, Special (None), Collection

iv. Operators: Operators are symbols that perform arithmetic and logical
operations on operands and provide a meaningful result.
v. Punctuators : Punctuators are symbols that are used in programming languages to
organize sentence structures. Example: ‘ “ # \ ( ) [ ] { } @ , : . =
exam p l e
Tokens
for a1 in range(1,10):
punctuators

if a%2 == 0:

print(a1)
Keywords A keyword is a word having special
meaning reserved by programming
language.

False assert del for in or while

None break elif from is pass with

True class else global lambda raise yield

and continue expert if nonlocal return as

def finally import not try


Identifiers (Names)
ü Identifier is a user defined name given to a part of a program such as variable, object,
function etc.
ü These are not reserved

Rules of Identifiers:
ü An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores and digits (0 to 9).
ü Python does not allow special characters
ü Identifier must not be a keyword of Python.
ü Python is a case sensitive programming language. Thus, Rollnumber and rollnumber
are two different identifiers in Python. Some valid identifiers : Mybook, file123, z2td,
date_2, _no, MYFILE, Myfile_1, Date10_8_24,FiLe123 etc.
1. Class names start with an uppercase letter. All other identifiers start with a lowercase letter.

2. Starting an identifier with a single leading underscore indicates that the identifier is private.

3. Starting an identifier with two leading underscores indicates a strong private identifier.

4. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
Literals
Literals are data items that have a
fixed value/constant value. Python String
allows several kinds of Literals:
Literal
Collection
Numeric

Literals

Special
Boolean
(None)
1. String Literals:
Literal Type Description Example Explanation
A sequence of characters enclosed name=’vikash’ Single line String
String with single/double/triple quotes. It print(name) using single quotes
can be either single line or multiline
Literals strings.
name=”vikash” Single line String
print(name) using double quotes

name=’’’vikash is a Multiline String


good student’’’ using Tripple
print(name) quotes

name=”vikash is a\ Multiline String


good student” using double quotes
print(name) with back slash
2. Numeric Literals:
Literal Type Types Example Explanation

Numeric Int Rollno=101 Return integer value


Literals print(Rollno)

float Marks=45.5 Return float value


print(Marks)

Complex Num=X+Yj Return complex number


value where (X is real part
and Yj is imaginary Part)
More on Numeric Literals: Decimal integer
(1234, 41, +92, -24)

Integers Octal integer


(Positive/Negative) (0o10, 0o14 etc.)
Numeric Literals

Hexadecimal integer
(0XBK9, oxPQR, ox19AZ)

Fractional Form (2.0, 17.5, - >>>a=1,234


13.0, -0.00625, .5, 7.) >>>b=17,225E02
Float >>>a
(Positive/Negative) (1,234) #Tuple
Exponent form (0.58E01, 152E05, >>>b
1.52E07, 152E+8, -0.172E)
(17,22500.0) #Tuple

a+bj (a and b are floats or real part


Complex and j is imaginary part which
represents √-1
3. Boolean Literals:
ü Boolean Literals in Python is used to represent one of the two Boolean values (True or
False)
ü A Boolean literal can either have value as True or as False

Literal Type Boolean Value Example Explanation

Boolean False a=10 Return False


Literals b=20
c=a>b
print(c)
True a=10 Return True
b=20
c=a<b
print(c)
4. Speial Literals: None
ü Python has one special literal, which is None.The None keyword is used to define a null
value, or no value at all or is is used to indicate the absence of value in Python.

Literal Type Example Explanation

None x = None Return None


Special Literals print(x) (That indicated x is epmty or null)

value1=10
value2=None Displaying a variable containing
print (value1) None does not show anything.
However, with print(), it shows
Example2: 10 the value contained as None.
print(value2)
None
5. Collection Literals: None
Literal Example Explanation
Collection
Type
List fruits = ["apple", "mango", "orange"] Return list
print(fruits)
Tuple numbers = (1, 2, 3) Return Tuple
print(numbers)
Dictionary alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} Return
print(alphabets) Dictionary

Set vowels = {'a', 'e', 'i' , 'o', 'u'} Return Set


print(vowels)
Now you understood what is Literals ?
ü Literals are data items that have a fixed value/constant value.
ü Python allows several kinds of Literals:

String

Literal
Collection
Numeric

Literals

Special
Boolean
(None)
Escape Sequences
Escape Sequences are the non-graphic character represented by a backslash (\)
followed by one or more characters to perform some actions.
Escape Explanation Escape Explanation
Sequence Sequence
\\ Backslash (\) \r Carriage Return (CR)
\’ Single quote(‘) \t Horizontal Tab (TAB)
\” Double quote(“) \uxxxx Character with 16- bit hex value xxxx
(Unicode Only)
\a ASCII Bell (BEL) \Uxxxxxxxx Character with 32- bit hex value xxxx
(Unicode Only)

\b ASCII Backspace (BS) \v ASCII Vertical Tab (VT)


\f ASCII Formfeed (FF) \ooo Character with octal value ooo
\n New line character \xhh Character with hex value hh
\N{name} Character named name in the Unicode
database (Unicode Only)
Size of the strings
string size Explanation
‘\\’ 1 Escape sequence \\ counted as 1
‘abc’ 3 3 alphabet counted as 3
“\ab” 2 1 for \a and 1 for b
“Seema\’s pen” 11 seema counted as 5, \’ counted as 1, s counted as 1
space is counted as 1 and pen is counted as 3 i,e. = 11
“Amy’s” 5 3 for Amy, 1 for ‘ and 1 for s i,e. = 5
str=’’’a 5 1 for a 1 for enter key
b 1 for b 1 for enter key
c’’’ 1 for c i,e. = 5
str1=’a\ 3 1 for a 0 for enter key because of multi sting
b\ 1 for b 0 for enter key because of multi sting
c’ 1 for c i,e. = 3
Try yourself
string size Explanation
str1=”a”
str2=”My_file”
str3=”It’s”
str4=”xy\
yz”
str5=”””ab
cd”””
str6=”Welcome\
To\
Python”
str7=”””Welcome
To
Python”””
Operators

ü Operators are tokens/symbols that are trigger some computation/action


when applied to variables and other objects in an expression.

ü Operators are symbols that perform arithmetic and logical operations on


operands and provide a meaningful result.

ü An operator need one or more operands to perform any operations. The


valid combination of both operands makes an expression which returns
computed result.
Operators

For Example
Operators

sum=a+b Expression

Operands
Types of Operators
Operator Symbol/Name
Arithmetic + , - , * , % , * * , //

Assignment =

Logical AND, OR, NOT

Comparison/Relational >,<, >=, <=, ==, !=

Identity is, is not

Membership in, not in

Bitwise & (bitwise X-AND)


^(bitwise X-OR)
|(bitwise OR)
~ (bitwise NOT)
Shift Operator << (bitwise left shift)
>> (bitwise right shift)
Augmented assignment/arithmetic assignment operators +=, -=, *=, /=, %=, **=, //=
Arithmetic Operator
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
BINARY OPERATORS
Assignment Operators
Operator Example Same As Example Output
x=5
//= x //= 3 x = x // 3 x//=3 1
print(x)

x=5
**= x **= 3 x = x ** 3 x **= 3 125
print(x)

x=5
&= x &= 3 x=x&3 x &= 3 1
print(x)

x=5
|= x |= 3 x=x|3 x |= 3 7
print(x)

x=5
^= x ^= 3 x=x^3 x ^= 3 6
print(x)

x=5
>>= x >>= 3 x = x >> 3 x >>= 3 0
print(x)

x=5
<<= x <<= 3 x = x << 3 x <<= 3 40
print(x)
Assignment/Augmented Operators
Operator Example Same As Example Output
= x=5 x=5 x=5 5
print(x)
+= x += 3 x=x+3 x=5 8
x += 3
print(x)
-= x -= 3 x=x-3 x=5 2
x -= 3
print(x)
*= x *= 3 x=x*3 x=5 15
x *= 3
print(x)
/= x /= 3 x=x/3 x=5
x /= 3 1.6666666666666667
print(x)
%= x %= 3 x=x%3 x=5 2
x%=3
print(x)
Augmented Assignment Operators
Comparison/ Relational Operators
Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Relational Operators Example
p q p<q p<=q p==q p>q p>=q p!=q

3 3.0 False True True False True False

6 4 True False False True True True

‘A’ ‘A’ False True True False True False

‘a’ ‘A’ False False False True True True


Identity Operators
Operator Name Example

is Returns True if both variables point at the x=10


same object y=10
print(x is y)
True

is not Returns True if both variables are not the same x=10
object y=“Hello”
print(x is y)
True
x is not y
Equality (==) Vs Identity (is) Operators
Equality (==) Vs Identity (is) Operators
Membership Operators

Operator Name Example

Returns True if a sequence x=[“apple”, ”banana”]


in with the specified value is
present in the object print(“banana” in x)
True

Returns True if a sequence x=[“apple”, ”banana”]


not in with the specified value is not
present in the object print(“pineapple” not in x)
True
Example Membership Operators
list1=[1,2,3,4,5] x=24
list2=[6,7,8,9] y=20
List1=[10,20,30,40,50]
for item in list1:
if (x not in list):
if item in list2: print(“x is not present in given list”)
print(“Overlapping”) if (y in list):
else: print(“y is present in given list”)
Print(“Not Overlapping”) else:
Print(“y is not present in given list”)

Output: Output:
Not Overlapping x is not present in given list
y is present in given list
Logical Operators
Operator Name Example Result

and Returns True if both True and False False


statements are true

or Returns True if one of the True or False True


statements is true

not Reverse the result, returns not True False


False if the result is true
Bitwise Operators
Operato Name Description Exampl Binary Output
r e
AND Sets each bit to 1 if both bits 5&3 0101 & 1
& are 1 0011→0001
OR Sets each bit to 1 if one of two x | y
| bits is 1
XOR Sets each bit to 1 if only one of x ^ y
^ two bits is 1
NOT Inverts all the bits ~x
~
Zero fill left shift Shift left by pushing zeros in x << 2
<< from the right and let the
leftmost bits fall off
Signed right Shift right by pushing copies of x >> 2
>> shift the leftmost bit in from the left,
and let the rightmost bits fall
Bitwise Operators
Bitwise AND (&) Exclusive OR-XOR (^)
A B Results A B Results

0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 0

Inclusive OR (|) Complement (~)


A B Results
A Results
0 0 0
0 1 1 0 1
1 0 1
1 0
1 1 1
Punctuators

ü Punctuators are symbols that are used in programming languages to

organize programming sentence structure, and indicate the rhythm

and emphasis of expressions, statements, and program structure.

ü Most common punctuators of Python programming language are:

‘“#\()[]{}@,:.=
1.3 Barebones of a Python Program
Lets understand this with the help of sample code.

# This program shows a program’s components


# Definition of function SeeYou( ) follows
Comments
def SeeYou ( ) :
print(“Time to say Goog Bye!!”)

Statements # Main program-code follows now


Function
a= 15
b= a-10 Expression
Print (a+3)
If b>5: #colon means it’s a block
Inline
print(“Value of ’a’ was more than 15 initially.”) Comments
Indentation
else: Blocks
print(“Value of ‘a’ was 15 or less initially.”)
SeeYou ( ) # calling above defined function SeeYou( )
Components Description
Comments: are the additional readable information to clarify the source code.

Statements: are the programming instructions.

Expression: are the legal combination of symbols that represents a value.

Function: a code that has a name and it can be reused (executed again) by
specifying its name in the program, where needed.

Blocks and Sometimes a group of statement is part of another statement


Indentation : or function. Such a group of one or more statement is called block or
code block or suite.
Comments
ü Comments are the additional readable information to clarify the source code.
ü It read by the programmer but ignored by Python Interpreter.
ü It begin with symbol # (Hash) and generally end with the end of physical line.

Full line Comments: Inline Comments:


(Physical line begins with #) (It starts in the middle of a physical line.)

In the previous example: In the previous example:


# This program shows a program’s components #colon means it’s a block
# Definition of function SeeYou( ) follows # calling above defined function SeeYou( )
# Main program-code follows now
Types of Comments
# Single Line Comments: Single-line comments are created simply a beginning a line with
hash (#) character, and they are automatically terminated by the end of the line. For Ex:
# This is an example of single-line comment.

# Multi-Line Comments: # Multi-Line Comments: Multi-line


Multi-line comments are created in two way. comments are also created By putting
i. By putting # symbol in the beginning of “””(Triple quotes) symbol in the beginning and
every physical line. end of the line.
For Ex: For Ex:
# This is an example of Multi-line comment. “””This is an example of Multi-line comment.
# Where We write more then one line by using ‘#’ Where We write more then one line by using
symbol. the symbol.”””
Expression
ü An expression is any legal combination of symbols that represents a value.
ü It is composed of one or more operation. It is a valid combination of operator,
literals and variables.

# Expression that are values only: # Expression that produce a value


when evaluated:
15
a+5
2.9 (3+5)/4

ü Other examples of expressions are: 5, a-10, a+3, b>5 etc.


The precedence order is described in the table, starting with the highest precedence at the top:
Highest

Operator Description
() Parentheses P
** Exponentiation E
~x bitwise NOR D
+x -x Unary plus(+), minus(-) M
* / // % Multiplication, division, floor division, and modulus/Reminder A
S
+ - Addition and subtraction
& Bitwise AND
R
^ Bitwise XOR
U
| Bitwise OR
L
<,<=,>,>=,<>,!=,==, is, is not Comparison (Relational Operators), identity operators
E
Not x Boolean NOT
and Boolean AND
or Boolean OR Lowest
Evaluating Arithmetic Expression

a,b=3,6 a,b=3,6 a,b=3,6

c=b/a c=b//a c=b%a

Output Output Output


c=6/3 c=6//3 c=6.0%3

c=2.0 c=2 c=0.0


Evaluate the following Expression:

12+ -6/2
12+12-
-3.0 Associativity of operators if
two operator have same
precedence, Evaluate left to
right.

Ou
tpu

21.0
t/R
esu
lt
Evaluating Relational Expression

p>q<y a<=N<=b

solution solution
(p>q) and (q<y) (a<=N) and (N<=b)
Evaluate the following Expression:

<6
Associativity of operators if
two operator have same
precedence, Evaluate left to
right.

It can be written as
(5>6) and (6<6)
False and False
False
Ou
tpu
t/R
esu
lt
Evaluate the following Expression:

<=6
Associativity of operators if
two operator have same
precedence, Evaluate left to
right.

It can be written as
(5<=6) and (6<=6)
True and True
True
Ou
tpu
t/R
esu
lt
Evaluating Logical Expression

25/5 or 2.0 + 20/10 (a or (b and(not c)))

solution Try it
5.0 or 4.0 ((p and q) or (not r))
Evaluate the following Expression:

and or and not 8<18


and or and not 8<18
and or and not 8<18
and or and

False or False
Output/Result False
Note:

Evaluate 25/5 or (2+20/10)


# output:
5 or 4, So Final Result will be 5
Do it your self

Q.2 Evaluate
a = 10 b = 3
c=a%b
result = c
print(result)

# Output: 1
Statement
ü A statement is a programming instruction that does something that is some
action takes place.
Representing Vs Evaluating

While expression represents something, a While expression is evaluated, a statement is executed i.e.,
statement is a programming instruction that some action takes place. And it is not necessary that a
does something or some action takes place. statement results in a value; it may or may not yield a value.
For Ex. Print(“Hello”) For Ex.
# this statement calls the print function a=15
b=a-10
Print(a+3)
If b<5:
Function
ü A function is a code that has a name and it can be reused (executed again) by
specifying its name in the program, where needed.

For Ex.

Calling a function becomes a


Def display( ):
statement e.g, print is a function but
print(“squre of 5”) when you call print( ) to print
something, then that function call
print(5*5)
becomes a statement.
display( )
Block and Indentation
ü Sometimes a group of statement is part of another statement or function. Such a group of one
or more statement is called block or code block or suite.
ü Note that Python uses indentation to create block of code. Statement at the same indentation
level are part of same block.
Note: You cannot
For Ex. unnecessarily indent a
a=10 statement; Python will
raise error for that.
b= 20

If a>b: Block inside if


print(“a is greater then b”) statement

print(a) Block inside else


Indentation statement
level else:
print (“b is greater then a”)
print(b)
1.4 Variable and Assignment
ü Variable : A variable represents named location that refers to a value that can be used and process
during program run.
ü Note that Variables are not storage container in Python.
ü These are called symbolic variables because these are named labels.

A=10
# Variable A contain an integer value 10. 10

Name=“Rahul”
‘Rahul’
Name
# Variable Name contain a string value Rahul
Creating a Variable
Some Examples of creating Variables.
ü panNo=‘ANUPT6335N’ # Variable created of string type
ü balance = 25972.56 # Variable created of Numeric (Floating point) type
ü rollNo= 901 # Variable created of Numeric (integer) type

Traditional Programming Language’s Variables Python Variables in Memory


Statement Age=15 means variable age will be created as a label pointing to memory
location where 15 is stored that is 20216.

Statement 15
20200 20216 20232 20248 20264 20280 20296
Age=15
202530
Statement
Notice memory Age=15
address/location of
variable did not
change with change in
its value 20200 20216 20248 20264 20280 20296
20232

Statement 20 Statement Now age referring to location 20296 as the variable


Age=20 Age=20 age’s value is changed
202530
Lvalues and Rvalues
# lvalue: expressions that can come on the lhs (left hand side) of an assignment.
# rvalue: expressions that can come on the rhs (right hand side) of an assignment

# For Example But you cannot say: # Note


a=10 10=a Lvalues are the objects to which you can assign
a value or expression.Lvalues can come on lhs
20=b or rhs of an assignment.
b=20 a*2=b Rvalues are the literals and expressions that
are assigned to values.Rvalues can come on lhs
of an assignment.
Assignment of Variable Assign same value to
a=b=c=10
multiple variables (Same value to multiple variable in
a single statement)

Assign multiple values to


x,y,z=10,20,30
multiple variables (Multiple values to multiple
variable in a single statement)

Note: While assigning values through multiple assignments,rememver that


Python first evaluates the RHS expressions and then assigns them to LHS.
Example:
a,b,c=5,10,7 #statement 1
b,c,a=a+1,b+2,c-1 #statement2
print (a,b,c)
Note: While assigning values through multiple assignments,rememver that Python first evaluates the RHS expressions and
then assigns them to LHS.
Example:
a,b,c=5,10,7 #statement 1
b,c,a=a+1,b+2,c-1 #statement2
print (a,b,c) #statement3

Output for statement2 What will be the output for print(p,q,r) ?


p,q=3,5 #statement1
b,c,a=a+1,b+2,c-1 #statement2
q,r=p-2, p+2 #statement2
b,c,a=5+1,10+2,7-1=6,12,6
What will be the output for print(y,y)
b,c,a=6,12,6 (Now, b=6, c=12, a=6)
x=10 #statement1
print(a,b,c)=6 6 12 #statement3 y,y=x+2, x+5 #statement2
Dynamic Typing
# What is Dynamic Typing?
A variable pointing to a value of a certain type, can be made to point to a value/object of different type.

# Note
# For Example Variable X does not have a type but the value it
x=10 Output: points to does have a type. So we can make a
variable point to a value of different type by
print(x) 10 reassigning a value of that type; Python will not
x=“Hello World” Hello World raise any error. This is called Dynamic Typing.
print(x)

# Caution with Dynamic Typing


Int: 10 A=10
B=5
C=A/2
Int: 10 B=“Hello”
D=B/2
String: Hello World
type( ) & id( ) in Python

# id( )
# type( )
It is used to determine the memory location of
It is used to determine the type of a variable
a variable where the value of that variable
i.e; what type of value does it point to?
stores.
# Syntax:
# Syntax:
type (<variable name>)
id (<variable name>)

# For Example # For Example


x=10 Output: x=10.5 Output:

print(type(x)) <class ‘int’> print(id(x))


<class ‘str’> 2639397864400
x=“Hello World” y=“Hello World”
print(type(x)) print(id(y)) 2639402452912
Type Casting (Explicit Type Conversion)
It is user defined conversion that forces an expression to be of specific type. Or The type casting of an
operand to a specific type is called type casting.

Function Description
Int(x) Convert x to an integer

float(x) Convert x to a floating-point number

str(x) Convert x to a string representation

chr(x) Convert x to a character

unichr(x) Convert x to a Unicode character


Example: Type Casting (Explicit Type Conversion)

a=“101” # string
X=95 # integer

Function Description Print Output


b=int(a) # converts string data type to integer print(b) 101

c=int(122.4) # converts float data type to integer print(c) 122

d=float(a) # converts string data type to float print(d) 101.0

e=str(x) # converts integer data type to string print(e) “95”


1.5 Simple Input and Output

In Python to get input from user


# Example
interactively, input( )
name=input (“Enter Your Name:”)
built in function is used to get
input from the user. Output:

Enter Your Name:


# Syntax:
Variable_name=input(“message to be displayed”)
Try yourself in Python IDLE
# Example_3
# Write a program to enter two integers
and perform all arithmetic operation on
# What will be the output for the them.
x=int (input("Enter Value 1: "))
following program y=int (input("Enter Value 2: "))
sum=x+y
diff=x-y
mul=x*y
div=x/y
mod=x%y
print("Numbers are: ", x,y)
print("sum=",sum)
print("Difference=", diff)
print("Product=", mul)
print("Division=", div)
print("Modulus=", mod)
Reading Numbers
# Problem: #Solution:
String value cannot be used for arithmetic ü int( ) and float ( ) functions are used with input( )
to convert the values received through input( )
or other numeric operations. For these ü Read the value using input( ) function
operation we need to have a value of ü And then use int( ) or float( ) function with the read
value to change the type of input value to int or
numeric types (int or float). float respectively.

# Method_1 # Method_2:
age=input (“What is your age ?")
age=input (“What is your age ?")
What is your age ? 16
print(age) What is your age ? 16
print(age+1) OR age=int(age)
age=int(input (“What is your age ?"))
age+1
What is your age ? 16
Output through print( ) Function

The print( ) function is used to display the output of any command on the screen.
It can be also used to print the specified messages.

#Syntax:
Print(*objects, [ sep = ‘ ‘ or <separator-string>end = ‘\n’ or <end-string>])

# For Ex_1: # For Ex_2:


Print( “Python is Wonderful”) Print( “Sum of 2 and 3 is”, 2+3)
Output Output
Python is Wonderful Sum of 2 and 3 is 5
Output through print( ) Function

# For Ex_3:
a=25
A print( ) function without any value or
Print( “Double of” ,a, “is” , a*2)
name or expression prints a blank line.
Output
Double of 25 is 50
Features of print( ) Function

# It converts the message or an object into a #For Ex.


string before writing it on the screen. print(“My”,”Name”,”is”,”Saroj”)
# It can have multiple parameters. Output:
My Name is Saroj
# It supports multiple escape sequences to
format the output. ex: “\n” (New Line), “\t” (TAB
#For Ex.
Space) and (Carriage Return).
print(“My”,”Name”,”is”,”Saroj”, sep=‘…’)
# It insert spaces between string items Output:
automatically because the default value of sep My…Name…is…Saroj
argument is space(‘ ’). The sep argument
specifies the separator character.
#For Ex.
print(“My”,”Name”,”is”,”Saroj”, sep=‘_’)
Features of print( ) Function…

#For Ex.
# It automatically added a newline character in the end
My Name is Amit. Or \n
of a line printed so that the next print( ) prints from the
I am 16 Years old.
next line.

#For Ex.
# If you explicitly give an end argument with a
print(“My”,”Name”,”is”,”Saroj”, sep=‘…’)
print( ) function then the print( ) will print the
Output:
line and end it with the string specified with the My…Name…is…Saroj
end argument.
#For Ex.
print(“My”,”Name”,”is”,”Saroj”, sep=‘_’)
#For Ex.
print(“My Name is Amit. ”, end = ‘$’) #For Ex.
Print(“I am 16 Years old. “) a,b=20,30

Output: print(“a=“, a, end= ‘ ‘)

My Name is Amit.$I am 16 Years old. print(“b=“, b)


Arguments Within print( ) fuction

What is sep=‘ ‘ What is end=‘ ‘

# In print( ) function, the default value of end argument is newline character (“\n”) and sep argument, it is
space (‘ ‘)

#Note
#For Ex.
In Python you can break any statement by putting a \ in the end and
Name=‘Students’
pressing Enter Key, then completing the statement in next line.
print(“Hello”, end=‘ ‘)
print(Name)
#For Ex.
print(“How do you find python?”) print(“Hello”, \
Output: End=‘ ‘)
Hello Students
How do you find python?
1.6 Data Types
ü Data types specifies which type of value a variable can store.
ü Data types can be of many types like character, integer, real, string etc.
ü Data to be dealt with are of many types, a programming language must provide
ways to facilities to handle all types of Data.
Python provides us type( )
ü Python offers following build-in core data types: function which returns the
1. Numbers type of the variable passed

2. String
3. List
4. Tuple
5. Dictionary
Hierarchy of Data Types
Data Types

Numbers Sequence Sets None Mapping

Integer Float Complex String List Tuple Dictionary

Boolean
Numbers
As it is clear by the name the Number data types are used to store
numeric values in Python.
It is of following types:
I. Integer Numbers

a) Integer Signed
b) Boolean Integer Float Complex

II. Floating-Point Numbers


Integer
Boolean
(Signed)
III. Complex Numbers
Integers
ü Integers are whole numbers such as 10,5,8,0 etc.
ü They have no fractional part.
ü Integers are represented in python numeric values with
no decimal point.
ü Integers can be positive or negative numbers like 5,10,-3
etc.
Integer
ü It is of 2 types: Signed and Boolean.
Integer
Boolean
(Signed)
Sequence
A Python sequence is an ordered collection of items where each item
is indexed by an integer.
It is of following types:
I. Strings Sequence

II. Lists
String List Tuple
III. Tuples
String Indexing
ü A Python string is a sequence of characters and each In Python 3.x, each character
stored in a string is a Unicode
character. Unicode is a system
character can be individually accessed using its Index. designed to represent every
character from every language.

Let us understand this: Name[0]=‘P’=name[-6]


Name[1]=‘Y’=name[-5]
Forward Indexing Name[2]=‘T’=name[-4]
0 1 2 3 4 5 Name[3]=‘H’=name[-3]
Name[4]=‘O’=name[-2]
Name[5]=‘N’=name[-1]
-6 -5 -4 -3 -2 -1

Backward Indexing

§ String in Python are stored by storing each character separately in contiguous memory location.
§ The characters of the strings are stored in two way indexing method
LIST [__,__,__,]
ü Lists in Python are container that are used to store multiple items/values in a single variable.
ü List are created using square brackets and their values are separated by comma.
ü List items are ordered, changeable, and allow duplicate values.
ü List items are indexed, the first item has index [0], the second item has index [1] etc.

Example_1 Example_2 Example_3

My_list = ["apple", "banana", "cherry"] a=[1,2,3,4,5,2] a=[1,2,3,4,5]


print(My_list) print(a) print(a) Output:
list = [1, 5, 7, 9, 3] a[5]=6 a[4]=10 [1, 2, 3, 4, 5]
print(list) print(a) print(a) [1, 2, 3, 4, 10]
b=[1,2,3,4,'Rahul'] [1, 2, 3, 4, 'Rahul']
Output: Output: print(b) [1, 2, 3, 4, 'Rohan']
["apple", "banana", "cherry"] [1,2,3,4,5,2] b[4]='Rohan'

[1, 5, 7, 9, 3] [1,2,3,4,5,6] print(b)


TUPLE (__,__,__,)
ü Tuple in Python used to store multiple items in a single variable.
ü Tuples are created using round brackets and their values are separated by comma.
ü Tuples items are ordered and unchangeable though it is immutable type
ü Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Example_1 Example_2

p=(1,2,3,4,5)
Tuple_1= ("apple", “10", “3.4“)
print(p)
print(Tuple_1) p[2]=10
print(p)

Output: Output:
TypeError: 'tuple' object does not support item
("apple", “10", “3.4“) assignment
SETs {__,__,__,}
ü Set in Python used to store multiple items in a single variable.
ü Sets are created using curly brackets and their values are separated by comma.
ü A set is a collection which is unordered, unchangeable*, and unindexed.
ü Note: Set items are unchangeable, but you can remove items and add new items.

Example_1 Example_2

set_1= {"apple", “10", “Vikash”} set_2={1,2,3,4,3,2}


print(set_1) print(set_2)

Output: Output:
{"apple", “10", “Vikash”} {1,2,3,4}
Dictionary
ü Dictionary data type is an unordered set of comma-separated key : value pairs
ü Dictionaries are written with curly brackets, and have keys and values:
ü A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
ü Dictionary items are presented in key : value pairs, and can be referred to by using the key
name.

Example_1

Students={1:'Rahul',2:'Vijay',3:'Akash'} Output:
print(Students) {1: 'Rahul', 2: 'Vijay', 3: 'Akash'}
print(Students[2]) Vijay
print(Students[3]) Akash
1.7 Mutable and Immutable Data Types

Mutable Immutable

Lists Integers

Dictionaries Floating point Numbers

Sets Booleans

Strings

Tuples
# Mutable Types: # Immutable Types: these are
these are the data types whose the data types that can never
values in place. change their value in place.
# Programs_2
# Write a program to obtain three numbers and print their sum.

Num_1=int(input(“Enter Number 1: “)) # Output


Enter Number 1:4
Num_2=int(input(“Enter Number 2: “))
Enter Number 2:6
Num_3=int(input(“Enter Number 3: “))
Enter Number 3:10
Sum=Num_1+Num_2+Num3 The three numbers are: 4 6 10
print(“The three numbers are: “,Num_1,Num_2,Num_3) Sum is: 20

print(“Sum is” , Sum)


# Programs_3
Write a program to obtain length and breadth of a rectangle and calculate its area.

length=float(input(“Enter length of the rectangle: “)) # Output


breadth=float(input(“Enter breadth of the rectangle: “)) Enter length of rectangle:
Area=length*breadth Enter breadth of rectangle:
print(“Rectangle Specifications “) Rectangle Specification
print(“Length= “, length, end=‘ ‘) Length= 5.8 Breadth= 3.0
Print(“Breadth=“, breadth) Area= 17.4
Print(“Area= “,area)
# Programs_4
Write a program to calculate BMI (Body Mass Index) of a person. (Hint: BMI=KG/M2)

weight_in_kg=float(input(“Enter weight in Kg: “)) # Output


height_in_meter=float(input(“Enter height in meters: “)) Enter weight in Kg:
bmi= weight_in_kg/(height_in_meter* height_in_meter) Enter height in meters:
Print(“BMI is: “,bmi) BMI is:
# Programs_5
Write a program to input a number and print its cube.

#Write a program to input a number and print its cube.

num=int(input(“Enter a number: “)) # Output


cube=num*num*num Enter a number:
print(“Number is”, num) Number is:
print(“Its cube is”, cube) Its cube is:
# Programs_6
Write a program to input a value in kilometers and convert it into miles. (hint: 1km=0.621371 miles)

#Write a program to input a value in kilometers and convert it into miles.

km=int(input(“Enter kilometers: “)) # Output


miles=km*0.621731 Enter a Kilometer:
print(“Kilometers ”, km) Kilometers:
print(“Miles”, miles) Miles:
# Exercise
1. Write a program to calculate radius of a circle.

2. Write a program to calculate total marks of a student in six different subjects Eng, Hindi, Phy, Che, Bio, Comp. Sc. and find
its percentage. (F.M:500)

3. Write a program to calculate total marks of a student in six different subjects Eng, Hindi, Phy, Che, Bio, Comp. Sc. and find
its percentage. (F.M:500)

4. You have 1000 Rupees. You went to the market and brought different items like:
i. 2 Pkt. Of biscuits (95.00),
ii. 5 kg. Rice
iii. 1 kg. Potato
iv. 1 kg. Tomato
v. 1.5 kg onion
and rest of the amount you gave to your mother. How many rupees you have invested and how many rupees gave to your
mother. Write a program based on above data.
# Exercise
5. What will be the output produced by following code?
name=‘Simran’
age=17
print(name, “,you are”, 17,”now but”, end=‘ ‘)
print(“you will be”,age+1, “next year”)

6. What will be the output of the following code?


x, y=2, 6
x, y=y, x+2
print(x,y)

7. What will be the output of the following code?


x, y=7,2
x, y, x=x+1, y+3, x+10
print(x,y)
# Exercise
8. Write a program to find average of three numbers.

9. Write a program to find odd or even number of a given numbers.

10. Write a program to determine the current time of Washington, DC, USA as compared to India. (Hint: in
India +10:30 hours)

11. What will be the output of the following code?


print(“Hello, Welcome”, end=‘@’)
print(“Python Programming”)
It is a standard module in Python. To use
mathematical functions of this module,we
ma t h module have to import the module using import math.

Function Description Example


ceil(n) It returns the smallest integer greater than or equal to n. math.ceil(4.2) returns 5
factorial(n) It returns the factorial of value n math.factorial(4) returns 24
floor(n) It returns the largest integer less than or equal to n math.floor(4.2) returns 4
fmod(x, y) It returns the remainder when n is divided by y math.fmod(10.5,2) returns 0.5
exp(n) It returns e**n math.exp(1) return 2.718281828459045
log2(n) It returns the base-2 logarithm of n math.log2(4) return 2.0
log10(n) It returns the base-10 logarithm of n math.log10(4) returns 0.6020599913279624
pow(n, y) It returns n raised to the power y math.pow(2,3) returns 8.0
sqrt(n) It returns the square root of n math.sqrt(100) returns 10.0
cos(n) It returns the cosine of n math.cos(100) returns 0.8623188722876839
sin(n) It returns the sine of n math.sin(100) returns -0.5063656411097588
tan(n) It returns the tangent of n math.tan(100) returns -0.5872139151569291
pi It is pi value (3.14159...) It is (3.14159...)
e It is mathematical constant e (2.71828...) It is (2.71828...)
Syntax:
h . Ce i l( )
m at math.Ceil(n)

Example:
Import math
# It returns smallest integer
not less than num print(math.ceil(9.7)

print(math.ceil(-9.7)

print(math.ceil(9)
Output:
10
-9
9
Syntax:
. f lo o r( )
m a th math.floor(n)

Example:
Import math
# It returns largest integer
print(math.floor(9.7)
not greater than num
print(math.floor(-9.7)
print(math.floor(9)
print(math.floor(4.5)

Output:
9
-10
9
4
Syntax:
f a b s( )
m a th . math.fabs(n)
Example:
# It returns absolute value
Import math
print(math.fabs(6.7)
print(math.fabs(-6.7)
print(math.fabs(-4)
print(math.fabs(-4.23)

Output:
6.7
6.7
4.0
4.23
Syntax:
a c to r i a l( )
m a t h . f math.factorial(n)

Example:

# It returns factorial of a Import math


print(math.factorial(2)
num print(math.factorial(3)
print(math.factorial(4)
print(math.factorial(5)
Output:
2
6
24
120
Syntax:

f m o d( )
m a th .
math.fmod(x,y)
Example:
Import math
# It returns the modulus print(math.fmod(4,4.9)
resulting from the
print(math.fmod(5,2)
division x and y. fmod is
print(math.fmod(3,3)
preferred for floats.
print(math.fmod(5,4)
Output:
Note: % returns int value 4.0
where as fmod returns float 1.0
0.0
value 1.0
Syntax:
p ow( )
m a th . math.pow(x,y)
Example:
# It returns the power of Import math
the num (x raise to the print(math.pow(4,2)
power y) print(math.pow(3.5,2)
print(math.pow(3,3)
print(math.pow(5,2.5)
Note: to perform power of a
num we can also use ** operator. Output:
16.0
12.25
27.0
55.90169943749474
Syntax:
s q r t( )
m a th . math.sqrt(x)

Example:
# It returns squre
Import math
root of x
print(math.sqrt(144)
print(math.sqrt(256)
Note: Always returns in print(math.sqrt(64)
float value. print(math.sqrt(6.4)
Output:
12.0
16.0
8.0
2.5298221281347035
Syntax:
o s / t a n ( )
m ath.sin/c
math.sin(x)
# It returns sine, cosine and tangent of x Example:
Note: Used in Trigonometry and are based
on a Right-Angled Triangle
Import math
print(math.sin(30)
print(math.cos(45)
print(math.tan(60)
print(math.tan(25.5)
Output:
-0.9880316240928618
0.5253219888177297
0.320040389379563
d e g re e s( )
ma t h . Syntax:

math.degrees(x)
# It converts angle x from radians to
degree
Example:
Import math
print(math.degrees(30)
print(math.degrees(45)
print(math.degrees(60)
print(math.degrees(3)
Output:
1718.8733853924696
2578.3100780887044
3437.746770784939
171.88733853924697
Syntax:
ra d i a n s( )
ma t h . math.radians(x)

# It converts angle x from degree to Example:


radians
Import math
print(math.radians(45)
print(math.radians(60)
print(math.radians(90)
print(math.radians(30)
Output:
0.7853981633974483
1.0471975511965976
1.5707963267948966
0.5235987755982988
Syntax:

a t h . l o g ( ) math.log(x)
m
Example:
# It returns the natural logarithm for num
Import math
print(math.log(45)
print(math.log(60,2)
print(math.log(90)
print(math.log(30)
Output:
3.8066624897703196
5.906890595608519
4.499809670330265
3.4011973816621555
Syntax:

t h . l o g 1 0 () math.log10(x)
ma
Example:
# It returns the base 10
logarithm for num Import math
print(math.log10(45)
print(math.log10(60)
print(math.log10(90)
print(math.log10(30)
Output:
1.6532125137753437
1.7781512503836436
1.954242509439325
1.4771212547196624
Syntax:

a t h . ex p() math.exp(x)
m
Example:
# It returns the exponential of
Import math
specified value
print(math.exp(2.0)
print(math.exp(3)
print(math.exp(4.5)
print(math.exp(30)

Output:
7.38905609893065
20.085536923187668
90.01713130052181
10686474581524.463
a t h . g cd() Syntax:
m
math.gcd(x,y)
# It returns the greatest
common divisor Example:
Import math
print(math.gcd(3,6)
print(math.gcd(12,36)
Output:
3
12
Try it Solution:
Import math

r=7.5
# The radius of a sphere is 7.5
metres. WAP to calculate its area=4*math.pi*r*r
area and volume. (Area of a volume=4/3*math.pi*math.pow(r,3)
sphere 4= ��2 ; volume of a print(“Radius of the sphere: ”,r,”metres”)
4
sphere = 3 print(Area of the sphere: ”,area,”units squre”)
3��

print(Volume of the sphere: ”,volume,”units cube”)

Output:

Radius of the sphere: 7.5 metres


Area of the sphere : 706.8583470577034 units squre
Volume of the sphere : 1767.1458676442585
m M o d u le
R a n do

# This module contains functions that are used for generating random numbers.
Some of the commonly used functions in random module are:

random() randint() randrange()


ra n d o m ()
o n ly u s e d
Comm
f un c t i o n s
random()
It returns a random floating point number randint()
in the range 0.0 to 1.0
Example: It returns a random integer number in the randrange()
Import random range (x,y)
random.random Example: It returns random integer between x and y
Output: Import random Example:
0.0011172325660707694 print(random.randint(1,5)) Import random
print(random.randint(3,10)-3) print(random.randrange(1,5))
Output: print(random.randrange(6))
1 to 5 print(random.randrange(3,8)-2
0 to 7 Output:
1 to 4
0 to 5
1 to 5
r an d o m ( ) #random(): It returns random number between 0.0 and 1.0:
import random
print(random.random())
Returns a random float number OR
between 0 and 1 import random as rn
print(rn.randint(3, 9))

Output:

0.14060071708188693
randint()
#Example:
import random
The randint() method returns an integer print(random.randint(3, 9))
number selected element from the specified OR
range. import random as rn
print(rn.randint(3, 9))
Syntax:
random.randint(start, stop)
Output:
More on randint():
We can use any arithmetic operators after the specified
range 4
Possible errors:
6
ü TypeError if we pass single argument.
ü We can not pass any float value as arguments. 9
ü Argument can not be empty.
ü It will take only 2 digits not start, stop and stop. 6
ü First argument must be smaller than 2nd argument.
ran ge( )
rand
#Example:
The randrange() method returns a randomly import random
selected element from the specified range. print(random.randrange(3, 9))
OR
Syntax:
random.randrange(start, stop, step) import random as rn
print(rn.randrange(3, 9)) # 3 t0 8
More on randint(): print(rn.randrange(9)) # 0 t0 8
We can use any arithmetic operators after the specified
print(rn.randrange(1,10)) # 1 t0 9
range
Possible errors: print(rn.randrange(1,10,2)) # 1 t0 9 with a
ü if we pass single argument, it will not generate error. It step value 2
will take as start value 0.
ü We can not pass any float value as arguments.
ü First argument must be smaller than 2nd argument. If
we do so, we will pass a step value like -1, -2, -3 etc.
ü Argument can not be empty.
What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the
following code?

import random
List=[‘Delhi’,’Mumbai’, ‘Channai’, ‘Kolkata’]
for y in range(4): Options:

X=random.randint(1,3) (i)Delhi#Mumbai#Channai#Kolkata#
(ii) #Mumbai#Channai#Kolkata#Mumbai#
print (List[x],end=”#“) (iii) #Mumbai# #Mumbai#Mumbai#Delhi#
(iv) #Mumbai# #Mumbai#Channai#Mumbai
Ans
Maximum value of FROM = 3
Maximum value of TO = 4
(ii) #Mumbai#Channai#Kolkata#Mumbai#
What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the
following code? Also specify the maximum values that can be assigned to each of the variables FROM and TO.

import random Options:


(i)10#40#70# (ii)30#40#50#
LIST=[20,30,40,50,60,70]
(iii)50#60#70# (iv)40#50#70#
FROM=random.randint(1,3)
Ans
TO=random.randint(2,4)
Maximum value of FROM = 3
for Y in range(FROM,TO+1): Minimum value of FROM = 1
print (LIST[Y],end=”#“) Maximum value of TO = 4
(ii) 30#40#50#
Find the maximum and minimum value assigned to variable FROM
import random #Options:
List=[20,30,40,50,60,70] i. 1,3
ii. 4,1
FROM=random.randint(1,3) iii. 1,4
TO=random.randint(2,4) iv. 3,1

for y in range(FROM,TO+1):
Answer: ?
print(List[y],end=“#”)
What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the
following code? Also specify the maximum values that can be assigned to each of the variables FROM and TO.

import random Options:


(i)10#40#70# (ii)30#40#50#
AR=[20,30,40,50,60,70]
(iii)50#60#70# (iv)40#50#70#
FROM=random.randint(1,3) Ans
Maximum value of FROM = 3
TO=random.randint(2,4)
Maximum value of TO = 4
for K in range(FROM,TO): (ii) 30#40#50#

print (AR[K],end=”#“)
What will be the output of the following code?

import random
Color=[‘Red’, ‘Orange’, ‘Yellow’, ‘Black’, ‘Cyan’]
For c in range(len(color)): #Options:
P=random.randint(2,4) i. Red$Red$Cyan$Orange$Yellow

Print(color[p], end=‘$’) ii. Cyan$Black$Black$Cyan$Yellow


iii. Black$Red$Black$Red$Black
iv. Black$Orange$Yellow$Black$Black

Answer:
ii. Cyan$Black$Black$Cyan$Yellow
Consider the given code and identify the incorrect output?

import random
#Options:
no1=random.randint(0,5) i. 0#0#1
Print(no1, end=‘#’) ii. 8#0#1

no2=random.randint(3,5) iii. 2#5#5


iv. 5#3#2
Print(no2, end=‘#’)
no3=random.randint(2,5) Answer:
ii. and iv
Print(no3, end=‘#’)
What possible output(s) are expected to be displayed on screen
at the time of execution of the program from the following code?

import random
AR=[‘red’, ‘green’, ‘yellow’, ‘orange’, ‘blue’, ‘black’]
P=random.randint(1,3)
Q=random.randint(2,4) #Options:
i. Black-blue-orange
for I in range(P,Q+1) ii. Orange-blue
print(AR[i],end=‘-’ iii. Yellow-orange-blue
iv. Green-orange-blue

Answer:
ii. and iii
What are the possible outcome(s) executed from the following code?
Also specify the maximum and minimum values that can be assigned to
each of the variable BEGIN and LAST.

Import random
POINTS=[30,50,20,40,45] Options:
i. 20#50#30#
BEGIN=random.randint(1,3) ii. 50#20#40#
iii. 20#40#45#
LAST=random.randint(2,4) iv. 30#50#20#

For C in range (BEGIN,LAST+1): Ans:


Maximum value of BEGIN=3
Maximum value of LAST=4
print(POINTS[C],end=“#”)
What possible output(s) are expected to be displayed on screen at the time of execution of the program from the
following code? Also specify the minimum values that can be assigned to each of the variables BEGIN and LAST.

import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80]
BEGIN = random.randint (1, 3) Options:
(i) 30-40-50- (ii) 10-20-30-40-

LAST = random.randint(2, 4) (iii) 30-40-50-60- (iv) 30-40-50-60-


70-

for I in range (BEGIN, LAST+1): Ans


OUTPUT – (i) 30-40-50-
print (VALUES[I], end = "-") Minimum value of BEGIN: 1
Minimum value of LAST: 2
Consider the following code:

import math import random

print(str(int(math.pow(random.randint(2,4),2)))) Options:
i) 2 3 4 ii) 9 4 4
print(str(int(math.pow(random.randint(2,4),2))))
iii)16 16 16 iv)2 4 9

print(str(int(math.pow(random.randint(2,4),2)))) Ans
Possible outputs : ii) , iii)
What could be the possible outputs out of the randint will generate an integer between 2 to 4
which is then raised to power 2, so possible
given four choices?
outcomes can be 4,9 or 16
Consider the following code and find out the possible output(s) from the options given below. Also write the least
and highest value that can be generated. import random as r

print(10 + r.randint(10,15) , end = ‘ ‘)

print(10 + r.randint(10,15) , end = ‘ ‘) Options:


i) 25 25 25 21 iii) 23 22 25 20
ii) 23 27 22 20 iv) 21 25 20 24
print(10 + r.randint(10,15) , end = ‘ ‘) Ans
Possible outputs :
i), iii) and iv)
print(10 + r.randint(10,15)) Least value : 10
Highest value : 15
What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the
following code. Select which option/s is/are correct

import random

print(random.randint(15,25) , end=' ')

print((100) + random.randint(15,25) , end = ' ' )

print((100) -random.randint(15,25) , end = ' ' )

print((100) *random.randint(15,25) ) Options:


(i) 15 122 84 2500 (ii) 21 120 76 1500
(iii) 105 107 105 1800 (iv) 110 105 105 1900
Ans
(i) (ii) are correct answers.
What are the possible outcome(s) executed from the following code?
Also specify the maximum and minimum values that can be assigned to
variable N.

Import random
SIDES=[“EAST”,”WEST”,”NORTH”,”SOUTH”]
Options:
N=random.randint(1,3) i. SOUTHNORTH
ii. SOUTHNORTHWEST
OUT=“” iii. SOUTH
iv. EASTWESTNORTH
For i in range (N,1,-1):
Ans: (i) SOUTHNORTH
OUT=OUT+OUT+SIDES[I] Maximum value of N=3
Minimum value of N=1
print(OUT)
What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum values
that can be assigned to the variable End

Import random
Colours=[“VIOLET”,”INDIGO”,”BLUE”,”GREEN”,”YELLOW”,”ORANGE”,”RED”]
End=randrange(2)+3
Options:
Begin=randrange(End)+1 (i) INDIGO&BLUE&GREEN&
For i in range (Begin,End): (ii) BLUE&GREEN&YELLOW&
(iii) VIOLET&INDIGO&BLUE
print(Colours[i],end=“&”) (iv) GREEN&YELLOW&ORANGE
Ans
Ans: (i) INDIGO&BLUE&GREEN&
Minimum value of End=3
Maximum value of End=4
What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the
following code?

import random
colors=[‘Violet’,Indigo’, ‘Blue’, ‘Green’, ‘Yellow’, ‘Orange’, ‘Red’]
end=random.randrange(2)+5
Options:
Begin=random.randint (1,end)+1 (i)Blue&Green&
for i in range(begin,end): (ii) Green&Yellow&Orange&
(iii) Indigo&Blue&Green&
print (colors[i],end=”&“)
(iv) yellow&Orange&Red&
Ans
Minimum value of end = 5
Maximum value of begin = 7
(ii) Green&Yellow&Orange&
Que s t i o n
What could be the minimum and maximum possible
number by the following code? #Hint:
15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30

import random
print(random.randint(15, 30)-7) Output:

Minimum possible numbers: 8


Maximum possible numbers: 23
What are the possible outcome(s) executed from the following code?
Also specify the maximum and minimum values that can be assigned to
variable N.

Import random
NAV=[“LEFT”,”FRONT”,”RIGHT”,”BACK”];
Options:
NUM=random.randint(1,3) i. BACKRIGHT
ii. BACKRIGHTFRONT
NAVG=“” iii. BACK
iv. LEFTFRONTRIGHT
For C in range (NUM,1,-1):
Ans:
NAVG=NAVG+NAV[i] Maximum value of N=3
Minimum value of N=1
Print NAVG
4.Which is the correct outcome executed from the following code?

import random
n1= random.randrange(1, 10, 2)
Options:

n2= random.randrange(1, 10, 3) i. 2 and 7


ii. 3 and 4
iii. 8 and 10
print (n1,"and",n2) iv. 8 and 9
Ans. (ii) is correct
1. What are the possible outcome(s) from the following code?

import random
PICK=random.randint (1,3)
CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"]
for I in CITY:
(i) (ii) (iii) (iv)
for J in range (0, PICK): DELHIDELHI DELHI DELHI DELHI

print (I, end = "") MUMBAIMUMBAI DELHIMUMBAI MUMBAI MUMBAIMUMBAI


CHENNAICHENNAI DELHIMUMBAICHENNAI CHENNAI KOLKATAKOLKATAKOLKATA
print () KOLKATAKOLKATA KOLKATA

Ans. Option (i) and (iii) are possible


3. What are the possible outcome(s) executed from the
following code ? Also specify the maximum and minimum
values that can be assigned to variable PICKER.

import random
N=3
PICKER = random.randint (1, N)
COLOR = ["BLUE", "PINK", "GREEN", "RED"]
for I in COLOR : (i) (ii) (iii) (iv)

BLUE BLUE PINK BLUEBLUE

for J in range (0, PICKER): PINK BLUEPINK PINKGREEN PINKPINK

GREEN BLUEPINKGREEN GREENRED GREENGREEN


print (I, end = " ") RED BLUEPINKGREENRED GREENGREEN

Ans. Option (i) and (iv) are possible


print () The maximum value of PICKER is 3 and minimum is 1
2.What are the possible outcome(s) from the following code?
Also, specify the maximum and minimum values that can be
assigned to variable SEL.

import random
SEL=random. randint (1, 3)
ANIMAL = ["DEER", "Monkey", "COW", "Kangaroo"]
for A in ANIMAL:
(i) (ii) (iii) (iv)
for AA in range (0, SEL): DEERDEER DEER DEER DEER
MONKEYMONKEY DELHIMONKEY MONKEY MONKEYMONKEY
print (A, end ="")
COWCOW DELHIMONKEYCOW COW KANGAROOKANGAROOKANGAROO
print () KANGAROOKANGAROO KANGAROO KANGAROOKANGAROO

Ans. Maximum value of SEL is 3 and minimum is 1


(iv) is the correct option.
Statement Flow Controls
ü In a program, statements may be executed sequentially, selectively or
iteratively. OR
ü Every programming language provides constructs to support sequence,
selection or iteration.
ü A conditional is a statement set which is executed, on the basis of result of a
condition. A loop is a statement set which is executed repeatedly, until the
end condition is satisfied.

1. Compound Statement (The conditionals and loops)


2. Simple Statement (Any single executable Statement in Python)
3. Empty Statement (A Statement which does nothing like pass)
The if conditional:

ü These are used to selectively execute some statements and


control the flow of execution of program depending upon
condition.
ü There are three types of decision making statement.

If Statement

Decision Making Statement If-else Statement

If-elif Statement
1. If statement or Simple if
The if statement tests a particular condition; if the
condition evaluates to true, a statement or set-of-
statements is executed. if the condition is false, it
False
does nothing. Test
Expression

Example:
True

Body of if
Example: if statement

a = int(input("Enter a Number: ")) Marks = int(input("Enter your Marks: ")

if a< 200: if marks >500:


print(“The number is less than 200") print

Output : Output :
Enter your score: 150 Enter your score:650
The number is less than 200
>>>
>>>
2. if-else statement:

The if statement tests a particular Test False


Expression
Body of else
condition; if the condition evaluates ?
to Tr u e , a s t a te m e n t o r s e t - o f -
True
statements is executed. if the
condition is False, it executes else Body of if

statement indented below.


Example of if-else. WAP to check even or odd:

num = int(input("Enter an integer: "))


if num % 2 == 0:
print(num, "is even.")
else:
print(num, "is odd.")
Output :
Enter an integer: 15
15 is odd

Enter an integer: 12
12 is even.
3. if-elif statement:
if <condition> :
The if...elif...else statement allows you to [statement]
[statements]
check for multiple test expressions and elif <condition> :
execute different codes for more than two [statement]
conditions. [statements]
and
Example: if <condition> :
a=input(“Enter first number”) [statement]
b=input("Enter Second Number:") [statements]
if a>b: elif <condition> :
print("a is greater") [statement]
elif a==b: [statements]
print("both numbers are equal") else :
else: [statement]
print("b is greater") [statements]
WAP to print Grade of the student:

score = float(input("Enter your score: "))


if score >= 90:
Output :
print("A")
Enter your score: 75
elif score >= 80: C
print("B") Enter your score: 89
B
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
WAP for Age Classifier

age = int(input("Enter your age: ")) Output :


if age < 18: Enter your age: 23
You are an adult.
print("You are a child.")
Enter your score: 17
elif age < 60: You are an child
print("You are an adult.")
else:
print("You are a senior citizen.")
ADD A FOOTER 146
ADD A FOOTER 147
WAP for ATM Machine
Create a basic ATM machine program that allows users to check their account balance and withdraw funds.
You can set an initial account balance and then deduct the withdrawn amount.

account_balance = 1000 # Initial account balance

print("Welcome to the ATM!")


Output :
option = input("Choose an option (1: Check Balance, 2: Withdraw): ")

if option == "1": Welcome to the ATM!


print(f"Your account balance is ${account_balance}.") Choose an option (1: Check Balance, 2: Withdraw):
1
elif option == "2": Your account balance is $1000..
amount = float(input("Enter the withdrawal amount: "))

if amount <= account_balance:

account_balance -= amount
print(f"Withdrawn ${amount}. New balance: ${account_balance}.")
else:
print("Insufficient funds.")
else:
print("Invalid option. Please choose 1 or 2.")
Iteration statements (loop)
The iteration statement or repetition statements allow a set
of instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called
loops or looping statement.
Python Iteration (Loops) statements are of two type :-
1. While Loop
2. For Loop
Counting Loop Conditional Loop
The loops that repeat a certain numbers of time; The loops that repeat until a certain things
ex: for loop happens; ex: while loop
For loop:

The for loop of python is designed to


iterate over the item of any sequence,
such as list, string, tuple etc.

# iterate from i=0 to i=3


for i in range(4):
print(i)
Output:
0
1
2
3
For loop:
The for loop of python is designed to process the item of any
sequence, such as list or a string, one by one.

General form of for loop Range( ) based for loop

• for <variable> in <sequence>: • for <variable> in range (start, stop):


• [statements to be executed] • [statements to be executed]
• Example: • Example:
• For element in [10,20,30,40,50]: • For val in (3,9):
• print(element+5,end=‘ ‘) • print(val)
• Output: • Output:
• [15,25,35,45,55] • [3,4,5,6,7,8]
With Range ( ) function
Example: Example: Example:
Print(list(range(10))) Print(list(range(3,10))) Print(list(range(3,10,2)))

OUTPUT: OUTPUT: OUTPUT:


[0,1,2,3,4,5,6,7,8,9] [3,4,5,6,7,8,9] [3,5,7,9]
Without Range ( ) function
Example: Example:
List1=[10,20,30,40,50,60,70,80] For i in [20,11,15,14,3,7,8]:
For i in list1: If i%2!=0:
If i%2==0: Print(i,end=“ “)
Print(i,end=“ “)
OUTPUT:
OUTPUT: [11,15, 3, 7]
[10,20,30,40,50,60,70,80]
# Find the Largest Number in a List # Find even numbers using for loop

numbers = [23, 45, 67, 12, 89, 54] for number in range(1, 21):

largest = numbers[0] if number % 2 == 0:


print(number)
for num in numbers:
OUTPUT:
if num > largest:
2
4
largest = num 6
8
print("The largest number is:", largest) 10
12
14
OUTPUT: 16
18
The largest number is: 89 20
# Python for loop to iterate through # output
the letters in a word p
Y
for i in "pythonista": t
H
print(i) O
N
I
S
T
a
# Python for loop using the range() # output
function
0
1
for j in range(5):
2
print(j)
3
4
# Python for loop to iterate through a list # output
Cat
AnimalList = ['Cat','Dog','Tiger','Cow']
For x in AnimalList: Dog
print(x) Tiger
Cow
# Input a range and print in reverse
order
n = int(input("Enter range: "))
#10 # output
while(n!=0): 10 9 8 7 6 5 4 3 2 1

print(n, end=" ")


n = n - 1
# WAP to reverse a string

n = int(input("Enter range: ")) # output


str = input("Input a word to reverse: ") # Input a word to reverse:

for i in range(len(str) - 1, -1, -1): PYTHON


print(str[i], end="") WORLDDLROW NOHTYP
print("\n")
Range( ) function
it generates a list of numbers, which is generally used to iterate over with for loop. range( ) function uses
three types of parameters, which are:
start: Starting number of the sequence.
stop: Generate numbers up to, but not including last number.
step: Difference between each number in the sequence.
Python use range( ) function in three ways:
a. range(stop)
b. range(start, stop)
c. range(start, stop, step)

Statement Value Generated


Range(10) 1,2,3,4,5,6,7,8,9
(stop) Range(5,10) 5,6,7,8,9
Range(3,7) 3,4,5,6
Range(5,15,3) 5,8,11,14
Range () (start,stop)
Range(9,3,-1) 9,8,7,6,5,4
(start,stop,step) Range(10,1,-2) 10,8,6,4,2
Range () function using for loop
Example: Example: Example:
for n in range(5) for i in range(5,10) for val in range(5,15,3)
print(“WEL COME”) print(i) print(val)

OUTPUT: OUTPUT: OUTPUT:


WEL COME 5 5
WEL COME 6 8
WEL COME 7 11
WEL COME 8 14
WEL COME 9
Note: All parameters must be integers.
All parameters can be positive or
negative
# Print Reverse

OUTPUT: OUTPUT: OUTPUT:


10 10 10
for n in range(10,0,-1):
9 8 8
print(n) 8 6 6
7 4 4
for n in range(10,0,-2): 6 2 2
print(n) 5 0
4

for n in range(10,-1,-2): 3
2
print(n)
1
For Loop Example
Example: Example: Example:
for i in [1,2,3,4,5]: for ch in ‘PYTHON’ for num in range(2,7)
print(i*5) print(ch) print(num)
OUTPUT:
OUTPUT: P OUTPUT:
5 Y 2
10 T 3
15 H 4
20 O 5
25 N 6
# Example on for loop in python:
Print Numbers from 1 to 10 # Calculate sum of numbers using
for loop in python

for number in range(1, 11): sum = 0


print(number)
for number in range(1, 11):
OUTPUT:
1
sum += number
2 print("The sum of numbers
3 from 1 to 10 is:", sum)
4
5
6
OUTPUT:
7
8 The sum of numbers from 1 to 10 is: 55
9
10
# Print Multiplication table using for loop

num = 7 OUTPUT:
7x1=7
for i in range(1, 11):
7 x 2 = 14
result = num * i 7 x 3 = 21
print(num,”*”,i, ” =“,result) 7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
Predict the output
7 x 7 = 49
num =int(input(“Enter any number”))
7 x 8 = 56
for i in range(1, 11):
7 x 9 = 63
print(num,”X”,i, ” =“,num*i)
7 x 10 = 70
# Print Pattern using for nested loop

OUTPUT:
size = 5
*****
for i in range(size): *****
*****
for j in range(size):
*****
print("*", end=" ")
print() *****
While Loops in Python
I t i s u s e d to exe c u te a b l o c k o f
statement if a given condition is true.
And when the condition become
false, the control will come out of the
loop. The condition is checked every
time at the beginning of the loop.

Where loop body may contain a single


statement or multiple statement or an
empty statement i.e, pass statement
While Loops Example_1.1

a=5 OUTPUT:
5 CLASS-XII-ROCKS
while a>=1: 4 CLASS-XII-ROCKS
print(a,"CLASS-XII-ROCKS") 3 CLASS-XII-ROCKS
2 CLASS-XII-ROCKS
a=a-1 1 CLASS-XII-ROCKS
print(a) # 6 no. line is false 0
While Loops Example_2

# While loop example OUTPUT:


a=5
while a>0: Hello 5
print("Hello",a) Hello 2
a=a-3
print("Loop Over!!")
While Loops Example-3

# Squre of a given number OUTPUT:


n=1 Squre of 1 is 1
while n<5: Squre of 2 is 4
print("Squre of",n,"is",n*n) Squre of 3 is 9
n+=1 Squre of 4 is 16
print("\nThank You")
Thank You
While Loops Example_4

# To find out the factorial of a number OUTPUT:


num=int(input("Enter any Number :"))
fact = 1
i=1 Enter any Number :5
while i<=num:
fact = fact*i
i+=1 The factorial of 120

print("\nThe factorial of", fact)


While Loops Example to print 1 to 10

OUTPUT:
1
num = 1 2
3
while num <= 10: 4
5
6
print(num) 7
8
9
num += 1 10
While Loops Example to print a series a number

n = 10
while n <= 100: OUTPUT:
10,20,30,40,50,60,70,80,90,100

print(n ,end = ",")


n = n+10
While Loops Example to take input from the user

OUTPUT:
Enter a number :3
n = int(input("Enter a number: "))
Enter zero to quit:5
while n != 0:
Enter zero to quit:8
n = print("Enter zero to quit: "))
Enter zero to quit:2
Enter zero to quit:0
While Loops Example to calculates the sum of numbers from 1 to 100.

total = 0
num = 1
while num <= 100:
total += num
num += 1
print("Sum of numbers from 1 to 100:", total)

OUTPUT:
Sum of numbers from 1 to 100: 5050
While Loops Example to print even numbers
OUTPUT:
2
num = 2 4
6
while num <= 20: 8
10
print(num) 12
14
num += 2 16
18
20

#Example:To print up to 10 incremented by2 OUTPUT:


i=0 0
while i<=10: 2
4
print(i) 6
i+=2 8
10
# Good exercises on while loop in python: Print a Triangle of Stars

OUTPUT:
n = int(input("Enter the number of rows:
Enter the number of rows: 10
")) *
**
row = 10 ***
****
while row <= n: *****
******
print("*" * row) *******
********
row += 1 *********
**********
# Good exercises on while loop in python: Print a Triangle of Stars

i =0 OUTPUT:

while i <6: Enter the number of rows:6


*
J=0 **
***
while j <i: ****
*****
print("*“,end=“ “) ******
j += 1
i+=1
print()
Example to print square of a number.

num = int(input(“Enter a number to print its square :”))


square= num*num
print(“Square of“, num,”is”,square)

OUTPUT:
Enter a number to print its square :5
Square of 5 is 25
Example to print square of a number.
while=True:
num = int(input(“Enter a number to print its square :”))
square= num*num
print(“Square of“, num,”is”,square)
choice=input("Choose an option (1: Press ‘Y’ to continue, 2: press ‘N’ to exit): ")
if choice==1:
print(“Press ‘Y’ to continue :”)
else:
print(“press ‘N’ to exit”)

NOTE:
If we want to run the particular code multiple times then we
can put the code within a loop.
# Infinite loop

a=0 OUTPUT:
1
while True: 2
3
print(a) .
.
a += 1 .
Up to infinite till the memory full
a=0
OUTPUT:
while True:
1
print(a) 2
3
a += 1 .
.
If a==10: .
break 9
Jump Statement in Python
Python offers 2 jump statements to be used within loops to jump
out of loop-iterations. Jump
statement

break continue

Break continue
The break statement enables a
program to skip over a part of the
code. Continue statement forces the
A break statement terminates the next iteration of the loop to take
very loop it lies within. place, skipping any code in
Execution resumes at the statement between.
immediately following the body of the
terminate d statement
While Loops Example using break statement

n=1 OUTPUT:
Hello Vikash
while n < 5:
Hello Vikash
print("Hello Vikash")
n = n+1
if n == 3:
break
Break statement
With the break statement we can stop the loop even if it is true.

Example: Example:
i=1 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
print(i)
if x == "python":
if i == 3:
break break
i += 1 print(x)
OUTPUT:
1 OUTPUT:
2 java
3
for Loops Example using break statement

For Name in['Jay','Riya','Tanu','Anil']: OUTPUT:


print(Name) Jay
if Name[0]=='T': Finished!
break Riya
else: Finished!
print('Finished!') Tanu
Continue statement
With the continue statement we can stop the current iteration, and continue with the next iteration.

Example: Example:
i=0 languages = ["java", "python", "c++"] for x in
while i < 6: languages:
i += 1 if x == "python":
if i == 3: continue
continue print(x)
print(i)
OUTPUT: OUTPUT:
1 java
2
c++
4
5
6
While Loops vs for loop
num = 1 for i in range(1,6)
while num <=5: print(i)
print(num)
num += 1
OUTPUT: OUTPUT:
1 1
2 2
3 3
4 4
5 5
Loop else statement
The else statement of a python loop executes when the loop
terminates normally. The else statement of the loop will not execute
when the break statement terminates the loop.
for loop while loop
for <variable>in <sequence> While<test condition>:
statement-1 statement-1
statement-2 statement-2
.. ..
else: else:
statement(s) statement(s)
Nested Loop
ü A loop inside another loop is known as nested loop.
ü But in a nested loop, the inner loop must terminated before the outer loop.
ü The value of outer loop variable will change only after the inner loop is completely
finished.

Example: Program_1: Program_2:


for i in range(1,6): for i in range(1,5):
for j in range(1,i): for j in range(1,i+1):
print("*", end=" ") print(j," ", end=" ")
print(" ") print('\n’)

Output: Output:
* 1
* * 12
* * *
123
1234
* * * *
C h a p ter 1
End of

ter
Next Chap our-2
tho n Rev ision T
Py

You might also like