is a general
gossum designed Python anc
ne famous BBC comedy TV
yihon as 2 language suppo
saintain, This is one impos
Monty Pythanss Flying Circus”
te mating it easy f
this chapter, we wall learn a few ather important feature: and the basic C30
(>>) and Python gives you the result based on the command given. It means y
fun code directly an shell mode accessed thraugh the terminal of an operating system. This mode will not say
your commands and outputs and should be used only when you want to play with small one-line instructis
You can also use the print{ ) function to print the messages on the Shell window. For example
29 64 bit. (ne
Type *help*, ccapyeione™, ‘erudite’ or “themse(|* for mre sstamm
Wearactive ase .
+ Script Mode (Editor): In this mode, you save all your commands together in any text editor with the extension
Py. When we run this text file. py then the output of the commands will be displayed in Shell mode. The stecs
to create and run script file in seript mode are: aa
‘SHEQ 1 Click on the File > New File option in Shell mode. A new blank text editor |
appears, ‘
‘Step! 2 Type the commands and then click on the File > Save as option to save the file.
‘The Save As dialog box appears,
Step 3 Select the desired location to save the file and type the file name in the File
Name box. In this case, we have typed the file name as MyFirstFile py,
New File option
SIE) 4 Click on the Run > Run Module or press F5 key to run the program. The program will execute and
the output will be shown in the Shell window.
ype “hele, “copycat”, *erwMlEa* oe “Lice
Casey
Ms C1 one / RGA ea /PHAEAMAI Pye yh
- Pre rym Ao
Punewag a serge
@> 282 | Touchpad Antificiat Intelligence tx
WAN_— es
@ AiTask ) ee
Colab—2 free Jupyter notebook environment that n
tinny in the clon 419 write and
execute Python cod;
ype itp //cot
which Can be simultaneously edited by the m
research google com to creas
nbers with wham you have shared yout cod
| This process is
nil to the way you edit decurn
in Google Dries, Google theets or Gong
Accharacter set can be a set ol valid characters. For example,
«© Digit tke 0,1, 2,9
+ Letters in upper or lowercase like AtoZ or atoz
«+ Special symbols like §, %, *, 8, *, 0, @, | ete
+ Whitespace lke spacebar, Tab key or Enter key
+ ASCII or UNICODE characters like emoji symbols or other symbo
(S) statements in Python
Instructions written in a source code that are executed by a Python interpreter are called statements There amt
three types of statements in Python which are simple statements, multiline statements and multiple statements
tetus learn about them in detail.
Simple Statements
fy default, the end of a statement is dane by pressing an Enter key. Each statement is written on a raw line
with unique code
isa simple statement where variable ‘a’ is created with value 5.
+b
Multiline Statements
We can make a statement that extends over multiple lines by using line continuation character (\) as shawn
below:
44544
647
B+9
The main advantage of using multiline is when we need to do long calculations and cannot fit these statements
into one fine.
Multiple statements represent more than one statement in a singie line. This can be done by separating the
Satements using semicoton (),
jb = 10;¢ = a + b; print(c)
Introduction te Python | 283Tokens
Tokens ate ¢ ‘
ond ate the wnatiest t
Keywords
Words that have soee
eau are rest
8S identifiers We can ©
command prom
False class Finally
None continue: fer yy
Tue det from we
and det globat my
as ist * Fld ne
assert else umport
break acest in ?
Identifiers (Names)
‘Identifiers are the user-delined names of vara
in Python,
les, list, dictionary. tuples. classes etc. They
yan Bement
Naming the identifiers follows rules a3 given below:
© An ident
can have tetters in uppercase oF loweress2, numbers of und:
« Itcannet begin with a number or an underscore
» No special characters like §, periodt), space, ete. are allowed.
+ Wshould not be a Python keyword.
© Uppercase and lowercase letters are different.
rscorel)
Example of invalid identifiers are
Firstname ; Spaces net allowed
Last&Name Cannot have special character,
_elasstth =; Cannot begin with underscore
Sthelass > Cannot begin with number
else Keyword not allowed.
Example of valid ide
rs ate:
Myclass, class9. Address, address, frst_name, cay, studemtid datal23, _ctassout
Variables = \
Vanable is a name given te
memory loca
type of data that can be changed fu
hold a specific value
ter in the program
2 Kea COMaInE! that can Nols ant variable cn same line,
o
pera bs 2 = 10
Brainy Fact
Python is @ case-sensitive language where upperrase and lowercase characters hawe a
meanings. Name and name are two different wana!
Data Types
Data types specify the kind of 3 value 3 venable can store
be performed on that specific data type, Every value in Python has 3 data type. Same of the stangard burton
data types of Python are:
lps us to identity the kind of operation that can
Data Types
= t
Sequences Sets
fetreduction to Pyvumntsers, |
+ Moat tt
wun the:
+ Complen:
and 26 a na
None: This
represented
Sequen.
can be mutable or non-mutable. There #
‘real umber with Moating pote reprise ,
exponent notation E For eaemple, 115 #1000" —
eis enade up of area! nurnibser anet an lenagina”t
nary number ie
is special data type wih NULL or nema? *
by None
isa:collection of data stored undet 8 COMMON OME os fy
are theee types of data as 3007 4 8
+ String: itis a sequence of UNICODE char on the
created using triple quotes (angie or deat
empty where we have j jotws with ns
sete is
an inten
+ Lists Itis a sequence of heterogeneous values attargied 3
values
of these data types can be changed by the user
» Tuples: It is a sequence of heterogeneous values eran
number, These values are separated by comma and are encioveed im orcs'at
as the values of these data types cannat be changed by the user after crea
+ Boolean:
Language
ae separated by comma and are enced in square bracheas!) They 00288
after creation For #natr
List_of_nanes={*Anit™, "0
Marks=[B9, 92,93, 76,693
class9=[101, "Neha", 89.5, 202, "5h
It is a data type with two built-in values: True or False
represents 1 while a False represents 0.
Data Type Conversion
Data of on
float (), s
e type can be converted into another type by using type conver
(0, ete. The process of converting value of one data type t=
type casting. For example,
>>> float (12)
12.0
>>> int (15.5)
18
=
286 | Touchpad Article
igence
aFaise
You can get the data type of any object by using type ) function For example.
>>> type tio)
?>> type ("abo")
>>> type (14_5
literals
it is defined as any data stored in a variable. This data can be Sting
quotes. For example,
“Hello”
‘Python’
+ Numeric literats: They can bé integer, float or complex, For example,
14
205
245)
* Boolean literals: They can be True or False. For exemple,
Tue
© Special literals: Only None is a special literal. It means something not yet created.
Punctuators
Punctuators are special symbols used in Python to arganise statements and expressions Most comment used
Punctuators in Python are:
“#\000@.:
Operators
Operators are special symbols used to perform mathematical, logical and relational operations on vanadies
and values. The variables or values on which the operators work are called operands. Some commoniy uses
“perators in Python are arithmetic operatars, relational operators, logical operators and augmented assignment
‘*perators.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on variables and values.
Introduction te Pythen 28:
a CLL‘ome Symbol Purpose bearwle ste
a4 ‘
dition . to ethos go+4
6-2 ‘
Spication Ne Muylnpies two values
25
Ehisio : Divides two values yan 83
Returns the remainder of a division oak ;
Ceiarsaa a Second number raised to the 52
ae power of the first number. & w-2 23
yz 5
Divides the first number with the ;
oar inion: second number and returns the “uy2 .
st us whole number adjusted left to the a4 3
number line. a a
Brainy Fact a
* Ifwe use + (Addition) operator with strings, it concatenates two values. ,
+ If we use * (Multiplication) operatar with String and integer value, it repeats string value same
number of times.
‘elational Operators
elational operators or comparison operators compare the values given an both the side of the operators arg
turns the boolean value either True or False. Following relational operators are provided by Python
Name Symbol Purpose Example Output
a=S
Reti Te if both thi i
2 jeturns True if both the values are oul
Equal
_—~ same otherwise False,
gy 788 | Touchpad Artificial Intelligence-D¢
WaNot equal to
Ratuaris Truw of fret a
than
- than second salut ¢
et vate is 2
poturns True 1 the first value 1 SS
teens - than second volue other
penne gruestt tha: Reet ee
greater than OT gi greatats the or equals to the me
— second value,omnennise False sole
; 7 a=5
returns True if the first
ee oan or equals to the second value a
eat otherwise Fals@- sb
Brainy Fact
Python uses ASCI/Unicede character set. ASCIE Stands for “american Sande
information Interchange. is a character encoding standard that uses fF
represent characters in uppercase and lowercase, numbers and punctuation Fy™Do
values of capital letters A-Z are 65 to 90. small letters are 97 tO 122 and sumBers 9 10 9 are
1057.
Logical Operators
2 used to combine one or more
Following logical oper:
Logical operators are conditional statements and returns either True
ators ate provided by Python:
cased on the evaluation of the conditions.
Name symbol Purpose Example
Returns True if both the operands
AND a perands e
ia are True otherwise False, Faster Bs
Returns True if either the operand:
x or perands 5 > 10.0r2 >=
6
7 iiss
8 not, and, oF
an expression contains two or more operators with the same precedence, then order of evaluiation is from lett
ta right except for exponential (**} which is always fram right to left. For example,
* 10-2 + 3~3 will be evaluated from left to right as + and — has the same order of precedence. So, the answer
will be 10 ~ 2 will be 8 + 3 will be 12-3 will be 8
= 23 * 2 will always be evaluated from right to left. It will be calculated as 2
(2** 3) ** [Link], the answer will be 522,
(@ ™ 2) and not as@ aitosk
Solve the following expressions using the operator precedence:
* 10+20/5-3*2
* 5°(0+5)+10-5
@ ‘Comments in Python
Comments are used to increase the readability of the code. We use them to give proper un
code in simple English statements, They are completely ignored by the Python interpreter
practice to add comments in your code $0 that if anybody in future wish to understand or
‘then through comments it will be easy to interpret the instructions. There are two dif
comments in Python, Let us learn about them in deta.
Fert waTS OF ie
Single Line Comment
Single line comment starts with hash symbol F followed by the text to be written as a comment that last il mg
end of the line,
For example, .
F assigning @ value to dhvarable ’ ‘
numl = 10
num2 + 20
# calewlating the
verage
(num + numa) / 2
Multiple Line Comments
‘When we add up comments which occupy two or more lines then we begin the comment with either 31
single quotes “* or double quotes "*", followed by text on multiple lines and end with single quotes or
quotes
‘0 mark the end of the comment. For example,
progrem calculates
the average of
two numbers stored in
two different varlabias"*"
a= 10
b= 20
2 fet ey ¢
232 | Touchpad Artificial Intelligence-1x
Sea oT
The print() Function
i 15 into a string before
age print U function is used to print an output on the screen, It converts the expressions In q
iting to the screen. Syntax to use the print ) function ist
tebject (a), sep ~ separator,
F end - end)
where.
4 object can be one or more separated by camma and It can be a variable, literal, expression. An object v1!
converted to string before printed,
| sep is Used as a separator if there are more than one objects.
end specifies What to print at the end, Default is newline‘ \n"
allowing are some of the examples of the print ( ) function
Commands Output
print (hello) hello
te print("hello", "friends") hello friends
prtrtqmhello* + “friends") hellofriends
(This is concatenation of atring using "4"
operator)
print(*heilo", "friends", sep-"8") helloStriends
print("hello", "friends ‘s, sep="$", end=*!-) hello$friends!
brine (hellic’,, Otends's endewiel | eee iiaile fiends!
print ("hello") helio
peint () friends
print{" nda")
print (*hello", end="8") hhello%frends
print ("friends")
print "hello", “friends”, *welcore", se hello#triends#welcome®
end="@")
print ("2 em in class", 9) Tam in class 9
a-5
b= 10
Sum of two numbers is 15
print ("Sum of two nun
14
is “ + ste(a + bi}
age Jam 14 years old
print("I am “, age, " years old")
(tre input() Function
The input { } function is used to take an input from the user, When, this statement executes then the flow of
the prooram stops and waits with the cursor blinking for the user te enter a value The input given by the user
ig always @ String value in Python. =
Introduction te Pythen | 293» Ses
i LETS =When the preceding statement executes, it will ask to enter name. Winen you enter th
key. entered name will be displayed on the screen
race and pene
{f we execute the preceding cade and enter 4 and 5 as the values of the first and second numiars
answer will be 45 instead of 9, Thisis because Python considers every input vaiue as string, ifwe wane taper:
mathematical calculations, then we have to convert the taken input explicitly by using
functions. The syntax to convert an input value into an integer oF float type is
# to convert inte inte
a = int (input (pi
pt)
sat (input (prompt) # ta convert ifte Roat
Lot us create the preceding program again by using the int ( ) function.
= intlinput("enter first number")) #line 1
a
be #line 2
As you know that a program is a set of instructions given to a computer to do a specific task. The order of
execution of these instructions controls the flow of a program. There are three important ways to control the
flow of a program which are interpreted by any programming language in a structured manner. These are:
= Sequential
+ Selection
+ herative
Let us learn about these in detail.
® Sequential Statements Te
A step-by-step process of execution of code is called sequential flow of control. This is the default flow of
er on of a mrogram. It means that the computer will run the code one line at a time starting from line 3,
followed by line 2 and so on tll it reaches the last line of the program.
Let us take an example of making a mango smoothie, The steps will be:
1. Put mango pieces in a Mixer jar
2, Add sugar
Intreduction to Python | 295ne More ¢
© TnpAt First panne and Last name fem the user ancl diaplay fill nartye
Algorithm Flowchart
start
Input FastName
Input LastName.
vame + LastName MeUT
fullName= Firs Lae
Display FullName “ = ey
Stop £
Source Code: Fuliaenaes Ford Maem Lint Maen
a
+FullNames" 7
1
:
Output: ic "HF )
Enteryour First Name ‘Suzan,
Enter your Last Name :Chtistopher
sell (Suzan Christopher Welcome to the World of Python ,
‘+ Input Length and Breadth of a Rectangle. Calculate the Area and Perimeter
Algorithm Flowchart
ps
Input Length, Breadth
Area=Length X Breadth
Perimeter= 2(Length X Breadth)
Display "Area is", Area
*, Perimeter
Display “Perimeter
Stop
Source Code:
ength= £
Breadth = int
Area= Length*Breadth
> 296 | Touchpad Artificial Ineligence-Ik
; ~AO\,ger Breadth 10
i"
aa s 50
perimeter is 100
@)AiTosk
ah en by TH peters, aay ror
‘Type “import this” in your Python IDLE and you will find a poem weitte by
to the Python community.
|
* Gb ai Task ae
Input a radius of a circle. Calculate the area and perimeter of circle.
Se Selection Statements ~ .
In Python,
Selection flow of control is achieved through conditional statements.
« In the conditional/selection statements, flow of control is changed based on 3 con
condition in the program which evaluates to either True or False.
+ {if candition is True then the block of statement written for True will be executed and
False then the block of statements for False will be executed.
+ Conditional statements are also called as branching statements as a program decides which sta
execute based on the result of the evaluated condition,
+ Abblock is identified by using an indentation (minimum 1 space). Ensure that all statements in one block are
indented at the same level.
'* Python mainly provides three types of conditional statements—
Let us learn about them in detail.
jon. We specify the
in case the condition 15
tement to
statements.
Introduction to Python | 297
LLELLEee
he
The i Statement
We 00 the i
'
Wletnerit to uM GOO aHA Retigtattinang. Carta aH trae | NNR em He a
‘enatas then (1 Suwveree 11 apical uo ee puarOtvenlh. IH Poms 4 Mimsy Chom Fw ag
20 8 ot a Ite ee Mbatannyent TY atten shanmsrunib Kata Kant a 4 BHO) smn HPI 6
Hae be pase
Konelinien LN HO. A Matern ltach .. >
WRercent h more than #0 then =
Display *Congratutauens® 7
Display "Your are awarded Certificats of Uxcellence”
Stop
Source Code:
POLCONt= int finput ("En your paccentane 1)
percunt 4d;
PEt (MCONGHATULAT LORS")
PrLAt (YOU 9E8, ANAL | Samet Cena b?
Output:
Enter your percentage 49
CONGRATULATIONS
You are avarded~ ‘Certificate of Excellence’
NK 4. 298 | Touchpad Artificial Intelligence 1
Nee
AN |weoeklay
“gobi 1S SAMEAS “SUNDAY then
paniay * Reward Point - Checolate Cookie FREE Ir
wr
source Code:
eCeRTE NPT
enter day of the week ; SUNDAY
seward Point ~ Chocolate Cookie FREE
The if...else Statement
When the condition is True then the statements indented just below the i: statement wil &
executed and if the condition is False then the statements indented just below the «Lae statemen
will be executed, The else statement is optional and if required can be only one «ise statement in on
22 block, The syntax to use the {false statement is:
Af (condition):
Statements for True
gise:
Statements fox False
Where,
« Le and alee are keywords,
tdon can be any relation or logical expression.
+ statements are always indented and can be single or a block
Tnoduction to Python | 239 a
LttProgram a: Te ingait WO mumble” ana display the bigger Of!
Algorithen ' Howehart
Stor '
Input Na, Ae ‘
4811 68 Greater than nathon
Display Nias tigger |
Otherwise
Display “N2 ts bigger
Stop
Source Cod
NU = Ant Clnput (“eames fhe ey) |
H2(OUCinput (Meaten 4 Number
Nise:
PUANCQNL, Le Bigger "9
Print (M2, "L9 ba or
Output:
Enter first Number :34
tater secend Number 45 STOP
45 is bigger % .
Program 4: To input a number and display whether itis even or odd.
‘Aigorithen Flowchart
Start
Input Num
If Num is divisible by 2 then
Display “Num is EVEN*
Otherwise
Display "Num is ODD"
Source Code:
Num=int (inpul ("™eatee 4 Number 27)
Numt2=—
print (Wum," ie EVEN ")
print (Num, " is opp *)
Output:
Enter a Number :23
23 is ODD
300 | Touchpad Artificial Intelligence-IX
SR,if,..0lif. else ® Statemene
there re tit
er
mip eoadition 6
erent Below it wi
caneOR STN ;
Senecuted The 570A ef they
Hateenacts weitie . es
+ statement ig ax
z teondit seni)
aeamere
¢ toon
gratenonte +
plant
grataments:
smeared whe
where cnn
eo LE wpdne 25 f ate cpwees
Mabe cn
2 3d on
5% 140 be any sepraccnn
33 re anys sneteriins cae bee os
statementes and »
Start
Input NI, N2, op
fap is seme as that of ~’ thaw
Display N1+N2
Ctherwise, if op is same at that of ier
Display NA-N2
Otherwise, if Op is same as ther of then
| Display NI*M2
Otherwise
| Display "Wrong operator entaren”
=
Source Code:
Hietnt input (aecer
"int tinpu
Ste GeOutput:
Enter first Number 5
Enter second Number -4
Enter an operator(+,~* only) :*
The multipication is 20
Program 6: To input a number and check whether the number is positive of negative, -
Algorithm
Start
Input Num
{Num is same as 0: \
Dispay “You entered zero’
Otherwise, If Num is greater than 0;
Display “You entered +ve Number"
Otherwise
Display "You entered -ve Number"
Stop
Source Code:
Num=int (input ("©
Num==9 3
print
Num >0
Pprint("¥oo 2
print ("You
Output:
Enter first Number 4
You entered a -ve number
3. 302 | Touchpad Artificial Intelligence-tx
~AARAL
Flowchartnested if Statement
geting one 2
f stotement can be upto:
Statecvent within anotinar 42 is caea nested x6
|, Indentati i statement. Nesting of i
ggievet Incentation plays avery important role in identitying
the levels.
program 7: To input billing amount and gender. tf the billing amount is more than 10600 and gender is
jemale. then discounts. 15% otherwise discount Is 0%. Calculate the billing amount accordingly.
orm
gatt
sput Amount, Gender
amount is more than 10000 then
|
if Gender is same as that of “F* then
Display “Amount after 15% discount is =, Amount-(0.15"Amount)
Otherwise
Display "Amount after 10% discount is *, Amount-(0.10*Amount)
ctherwise
Display "Sorry! No Discount”
Sop
flowchart
Source Code:
amount«int (input ("Enter billing Amount: ">) ;
zi input (“Gender =")
gender=i0P! Intraduction to Python | 303 s
LTETTrey! sa ds
Output:
Enter billing Amount : 12000
Gender :M
Amount after 10% Discount is 10800.0
Program &: To input a number and check whether it is multiple of 5 or not. This check is valid only for
positive numbers,
Algorithm
Start
Input Num
if Num is greater than zero then
if Num Is divisible by 5 then
Display “It is multiple of S*
Omerwise
Display "Not divisible by S*
Otherwise
Display "Sorry! Invalid Number”
Stop =
Source Code:
Numsint (input ("Enter a number 2"
Num>0+
Numts==0:
print (Num," is multiple of 5%)
print(Num,” is not multiple of 5%)
print ("Sorzy! Invalid Humber")
Output:
Enter a number : 34
34 is not multiple of 5
304 | Touchpad Artificial Intelligence-tX
\ NARA.
Flowchart
START,
¥ Brainy Fact ~
True meane NON-zer0 numIser oF non-empty object and False means rero number or empty object
ve
(e)terative Statements
ton, the Process of repeating a set of instructions based on @ condition is called Joop. There are two types
ucopsin Python—tor loop and white loop. Let us lea about them in detail,
he for Loop
be Cor foop 15 used to repeat a set of instructions for a fixed number of times, It means the number of
gations are known/ definite before we start with the execution of a loop. Therefore, the for loop is also known
defile loop, Indentation of statements is must Lo specity the block ot statements to be repeated using the
or logp: There are commonly two different Ways of using the fox loop:
Using Sequence: In this type of tor loop,
4 Sequence of values is used on which the loop iterate, The syntax to
use the £01 loop with a sequence is;
for in :
Statements
Where,
» for Bakeyword,
+ counter variable is any
lentifier that keeps a count of the loop.
sequance Is any values like integer, string, list, etc.
Statements are always indented can be single or a block.
Different examples of for loop are:
Commands Output
for 4 in [1,2,3,4]: 1
print (1) 2
3
4
for words in ("hello", "friends", how are you 2*}: hello
print (words) friends
how are you?
for alphabets in "hello!™: h
print (alphabets) ;
1
°
Introduction to Python | 305 3
{>ene
vatse=1 fl lop
value becomes 1 by ont
eras Q and Stan banumen 1 by cota
tio output
given enter starting ¥3
5
enter ending wal
10.5,7.9,and logic
‘operators (3nd, ar) retums tue oy
the while Loop
= lo0p is used to reps
sumber of iterations ate not fixe
definite loop. Indentation
2 leop
at a set of instruc
GVincefinite before we start with the
ons as tong 95 the condition i true. tt me:
Sxecution of aloop. tts th
block of statements to be
aR when the
Of statements is must to specity th ca
Ths loop is also called an entry-controlied loo
coniiion is tue then the bedy of the loop wit
rpemer within the loop and it stops,
{or the concltion in the begin
\ ing only
is false then it wit
IL nat be allay
is a keyword.
ditt ions @ criterion fa repeat the instructions. The ing
the conditions Felss, the control ets fo
structions repeat til
1m the loop.
Ithe condition is True, AS soon as
"its are always indented can be single ora block and are fepeated tithe condition is True:
Brainy Fact
When there is no change of condition in while leop then it becomes infinite loop, For example,
aot
whlie i 310 | Touchpad Artificial intelligance-tx
‘ WA,F -_ pryeTrHrorn®
print
print (indexno, end:
Using + Operator with List
The + operator is used to concatenate the list with another list, Remember that b
the
a piyiTiHTornl
e Mivalent tot
Ba Lists
Tt}; u(2j, weir eer
ty 1ayst
se orat2i3!
index hunbéer of each element in & ©
THe, THE, Not, THE
exno in range (len (hl)
oth the operands on either side
of the + operator have to be a list only otherwise it gives an error, For example,
A= (1; 2
B= 14, 5,
crate
print (¢)
A» (1, 2
B- (4, 5
Bt A
print (B)
A= (1, 2,
B= (4, 5,
C= (ty 8,
Cor
3]
6)
3)
6)
3)
6)
9}
D=A+tBHC
print (D)
Ae [l, 2,
3)
B=A+ [10,
print (B)
A= (1, 2,
3)
B= A+ "abe"
print (B)
mmands Outpue
(1,2, 3,4, 5, 6)
14, 5,6,1, 2, 3]
(1.2, 3,4,5, 6, 7,8, 9]
{2 2, 3, 10, 20)
20]
Typetrror: can only concatenate list (not “str*) to list
Introduction to Python | 311
ALLA LAOE Se
tea, d (12,345 67.891
= 1% By 9)
Mewlist = at 4 44, 5, 6) + 13
Print (newlisty
Using * Operator with List
The * operator is used to replicate a list by # specific number of times. With * operator
list and the other shoutd only be an integers, otherwise it will give an effOr. For exam
Or one operand hat to
Commands Output
Ae, 2,3) 123,1232231
Pea as
print (B)
a 155.5)
Ae (x74 3
print (A)
Commands Output
nane > "hit" [Amit ‘Amit, ‘Amit, Amit]
Zt= [name] "4
print (za ,
nilne - "Amit" — Typefrror: cant multiply sequence by non-int of type ‘st
1 ~ [name] *
ma"
Comparing the Lists
The comparison of the lists is done using comparison operators >, <.> and ==, These operat
‘compare the elements in lexicographical order. For example, if corresponding elements are same, it goes to
next element, and so on until it finds elements that differ. For example,
i= [1, 2, 3]
z= f
1 @ 3]
13+ (, 2 13
dd = 11.0, 2.0, 3,0]
print (it == 12) #True
print(11 > 12) false
print (1? == 13) aPalse
print(1l == 14) s¥alse
print((l, 2, 6] = and
«The append( ) Function appends a single element with the given valueany datatype! at the end of IM st
2. 318 | Touchpad Artificial intelligence IX
eeu 97 Oe~
A Whi
Nh Of the following isa sequence of UN
x
Zerodivisin
a usontrror eros»
as b. Logical t
© Runtime g ston
ror crabet
on Error
OO
«Bo CODE characters?
lean, a) b. Numbers
© String oO d. Float
10. Which of ti ;
bs Of the following is a data type that has two builtin values True or False?
rin
a oO b, Boolean
© Integer Oo Flot
1. Which of Fi
~ oF the following conditional statements is used to test multiple conditions?
a
i ( b. [Link]
© if.
[Link] © d, All of these
X12, What will be the output ofthe following code?
i€ (true):
Print ("Hello")
else:
print ("Hi") ;
a. Hello ©) b. Hello Hi
¢ Hi O d. Nothing will print
13. FLL =o, R, ',‘G',"E, then what will be the output of the following statement?
print (21) _
a. ‘ORANGE’ © b, (OW'R "ANY "6, "29
OF 'RYAY NY Gh ie) , None of these
yi Consider the following code:
A= ["Orange")]
B= ("Education")
C=A+B
print (¢)
Which of the following will be the output of the preceding code?
a, Orange’, Education’) Oo b, [Orange Education’)
eoreneeveten oO d, Orange + Education
yas,
‘E] then which of the following will be the output of the given statement?
print (L1[::-1])
a, Prints the list as it is ‘© b. Prints the list in reverse order
cc. Prints the last element of the list @ d, Prints the first element of the list
B, Fill in the blanks,
De Aine
2 In
1 RAAAANO OU: « .
sun is written in any programming language.
uuu flow statements are placed one after the other.
320 | Touchpad Artificial Intelligence-IX
Zy
OO
OOo
COO” times")
e Unsolved Questions
5 SECTION A (Objective Type Questions)
Ai@viz
A. Tick (v) the correct option.
Which of the following is not the conditional statement in Python?
a. if Statement oO
¢. ifelse Statement S
b. if.
[Link] Statement
d. None of these
2. Which of the following is a looping statement in Python?
4 4 torstatement
'@ bb, while statement
« Bothaandb er d, None of these
> Introduction to Python | 329a PRAT a veh FOP A Views sienben a
vie (e 1b otoe state )
y “otement : ¢
J@yrvenre © 4. continue statement )
following can be a port Of a ticte
4 String values bs Cc
ae CG b Integer valans e)
= 2 4. All ofthese Oo
alist name, :
His : “11 contains 4 elements, then which ofthe following can be used to access the last element ofthe UI lot?
a ul