Understanding the
Programming Basics
Structure
In this chapter, we will discuss the
following topics:
. Learn basic programming skills
through gamified platforms
+ Explore online portals like Code
Combat to understand coding
basics
Questions and Answers
i Objectives
|
| At the end of this chapter, you should |,
|) be able to:
1
{
| + Play online games that encourage i
| trial-and-error, critical thinking, |
i and creativity. t
i
Apply the coding skills learned by |,
developing their in project-based |
| solutions i
henever we want to use a computer for a specifictask, a chronological
order of instructions have to be given to thecomputer which can be
easily understood and interpreted. These set of logical instructions
ritten in a high-level language forms a program. Software development
corporates various intermediate tasks that follow anorganized plan and a
ries of sub tasks for application development.
rogram development stages
* Analyzing a problem requires a clear
definition of the problem statement,
inputs, processing and desired outputs,
and user interfaces.
Designing the program involves a clear
logical plan explaining the algorithm and
flowchart of the program activities. i
Coding involves translating the design
into an application using a programming
language.
Scanned with CamScanneri vy
ires making ! =
io atin an information manual for the |
&y
jerstand it better. Co,
Its accurately in Nese |
he program error free
+ Testing and Debuggin
n involves Pre
* Documentatio
user. cept
i n
Let us delve a little dee 10 the co!
to und
the resv’
" t
ous tasks tO get + .
are used to perform vt Iways need to follow steps 17 @ particular ms |
To perform any task, we OWT should be given to solve any py, Orde,
ites ‘oblem is defined, yo
Therefore, step-by-step ins
Thus, solving a problem depen
problem is designed and then implemente
To represent the steps for problem solving,
A-B-C-D Rule
ls on how the pr it he
d using a programming lan, " the
you need to follow the giver oe
‘,
he given problem.
wefully to understand the basic functionalities,
he inputs required and wat all calculations need to be
get the desired output.
Try tounderstand th
Read the problem
ii. diagrammatic representation
© ili, online tool to draw flowchart
d, Flowchart iv. Step-by-step procedure
e. Algorithm v. Decision
{, Din A-B-C-D stands for ea
7 vi, Proces
h. Cin A-B-C-D stands for viii. Debug and Test |
3, Write the full form for the following organizations:
a. HLL ]
b. A-B-C-D
c. RPG
4, Define the following terms:
@. Flowchart
b. Algorithm
c. Program
5. Write any one important feature of the following application
a. Code Combat
b. Draw.io ;
6. Write the functions ofthe following:
a. Translator
[ None tna tees applications of gamification which are used for
learning programming skills.
Understanding the Programming Basics 1 12)
Scanned with CamScanner1,
12.
13.
. Write an algorithm ani
bers and display the sum, gi
Bre,
two num
se two numbers.
Draw a flowchart to read
multiplication, and division of the:
int the bill depending on the price ang
Write an algorithm to pr eee
9 he GST, which is calculated as 18% oh
of an item. Also, print t
bill.
a,
d draw a flowchart to print five Multiples
Gee
number.
Write the stages involved in program development.
Define A, B, C and D in A-B-C-D rule for problem solving,
Write the steps required in analyzing the problem.
Scanned with CamScannerruclure
pis chapter, we will discuss the
oe ing topics:
ee peattreS of Python, Python
|* Gharacter Sel, Token “and
jaentifiers, Keywords
| jptroduetion to Python
programming: process of writing
program, running it, and print
statements
| pemonstrate the knowledge of
gmple data-types: integer, float,
string
. piscuss the purpose of Single line
and Multi Line Comments
. Understand the purpose of a |)
variable and how to manipulate it
+ Ilustrate accepting —input,
assignment statements — and
writing expressions
+ Understand different types of
operators: Arithmetic, Relational,
and Logical
* Introduce Conditional statements:
if, if-else, if-elif-else
* Writing simple programs
* Notion of iterative computation
and control flow: for, range ()
Questions and Answers
Objectives
| At the end of this 1
is ch |
(eae hapter, you should \
Appreciate the use of Graphical |
User interface and Integrated |
Development Environment. \
\
(+ Understand the design for the
Programming environment _ for |
creating Python scripts and |
programs.
| + Understand the concept and |
usage of different data types and |
operators in Python. \
Create Python scripts using basic |
control flow statements }
Scanned with CamScannerython is a modern computer pre
the development of many applica’
to WWW browsers fo games: The si
program code helps the programmer focu'
language itself. It is an Open Sour’
copies of the software, read a
community.
The Python program can be run directly fro
converts the code into bytecodes which Is |
language to run if
about the compiling
the code. Hence, ™
since it is porta
on every computer |
scientific and non-sc!
Figure 9.1: Python logo embedded with ©
Python was created by Guido Van Rossum when he was working at Notion.
Research Institute for Mathematics ‘and Computer Science in Netherlorg |
on the solution rather ai
ce Software; the user can freely dist 4
nd make changes i
ble by nature and work indepe;
ther customizable applications,
gramming language. If .,
ications ranging from text pro Pay |
inplicity of writing on Eng
a
bet
and redistribute again 4,
Of.
m the source code. The inje, }
translated into the computer's vel
it, The programmer need not,"
‘and linking of librories 12%)
aking Python a favorable ott
beg |
Aden |
It can be can be used for be
‘entific programming and can,
b
'
|
The first version of Python was released in 1991. Python can be used tofala,_
both Procedural approach and Object Oriented approach of Programmig |
It is free to use.
Some of the most popular features are as follows: |
+ Python is case sensitive language.
* Itisavery simple high-level language wi
gives immediate results.
t
'
* It is excellent for beginners as the language is interpretedand here, |
;
|
* The programs are easily readable and
* Itis easy to learn and use.
To write and run Python program, we need to have the Python interp®
installed in our computer. IDLE (GUI integrated) is the standord
development environment. IDLE is an acronym of Integrated Develop”
th vast library of add-on modus.
understandable.
;
t
|
Environment and can be downloaded from www.python.org. The progatt
can edit, run, browse and debug Python Pro
the latest version, 3.7.
grams from a single interface |
There are two ways to use the Python interpreter:
* Interactive mode
* Script mode.
124 @_ Artificial Intelligence
Scanned with CamScannererote ae allows
in neous whereas the seri
ott
3" files:
XeCution of ;
Pt mode Si individual Bi
see ging an interactis i ed to create and edit Pre
2 ill Be ti ive online Pp, edit Python
" 00 ing Our programs, quen editor https:/
z RAM graphi: - Google WHps://colab.
12,6 RANT Graphics processing un hee Ee 1 oe Pron
are the ronare Support. The program
‘Cogle Docs. The Notebooks with other j
nt() in-built function
Foon print() function is used to print infor
4 mation on th
gyntaX? S le screen.
vit (message) or print (variable value)
co & Python Basics
ot oe ie eh a ee e
+ Code + Text raw
ve es 7 A Editing]
© print (“Good torningt”)
[> Good Morning!
Figure 9.2: Image Screenshot of Colab Notebook (interactive mode)
Comments
Comments are the statements added with the code which are not executed
bythe interpreter. They help the developer understand the code better while
“ring to it later.
‘comment starts with # (hash sign). Statement following after # ‘ill the end of
line is treated as a comment ‘and the interpreter ignores it while executing
"eslatement. The sole purpose is tO add readability to the code
Ner
we two types of comments:
| * Single line comment using #
Language @_125
python Program
Scanned with CamScanner+ Multiline comments use TPT Le python interpreter ee SPY Staten’
the end will also be ignore nN
ments.
within them will be treated as COM
ithin them will be trea’
feine¢-eood Horning!)
[Good Morning! *+oOes,
© emis is pesnec) funetten OA ganb ALA eY land understanding
casa ee
Srinec"Good Noxning!”)
C+ cood Morning!
Figure 9.3: Python comments
Variables
A variable is a named memory location which stores values that can be ro
later, A variable is a name hig
@ «-2 refers to a value and an assignn.,
statement is used to create _,
pi = 3.14156
variables. There is no command},
name = "Jack"
declaring a variable in Python.
print (x) A variable is created when a va;
petotiet) is assigned with the help of
ea aad assignment operator (=). The pit
D 12 statement is used to display the vole
3.14156 of variables.
Jack
Figure 9.4: Variables
The rules for naming a variable in Python are as follows:
The nome should begin with an uppercase or a lowercase alphabé®
on underscore sign 0. This may be followed by any combindlcr!
ers a-z, A~Z, 0- zl i
digit. or underscore (_). A variable cannot start vit
: cen te of any length. It is preferred to keep it short and meaning!
t should not be a keyword or reserved word
Special i ;
pecial symbols like !, @, #, $,%, and so on cannot be used in vor
126_@_ Artificial Intelligence
te
Scanned with CamScannera 2 followi
DATA Typ following types of data
Numbers Ni
lone Sequences gt,
Moppings
Integers Floating Co :
Point rmplex Strings Tuple List oT
Boolean ictionary
yegers? These are the whole
1 iMmal digits like 100, -35, GUMBErS consisting of + oF ~ sign with |
geveloper need not to worry about the size of Pee tears te |
ore is automatically handled by eee eee eae \
ioe (): This function is :
Pt Number used to check data type of variable or value. \
» Floating ers with fractions or decimal point nt . \
int numbers. A floating point number will consist of sign (2 ae \
pPfecimals digits and a dot such as 0.0, -215.967, 0 soles |
» Sang: A string is a sequence of characters which are enclosed in single !
quotes (‘’) or double (” ”) informing the operating system where the string
constant begins and ends. They can have any character or sign, including
space. Square brackets can be used to access elements of the string.
@ «-:
eer
average = 98.56
qeacher_Name = “Jack”
status = ‘Y"
x ig an intes
y is an intes:
average is a floating point number
Teacher Name is a string
Status is a single character
wear
print("Character= ",Teacher_Namet?) )
print (cype())
print (type(y))
print (type (average) )
print (type(Teacher_Name))
print (type (Status) )
G characters k
Figure 9.5: Dato types
Scanned with CamScanneryr
Python Keywords
in the program fo:
Keywords are reserved words that can be used in p TO pre,
of ing for the interpreter, th Shin |
purpose. As these words have specific meaning ey cat
be used for eu other purpose oe ere
an raise t
for from |—erurn | if
ee ea
Ise while —_ * om nal
e
acco» 2 Printivo)
manorrror: nano ‘print’ se not cosine’
\
|
oes:
Bese |
|
|
|
|
Figure 9.6: Error message encountered for invalid keyword usage
|
Operators and Operands |
Operators are special symbols which represents computation which al
applied on operands), which can be values or variables. An expressions|
created when operators are applied on operands. Same operator can bebo:
differently when applied on different data types. Operands are values or
variables when used with operators. Operators are categorized as Arithme’:
Relational, Logical and Assignment.
Arithmetic Operators:
Operator Name
Example
+ Addition en.
Subtraction fe 100
. Multiplication
111] ‘cood"+*Bvenins"
Ce ‘Goodzvening’
112) 76-45
com {
(13) sees
C1906
Figure 9.7: Arithmetic oper"
Intelligence
Scanned with CamScanner%
a
“/
Division
Modulus 0) aay
Exponentiation © ine
209901951 35927045
Figure 9.8: Arithmetic operators
Floor Division
(21) 9.0772
G 4.0
© v2
G 4
Figure 9.9: Arithmetic operators
telational Operators:
Operator
>
Name | Example
Greater than _ © reine)
Less than prine(100<190)
Equal to
(3901=102)
eine (120>"102)
ee prinetiozen209)
Greater than or equal to Ch tree
eve
rue
False
true
ralae
true
Figure 9.10: Relational Operators
Scanned with CamScannerLogical Operators: These operators are usedto combine conditional stay, v
Exar any, |
Operator Description mple |
i xel2 |
Returns True if both ° ; }
and print (2750 and xeigo,
the statements are true Print 0250 OF aciony
Returns True if any one print (ROLGESO ang ye,
cal nt is true ony)
of the stateme! co raise
not Reverse the result, eve
returns False if the _
ee Figure 9.11: Logical operaton,
' |
Expression and Statements : |
An expression is a combination of values, variable and operators wi |
generates a single value. |
Example:
s = 18 a = 9.0/5 + (26 - 13-0) + 2*83
t= 25 print("result 1 a)
_ [> result = 12.8
print("value = ", U)
Figure 9.13: Expression }
value = 43
Figure 9.12: Expression
Precedence of operator: Higher precedence operator is worked on belo:
lower precedence operator which determines the order of evaluation ©
operands or values. When the operators are of the same precedence, &
are not grouped by parenthesis, the order of execution is based on pert
associativity. An operator may be Left-associative or Right —associative. IF
associative, the operator falling on left side will be evaluated first,
right associative operator falling on right will be evaluated first.In Python”
and '**’ are right associative. The precedence is listed below in the ode
high precedence to low precedence.
Operator Description
**
° Exponentiation (raise to the power)
7: unary plus and minus
Scanned with CamScannerMalki
aiviee
Addition a
Compariso
Equality o,
Assignmer
Logical oj
NY. divi
y divide, Modulo and
floor
ind Subtraction
N Operators
Perators
‘Nt operators
Perators
function
if ui() functionis used to accept data fi
x of inputl) is: Tom the user of the program.
= foromel)
pt is present, it is displayed
yed on the screen after which the user can
she pro!
de the dato. from keyboard. The functi
ea te eecigns it fo the variable. ction takes the data and converts it
[i] name = input("Enter your name + *)
english = input("Enter your marks in english
maths = input("Enter your marks in ens
science = input("Enter your marks in science : *)
total = english + maths + science
print (name, " has scored ",total, " marks.")
[> Enter your name : JACK
Enter your marks in english : 78
Enter your marks in maths : 89
Enter your marks in science : 87
JACK has scored 788987 marks-
Figure 9.14: input() statement
s very different from the
the default setting of string datatype
function. In the final answer, the
assuming them to simple
+ variable values into a
tu would have observed that the final output i
‘seed output. This happens due to
*ony variable accepted with the input()
“preter has merely concatenated all the numbers
“secters, Therefore, we have to convert a ee
"tie datatype type for any further manipulation
he to anotl
ing conversion method from one Sey oe float) fun
:*8sting. We will be making US¢ of int (
fe BAe
sired results in this example-
a mw
. Pythow Programm
Scanned with CamScanner
her is called as
tions to achieveay name = dmpue (Enter YOUE MANSY %
0 nae TO Tescdmee EMME TOME in mache #2?
sos (sn UnEnter YORE Eee eT ogence #
feathe = ine Cnpeeecceneer YOUr
ne tanpee “EME
ngiiah + athe
Tg acored “1
prine (namoy * 4
fence
otek
+ pares")
De mncar your mane + 30K 70
Emer your marks .
Enter Your marua in acsence, + &7
Shen’ Risvecored 254 ma"
input statement
Figure 9.15: using int() function along with input statemer
oe nae marke in english +7)
nee oe marke in maths +
in science
seltnee Sisecanpee "Ereee your maze
SEEDS Caoaten + mache ¢ aetence
SEIN [aane, has seored “stotal
© rane = inpurcvenver ye
english = f2oat(inputl
athe = float (input ("Ent
+ marks")
ater your nane 1 IAEK
© leer jour mnexa in engiiah
Encer your marke in maths ¢ 99
Enter Jour marke in science + 67
Shoe, how scored 244.5. MACKS.
178.5
Figure 9.16: using float() function along with input statement
Control statements in Python
There are three types of control statements in Python:
* Selection/Conditional: Python uses selection statements for decision
and branching of flow of control; that is, choosing between two or me’
alternative paths.
* Repetition/Iteration: Repetition is used for repeating a set of Python cot
multiple times in a row.
* Sequential: The Python statements execute from top to bottom in!
sequential order.
LS
Figure 9.19: Sequential
Figure 9.17: Selection Figure 9.19, g, ;
-18: Selection
132__Arlificial Intelligence
rr 5
Scanned with CamScannerction Strement ~if Statement
nm i .
1 te eke wlio? sometimes requires decigi
ns HOVE fo be taken as per the conditions Scision-making, Specific
lent
selecti ccurri :
oP PALSE con, ctatem Cvalvaies mulinig ine the execution
TRUE or FALSE as the Output. The course 4 Iple expressions, which
:“pejotements 10 execute if the output is TRUE Or FALSE determined by
erwisi
Af (conditi s =
on): » 2 You have
statement | i¢ (x ss 2): two books
[statements] print( ‘You outside of if
have *)
print (‘two
books’)
print( ‘outside
of if’)
Faure 9.20: if-else
Syntax Example Output |
© | Atlock of Python code is indicated by indenting each line of the block by the
sme amount. In above example both theprint statements are part of the if
e andiion because of both are at same level indented but not the third print
sotement.
iLelse statement: cs :
his statement executes some code if the test expression is true (non-zero) an
‘me other code if the test expression is false.
ample
¥ (condition): 1x=100 pn and x<=10@):
statement /if(a < 1000): i print(‘Grade A?)
[statements] print(‘value of x is
ies less than 1000’)
[statements] elses print(‘value of x is|8’)
more than 1000”)
else:
rint (‘Grade is
Setement P
Python Programming Language 133
Scanned with CamScannermultiple test conditions ang
Taro conditions: = 0:
if num
lo check for
; more than
a number? =)?
arr Enter a number: -34
eee Negative number
else:
print(“Positive number”)
else:
print (“Negative number”) '
if..elif..else:
This statement allows you to check #!
and execute a block of code as so
TRUE. The elif statement is optional.
he validity of multiple conditions for Try
on as one of the conditions evaluaies
Syntax: Example:
if expression1: amount = int(input(“Enter amount: “))
statement(s) if amount<5000:
elif expression2: discount = amount*®.@3
statement(s) print (“Discount given = “,discount)
elif expression3: elif amount<50@0:
statement(s) discount = amount*@.@5
else: print (“Discount given = “,discount)
statement (s) else:
discount = amount*®.10
print (“Discount given = “,discount)
134 Artificial Intelligence
Scanned with CamScannerNet = amount
Print ( “discount
Net payable amount”, Net)
Outpu
Enter amount: 5700
Discount given = 171
Net payable amount: 5871
pation - for statement
yer f : a
Joop 5 used for repeating or iterating over a sequence. There are multip|.
5 ‘e multiple
for i:
ah icti
atatypes such as list, tuple, di i
en torrie Casa a ne ow
Pa datatype object. for each element in a list and
oo =
[ @ sr x in “apple © ‘rine cach stationary ites in a stationary 1
print (x)
stationary = "pen", “pencil", “eraser")
for a in stationary:
ba prine(a)
P
P CG pen
1 pencil
7 eraser
a
Figure 9.21: for loop Figure 9.22: for loop
Tebreak statement is used to stop the loop when an exit condition is met.
# Print each stationary item in the stationary list
# Exit the loop when a is "eraser":
stationary = {"pen", “pencil”, “eraser"]
for a in stationary:
print (a)
ifa “pencil”:
break
Figure 9.23: For statement with break command
Python Programming Language @ 138
Scanned with CamScannerrange() function
The range() function is used to rep!
number of times. It returns a sequence © nS
and increments by 1 till it ends at the sp
tements for
a set of statem c ‘
oe umbers, starting from Q bya |
cified number. The uppe, Tees
Mie
excluded.
ange(2, 8);
6) for @ in range(10)+ g) for a in + 8):
fer Sep eintca) : print(a)
Ge |
2 > 2
3 -
5 4
é 5
3 6
3 7 |
LCL Figure 9.25: range() function |
© for a sn range(se, 25, 294
peine(ad }
C30
2
Me |
16
18
20
22
Figure 9.26: range() function
Sequential flow
The Python interpreter follows the sequential order of statements to give te
final desired output for the problem statement.
12) F bython program ta fied tho mquare root
# Toke the input ter the vece
nun © float Inpue("Enter & eusbers *))
100" oxponent operator is used to find tho square root
squrcot «nan #8 5
£4) function Is used te convert « nust
As used in the print staterent to o
tie data type into string date type
14d U9 OF Fore strings Cor display
Prine(rthe equate root of * + ste(naa) + * 48
str(aq.root))
Ce Enter a numbers 16
The square rest of 16.9 45 4.0
meme
Figure 9.27: use of ste() function
136 Artificial Intelligence
ne
Scanned with CamScannerFigure 9.28: Python program
(1 # Python Progzam to cor
4 conversion factor; 1
2 Taking Kiloncters. in
das = Coat (inpue(
e+ 0.621971
4 calculate nites
niles = ins +e
Prine (ens,
VEE KL Lene
ile = xilonee,
Put from the vaer
"Enter value in kilonoteras
“Kilonoters ts equal to -
[+ Enter value in kilometers: 27.5
27.5 Kiloneters is equal to 17-0877025 niles,
Figure 9.29: Python program
= float (input ("Enter tempe:
# calculate fahrenheit
f= (ce * 1.8) +32
print(f," degree Celsius is equal to “#str(t)+
( Enter temperature in Celsius: 41.8
107.24 degree Celsius is equal to 107.24 degree Fahrenheit.
Lees into niles
ers * 00621971
+ ste(mtiesy +=
19] # Python Progran to convert temperature in Celsius to Fahrenheit
# Conversion Formula, celsius + 1.8 » fahrenheit ~ 32
ture in Celsius: “))
»
miies.*)
* degree Fahrenheit.")
Figure 9.30: Python program
[12] # Python program to check if the input number is odd or even.|
‘RD number is even if division by 2 gives a remainder of 0.
If the remainder is 1, it is an odd number.
)
number = int(input("Enter a nunbe!
if (number $ 2) == 0: .
print(number, " is an even number.")
else:
print (number,
* is an odd number.")
G Enter a number: 456
456 is an even number
Figure 9.31: Python program
thon Programining Language @_137
Scanned with CamScannerFigure 9.32: Python program
eine sum of
© © ryenon program £0 PF
for a in range(ts 18, 29!
peinetad
eee reanot Ga numbers between 1 and 35 40” + ste(aun))
arti
{15} # Python program to print even numbers betwoen 0 and 15-
for & in range(0, 15, 2)+
print(a)
G
Figure 9.34: Python program
138 © Artificial Intelligence
Scanned with CamScanneroe ose mangedts
(Crate
ae
Figure 9.35: Python prog
pedugging
am
hon progr may not execute or may gene:
ammer enters @ wrong input or th rate wrong output when
7 prog! Fi
a ‘ ‘ ere is an
wpe source oe ine oe of identifying and a in the syntax of
fom a progr called debugging. Errors occurring i ig errors and bugs \
egorized as: ig in programs can be
+ Syntax errors \
+ Logical errors
+ Runtime errors
syntax Errors:
fyhon has its own rules of the programming language that determine its
gntox. The Python interpreter interprets and executes the statements only if itis
sntactically correct. In case of an error, the interpreter shows error message(s)
and stops the execution there.
for example, parentheses must be in pairs, so the expression (90 + 21) is
smtactically correct, whereas (7 + 11isnot due to absence of right parenthesis.
[20y rse5e89/3008 109
logical Errors
Algical error results in an undesired output without
cbuptly terminating the execution of the Python
Sregram. Since the program interprets successfully, it
sometimes difficult to identify these errors: They are
ne referred as semantic errors aS they occur when
"emeaning/semantics of the program is not correct.
Ce 167. 6os6sscosssees
© cseeeenrpe
34.33339333333333
Figure 9.36: Logical Error
yon Programming Lmsinse e139
Scanned with CamScannerRuntime Error re
1n of program while it is ¢
runii - mal terminatio . Key
Aruntime error causes abnor! wn starts running. tng é
It does not appear until after the progro' ae
i e division 9) i,
For example, we have a statement having th Peration +
inator entered is zero, then it wa 8]
eT
program. By mistake, if the denom
runtime error like “division by zero"
Food for thought :
lowing. Test the codes for corre
(Activity 9.1: Write Python scripts for the fol
) outputs. oe 4
1. Write a program to calculate the electricity bill. Accept the last me,
reading and current meter reading and the rate per unit from the y
's and total bill consumption for the user,
Calculate the number of unit:
Write a program to enter the name and height of the user. Convert th,
height in inches (1 Feet = 12 inches).
Write a program to swap two variable values.
Write a program to find simple interest.
Write a program to check for the correct
Write a program to display maximum and minimum of two numbers,
Write a program to find the largest of three numbers.
A company decided to give bonus of 5% to employee if his/her year of
service is more than 5 years. Write a program to ask the user for ther
salary and year of service and print the net bonus amount.
9. A school has the following rules for the grading system. Write a prograt
to ask the user to enter marks and print the corresponding grade as per
the following table.
+ Below 25 - F
25 to 45-E
45 to 50-D
50 to 60-C
60 to 80 -B
Above 80 - A
nN
5
>
5
§
5
‘
5
password.
oe
140. Artificial Intelligence
Scanned with CamScannerrite a Program to pring
wi 1 the disee :
10. giscount is based on the Following Scount in Rupe = .
Seti, A olen, 25
Sales a
«ps. 5000 Discount
ps, 5000 to Rs. 10000 5% Sour
8%
ve Rs. 10000 a
Abo 10%
i int= Sales * Di y
[Discou Discount, ) 1100}, TotalAmount = 1
= Sales - Discount}
joints Remember
» python is a platform independent programm,
both scientific and non-scientific purposes
» Python is case-sensitive langua
source programming language.
. Leelee “ ‘wo a Interactive mode or script mode.
+ The in Python allows the i oH
datements and display the output interpreter to execute individual
+ The script mode is used to create and edit Python programs. Program i
of instructions to perform any task. q pe a ce
+ Keywords are the reserved words and have special meaning for interpreter.
Therefore, these cannot be used for any other purpose.
An identifier is a name given to a variable, object, class, function, and so on, to
differentiate it from one another.
* Comments are the remarks that are added for the programmer to understand the
code later and are not executed by the interpreter.
* Single line comment and multiple line comments are the two types of comments
that can be used in Python. a
* Acomment starts with ‘#’ outside a quoted string and ends at the end of a line.
Comments are not part of statement. They may occur on the line by themselves or
at the end of the statement. They are not ‘executed by interpreter. :
hich identifies the type of value an object can
* Datatype declares type of an object w! i
hold and the kind of operations to be performed on thet oe
* Numbers in Python can be stored in vane. ae os
Point (decimal numbers) and Complex numbers. re different types of data
* Numbers, None, Sequence (String, List, and Tuple) a
YYpes in Python.
19 language which can be used for
‘ge with very vast library. It is free and an open
r, Boolean, floating
python Programming Language
P
ae oe
Scanned with CamScanner|. Multiple Choice Questions:
gome action ON OPEFANES, Operar,
i
ich performs
pols which perton ‘on it.
+ Operators are special sym
hold the value and operators perform
+ Arithmetic operators. Relations! Ol
categories of operators.
= Expression is a Python state
operands. a
+ Each and every Pro’ uires three stag
+ The input is taken ff
program.
+ Processing stat
«The output is the result whic!
statement. -
« Anerror in a program is called 2 DUS
. ae error, fogteal werror and runtime errors OTe the different categories of errors
atement(s) in a cOMPOUNA stateme
. i sed to re} resent the Python st Nt i;
Incentaton ie weed pound statement must PS iiglented by @ Set number
od Logical OPCFALOTS ein,
nt
nt which iS 2 combination of OPerators ang
mer
put ~ Process ~ Output
fatement oF declared Within the
a
ctions used after the input given,
s and fun
jements are the formulas BT ocessing statements Using prin)
nis displayed
4g removing this error is called debugging
spaces (usually four) 7 R
_SSHSE 0 ning of ine 6 pat of ndemuaon, SEWN NS
significant.
eto syntax eros.
= Wrong indentation can give ris
1. One of the following is not true for a variable name
a. Spaces are allowed.
b. It begins with a lowercase alphabet.
c. Letters, numbers and (_) underscore characters are allowed.
d. Special characters like @, *, % are allowed.
2. The file extension for a Python program is
a. py b. .pyt
c ph d. .python
3. The function used to convert a string of digits into an integer.
a. convert() b. int)
c. string() d.str()
Artificial Intelligence
Scanned with CamScannere
p. Double Quotes (” ¥)
qe Tiple quotes ("*« «4
g, Any of them
. all control flow statements in
Semicolon (; )
b. Hash sign ( #)
¢. Colon (:)
g, Full Stop (.)
his statement checks if a i:
é * Paes = ‘hon equal to b,
b. ifa<=b:
c ifa< ==b:
d. ifa>=
7, Number of white-spaces used for indentation:
a 4
b. 5
« 3
d. 6
8. A process where a set of instructions are repeated in a sequence for a
number of times until a condition is met.
Python end with:
a. Looping
b. Iteration
¢. Sequential
d. Selection
9. The function range(4) will return a sequence:.
o. 1,2,3,4
b. 1,2,3
« 0,1,2,3
d. 0,1, 2,3,4
10. The function range(10, 0, -5) will return a eu
b.-5
«10
“5 "0 d.0510
Pytlion Programming Language 8
Scanned with CamScanner
143RWNH
ONAD
ve oxomPie riable i
ava in a Python
What is a variable? Gi
Mention the important pol
What is input() functio
Which of the following are
Sum_total, $Name,
What is the difference betw
How is if..else statement ex’
Why is indentation importa
What will be the output o
n2 Give Sy!
invali
f the foll
ile creating
nd an example.
12rupees
float,
and == operators?
een =
ecuted?
nt while using if statements.
lowing statements?
Scanned with CamScanner
Prog,a inis chapter, we will discuss the
Fatowing tOPICS
ee nition and purpose of a list
ntroduction to Python
wogramming: process of writing
Program, running it, and print
statements
. simple problem statements:
finding the maximum, minimum,
mean, linear search on list of numbers,
gndcounting the frequency of elements
ina list
+ Questions and Answers
At the ena
be able to:
Objectives
of this chapter, you should | |
Create simple programs using |
lists,
Recognize the use of a data |!
structure list t i
0 store piec \
information. oe
‘Traverse a list and perform various |,
list operations. |
Differentiate between various list |
methods and built-in functions.
efore declaring a variable/identifier in our program, we should |
understand the use of it. In the previous chapter, we saw how the data
type plays a very important role in creating the program. Different data
jgesare used in the program as per the requirement of the code. Now, in this
copier, we will understand theconcept of one of fl
jneknown as a list in Python.
htroduction to a List in Python
‘lstin Python is an ordered collection of one or
“a fypes,
“We have already studied about the different
1 String, tuple, or another list.
he collections of the data
more elements of different
data types in python as integer,
ee
Scanned with CamScannerThe various Pro} erties of Lists
cr that is,onY element IP
« Lists are mutable,
Jements together.
creation. capes
« Lists are useful to store multiple YP © sare brackets.
«Elements in the list are enc!
* Each element in a list
* Each element in the
location.
+ The location of the very first element
by 1, and so on-
* The last element in
* To get the first element,
7 arated by 4 oe
is sep referenced with the help of its ing
Sy
list can be
in the list starts from 0, Second oy,
Tait Ts the list oF 5 integer elements
tact
tact?
Ge t20, 12, 25, 29 201
List2 is the list of 4 ety names (which Is of type string)
tyyderabad', ‘cateutea"l
to) tase = [rpetns, "Bombay's
bast?
syyderabad’, ‘Caheutta'l
Ge Utena, "Beaker!
List3 is the list of 3 floating point numbers
ft) base = eg
tase3
Ge 120.53, 12,538, 198-41
ists
Listé is the list of 4 elements of mixed datatypes - integer, floating point number, string 2 od ati
12, $27, Mew DeInA HT
Ly mista = (59, *todia!
tasté
{10, tindiat, 239.22, 12, 4.7,
&
tNew Dethit})
Figure10.1: Scree
.1: Screenshot of diff i
oe
146 Artificial Intelligence
ot
Scanned with CamScannerFig 10.2: Se
: Screenshot of acce:
lists created in colob research ocolecone
-google.com
fe slicing operation can also be used
to ext
ed to access a num xtract el i
mepecified location ae elements together Renae ies Te list Ween
eal index location sateen) atte len Wee
i 1 s from where to een the index locations
ond ihen,the next index location means eee followed by a colon,
an that. 7
1g elements from lists
accessin
google.com
Figure 10.3: Screenshot of
colab.researc!
using the slice operation created in
Python List @_147
Scanned with CamScanneri " from the beginn
i i P we ments TT ginnin
Traversing a List in ada all the clemocation number as Bo
Traversing list means 0, She nde Monge, the fs! MUmEe sechg
1S, .
the last element. To do
a SP Rtg,
speci + specifies that the list wit,
the previous example. When you SP! umber SP
i is not specif
i bees hird number is not spe
the starting index location ah Eee pen if the ti do spat
fetched one less than the sec faut i token 8 1. Ot,
ne FF mbar sce’ Teh ext element will tet
th i ifie ithe n !
the third number is specified of and then
fetching the list from a
location using the step statemen while loop. The concept ofthe
joc list using a for loop or ve euse the for loop ieee
You can ee a fe using evious Phapter.
loop is already tava!
in Figure 10.
elements from the list as shown in Figure 10-4)
Figure10.4: Screenshot of accessing elements from lists
Using the for loop using colab.research.google.com
Figure 10.5: Use of while loop
148 Artificial Intelligence
Scanned with CamScanner: elements f; ;
pile ii Tom the list ag shown
gut? built-in functions that can be use, rm vad
a Moython built-in functions are those which, are alread oes OPerations
sta specific Purpose and syntax, Teady defined with the
et
i) number of elements in the list. P< "@4 list, that is, the i
len(list_name)
Example:
F of elenents in List fen (taseay)
arker of elenents in List: ¢
Figure 10.6: len() function
It creates an empty list if no argument is passed and
creates a list if a sequence is Passed as an argument.
Syntax:
list)
Example:
Eisea=lise() #creates an expey lise
using sequence
Figure 10.7: list () function
ist @ 149
Python
Scanned with CamScannerappend()
insert()
150
RB Artic Inetigence
ne end of the list. The ele
t! 7
san clement nt with the function.
nar
Ment ig
rt add
passed as @
Syntax:
(item)
List_name.append
Example:
Figure 10.8: append() function
It is used to add an element at a particular index in the
list. It uses two arguments. The first one is the index
location where the element has to be added and the
second argument is the number which is to be added,
Syntax:
List_name.insert(index, element)
Example:
22, 87]
10, 22, 87)
Figure 10.9: insert() function
Scanned with CamScanner