Ch-6 Python Fundamentals
Ch-6 Python Fundamentals
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:
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.
To avoid this difficulty high level programming languages are invented like C++, Java, PHP,
Python etc. That are easier to manage by humans.
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.
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.
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
Hexadecimal integer
(0XBK9, oxPQR, ox19AZ)
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
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)
For Example
Operators
sum=a+b Expression
Operands
Types of Operators
Operator Symbol/Name
Arithmetic + , - , * , % , * * , //
Assignment =
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
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
Output: Output:
Not Overlapping x is not present in given list
y is present in given list
Logical Operators
Operator Name Example Result
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 0
‘“#\()[]{}@,:.=
1.3 Barebones of a Python Program
Lets understand this with the help of sample code.
Function: a code that has a name and it can be reused (executed again) by
specifying its name in the program, where needed.
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
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
solution Try it
5.0 or 4.0 ((p and q) or (not r))
Evaluate the following Expression:
False or False
Output/Result False
Note:
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.
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
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
# 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)
# 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>)
Function Description
Int(x) Convert x to an integer
a=“101” # string
X=95 # integer
# 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_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
#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
# 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
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. 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.
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
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
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
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.
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”)
10. Write a program to determine the current time of Washington, DC, USA as compared to India. (Hint: in
India +10:30 hours)
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:
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)
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��
Output:
# This module contains functions that are used for generating random numbers.
Some of the commonly used functions in random module are:
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.
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.
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
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
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#
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-
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
import random
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:
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:
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
import random
N=3
PICKER = random.randint (1, N)
COLOR = ["BLUE", "PINK", "GREEN", "RED"]
for I in COLOR : (i) (ii) (iii) (iv)
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
If 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
Output : Output :
Enter your score: 150 Enter your score:650
The number is less than 200
>>>
>>>
2. if-else statement:
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:
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:
numbers = [23, 45, 67, 12, 89, 54] for number in range(1, 21):
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
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.
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
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
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
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:
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
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.
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