Conditional Statements in Python, Lecture notes of Computer science

These notes will help you to understand how to use conditions in Python.

Typology: Lecture notes

2018/2019

Available from 02/10/2023

probalkar
probalkar 🇮🇳

7 documents

1 / 25

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
elasSmAte
Dte3/8/19
Page
CONDITIONALAND IERATVE
STATEMENTS
Generallyaprogtonexeces Hs Stadements toloeinninA
Ho end AlAhe progsansS cannotbe writeninSamepodtetn.
To pedor heirmanipulozivemifaclesorogramneedsbols.
heprogfem needsdoals dor pertosninqepeatadiveactian
Qnd candldhonadecisionnaking
lo
adttaintheososamin-
reuirementsPthonfrovidestolswhich areknawnas
Oroscm Cotrolstatements.
verProarainglanguagesuppacdsthsee_controlsttuctures
ADSeguendtial
Conddional Selection
3erdionLooping
Statement Elow Coitrol
napsoqramstcdemens
'mayoe etther sequeho execdedether
Seqendially
Or conchfion.ally
derativel,
Sequence
(he
sequence
conSfruei
means the Stalemeds oue being.
execuhed Sequenhially
lharepresenl
edehaultdaw o
shode
ment i.e.
norng Haw otcosol
in aplofam.tach
Stade
mend Aollo
ws henexl
Stcdernent 1Stademert n
Statemer 2
Storemext3
pf3
pf4
pf5
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Conditional Statements in Python and more Lecture notes Computer science in PDF only on Docsity!

elasSmAte

Dte3/8/

Page

CONDITIONAL

AND

IERATVE

STATE

MENTS

Generallyaprogton

execes

Hs Stade

ments

toloeinninA

Ho end AlAhe progsansS cannotbe writeninSamepodtetn.

To pedor heirmanipulozivemifaclesorogramneedsbols.

heprogfem needsdoals dor pertosninqepeatadiveactian

Qnd

candldhona

decisionnaking

lo

adttaintheososamin-

reuirementsPthonfrovidestolswhich areknawnas

Oroscm Cotrolstatements.

verProarainglanguagesuppacdsthsee_controlsttuctures

ADSeguendtial

Conddional

Selection

3

erdion

Looping

Statement Elow Coitrol

n

apsoqramstcdemens

'mayoe etther

sequeho execdedether

Seqendially

Or

conchfion.ally

derativel,

Sequence

(he sequence

conSfruei

means the Stalemeds oue being.

execuhed

Sequenhially

lharepresenl

e dehault

daw o

shode

ment i.e.

norng

Haw ot

cosol

in a plo fam.

tach

Stade mend Aollo ws he

nexl

Stcdernent

1

Stademert

n

Statemer 2

Storemext 3

elasSMAte

Date

Page

2Selection

Ihe

selectionConstructmeans heexecutionot stotements

dependingupan

a

conditiontest.a_conditionevclucdesb

Hrueo course

ot

achanistollowedathetwise anctherccurseci

actionistallowed.This pMAraminqconstuciisalsokoown 4

dedsianconsttuctasithelpsinmakingdecisionaloaut

whidh setot stotementsarenbe executed

1s

Condithon?

LSet ot stadenm.ent/ Setor

studenueutcs)

3Herotionor

Looping

he terccion

construetmeans

repecdttianot set

atstotenmeats

dependinganc Codithondest.illthehoneaCanditianis

troetrve

50me

set o

shdements ore repeahed

againand

again

QS Saam as a Condition becaes tals.ehe

repeaitiangbps

and dheconmol is tronskarced

thestate

nentstollauihg

the

iterodion

elasSmAte

Date

Page

statement..

a

intCinput

(Enter

a

number))

b

inpuCEntec Aame?)

prind(Hello)

CompaundStade naent

A

compound

state

ment reptesents aroupof stadements

executedasunitA compaund statemen endswth calun,

underwhich multiple

stademehs

areexecuted

ba

Compaund

Stetemen Header

Statement

Stcdement

3 Empty Statermen

lhesimpleststodema iscalledtheenmpty stdemeht,it.a

stodementwkichdoesnathingwhichalsameans itreptesents

nullopercdian.Hcanbeplementedbycihingpass.

ProgomLogicDevelojpmem

Tools

Behormdevelopin8acomputer progrannorogivesolution

ot

problem in

terms

oproeramhe

usershoud readand

analusedhe given pralalemarddecidealoutbasicsulataks

neaded tosclvedhe prolulenandotderottheseSu-rtasks

There sevatiousprayrologiedeveloamen nals,Someo

the

ase-

Agorithm-

An algorth

s astep-lay-

Step

pracedute

osoluehe

problem tisaSetototdered ond Hriteshepsasalethe

elasSMAte

Date

Page

8ren

proble.m.

Apart

ram

algarithm

there

areather

balS

Iik.e

pseudo

co

de,Howcharh,

decisionree..

flowchart

BHowchcs

isagraphicareptesent.ationo anadgorithm.tA

shows d:lerentsub-tasksth dilerentsumbls.

Start/ End

Inputl

Output

Statement

Diamancd

2

Sulbtasks

flo

ot

program

QDrawa How chor toindoutoreo otcircleAsowrite

Hhe

ses

pecive

algosthloe aretne

Hawchcs

diawn.

Algorithm

1Start

nput

radivs

3

Area

radiusxT

4

PrintArea

Start

Input

A-3.1A159rr

End

pint A

End

elasSmAte

Date

Page

3)Pseudo

code

His

an

intocma

way

ot

olescribing

the

steps

ota

profam's

Salutionwithout

using any Srictprogfaming

gug ntax

ar

undeclyingtechnaloa

considerodian.

Eg-

Ficst

input

anno.

adculate

areaas nos.Squae mutipliedb Pi

Displayarea

ib

nput

marks ina

sulaj.ech

morkS Qre more

than 33,

then

displo passed'L

else

display

hiled

Decision Tree

Decisian keeae ways ot presening-

rulesin

hierrchica

and

sequentia sttuchurewhere loasedon hiemrchyo tole

sertainoutcomesarestedicted..

Percentage

Percentae

26ol lou

got distinction

Percentage

250 You a

tirst

class

Petcentage

31

ou

got second class

You

sailec |ou

gad

pa8sing maksI

elasSMAtee

Date

Page

atade meds

in

Phon

Ihe

itstademeni is a

cattolled

shucture whichckecks the

condition

and

displaysthe

setot stete mets uhich sedisiesthe

condiion.

lhere

ase

voriaus

Alavour ot i-

f

else

A)Nestecdit

Fythonuppertsdeshingotcoalitianswiththe luelpo itecmtae

Simplei

displa&

thellack

stademerds anlyitthe conditionis

ue

Write a Pidhoncosle nieh iyoutsa nuher andcheck wether itis

positiveo1not

int linputEniera no.-

nzoi

print(Na

is

posihve?)

2Q nputa hauberand checkhethesisdwadiitpositive

Mwmber

or not.

n intCinput

C Enter

a ns2)

n79and

n<iOO

priatdlaiswo diatpostiveaa)

3QWrde aPihanCade uichinpuisa Jaialaerwheikertis2add

or

noi._

AQwridea

Pdhon

cale

wllch

inputs

maksata studentina

Sulajec check

whetherfhe

shudet passeaornai Ssumin

mcx matks

00

elasSMAte

Date

Page

QWrde aPyihonccde whichinputstemperatureotalercheck

shetherihas

reachedheatngpoin

or_net.

nE int(input(Eterdemperahure2)

nE=iO

print(Waterhasrechedbailingrheactingpoin?)

S.Wrhe a Pthancode aishiapuisprincipleohaltimedd

coleulat

diapleintesestprincipleamauutis

haore

fhan

2500o,herateo inderestis.

2 :intLinpuiEntertioie22)

Q5606naiulinput(Enterprinciple)

Gs p=nt 25000

G.S

Sipxr

t

100

print

(si)

p-

intCinput

(Enler

principle

L:intinputEnter

time)

_p

25000_

6i

p r&t100o

prin

(si)

2Q.nput

a chocacter

check

ohetheritisvowel

orhal

n:

raw-input

CEnter

acharacter)

i n:a,e,,0, 1

ifn-a?or ne or nio ne'oor nw

printCharacter

is

a vowel')

elasSMAte

Date

Page

2

elsestatengent

lhisdotrm oit_stotemenmHestsa condiitionanditthe

CAnolitioneveluates o trueitcarriesout stodtements

indeuted lbelow

it

And the condtionevaucdesto Jalseit carriesout

stare mets

irdenteolbelow

else

condiion)

set

or

stadementcs)

else

set ot

stotementCs)

n: int

Cinput(

Entera no2)

in°/o2=

printNoisEven")

else:

printnoisddd?)

Write a

Pthon code

whichinpuis

principleand

dime

priuciple

amount is

more

than 2000o theateor ideres

pplicahle

lapplicalule iso. cherwise 4 CalculodctheSimple interei

pE intCinputEvter principle amount))

t intCinput(Ené ine')

i

p200oo:

Si

pkrxt/AoO

print

Csi)

alassMAte

Date

Page

ptind

C

is a

vowel

else

ptind

1

is

aconsonen)

Qnputage o apersch.Chechdhe pese iseligblevater

ornot

age npehEterageintlinputCEnterage?))

itage

=

print(Personiseliibletovote)

else

printPersonisna eligibleto

vote)

Emer a

year hech whethes itis

leapyearor

nat

days

int

Chnpu

Enierna. ot days

in tebruary

Macth)

year:int Cinput Enterayear )

year

4==0:

printHs

aXeapyenr")

else

printlHs

nota

leap

ear)

OWridea

Pthon

codewhich

inputs salaryot a Sales person and

sales

oa.out.Eind

out

he

total

Selaryo asales person he

hos Made salesQove Ks

15000,Then he

qetsa

e.mmissian

io"/else

Commission

is27aothe sales maol

Salary

in

CinputCEitersalary»

Sales int

Cinput(Ener8ales

amount'))

2

iSales>

CESoles

10/1oo

else

CE

Soles

elassMAtee

Date

Page.

tata

CtSalary

printTata

salary

is,selee total)

Qnput dour number. Findlasgesh amonj1hem.

a

int

Cinpu Enter Ast na.

b:intCinputEnter 2nd no.)

Eintinput Enter3rdno.'

deintCinputEnterthna.

i

azb:

else

od

else

L:L

else

LEl2-

printLargest

na.

is,1)

put dnnuaers,dhe stnunmoer slargerAhanseco nunber

hen wap

the bath

nunnoess atherwise

psintculae

o the Smaller

number

2Q

intCinputl

Enter

istno.

b ntCihput(Enter2d ao)

iazo:

elassmate

Date

Page

printH's_an acute angle)

elit

anle 90

print(Rsan olatuse

angle")

elit angle

90

printf's aright

angle").

Write a Pdhon code whichinputs hreene.Eid lesgestamang

Hhe

a int(input(Enteristno.2»

b:intlinputEnter2ndno.

cEintlinput('Enter3rdna)

iab and azc

print(a,islargest)

elit b2a and o>c

pcint(b,is

largesi)

else

prid(islarqest)

Qhputamorth na.leitea pyhoncodewhichprintscoLespanding

math

ncme and

no oi dons

itcorntains.

mzintCinput(Entec

nonthno.

im=

printIts

danuarywith

31 days')

elf

m=-

prinlHs

Eebrury

with

28 days)

elmE=

3

printCls

Marchwth

31 das)

elitelit

m==

print(ltsAprilwth 30 days

elitm 5

peint.CHsMaywith 3 days)

elassMAte

Date

Page

elit== 6

print(HsJunewth 30 daus)

eli

==

printHs duly

wth

31 days)

eli-

prittsAsustwth 31 days)

eli

orintCItsSeptemlaer

wth

30 days)

elit

A

print('HsOcdober with 31 days)

eli==

printtsNovémber wth 30 days')

elit

-=

print(hsDecember with 31 day)

Q nput dau

noprint

coresp.anclingday

name

d int

(input Enter

da na))

d=

ptinttsMonday

eli

d==

printHsTuesday

elif d=

prins

Wednesday)

elif d= 4

priTs

Thursdau

elit

de=

printHs Eriday

lelit d=o

printClts

Sturdoy)

elit d

printCHs Sunda

lassate

Dete

Page

tchsiaor ch'eorchs ch zdor chz= o he-a

ch:crcha:1o ch= 0 a cha:V

print(isa voel)

elich>:B and ch 2ach2:L and chk: _

priCHisoconsanant)

lelifcho and dhx-o

primCisa

dgit

elce

prim H iso special

charader)

QWi ea Puthon code

whichinputs

number otcalls

ok

custae

usinghe servicesc

XY

telecaa

CCmpany heLtol Lillx

o nondih

is

celculated os

perthe

tollatwing slab

Numbe o Cells

Rte

Upto 100

01 to 3oo

O

301 o 550

55 o A

5O050/callin exess o

15+015Lcallin

exsess 300 cals

isO+A/callin

excess d 551cals

AO

200t125lcallinexcessc 000 ccls

Renta phone chceges isBs 8o dorall costomer

no

intinpulCEnler

ngeo

calls)

it

nac

E

ail 0

classmate

Date

Page.

eli noci00and

noc

300

bill= 50+0SO* Cnot-1O0)

elil

noc an ns K: 550

oill:

15+075*noc300)

elit noc2550ánd noc IO

laill150+1*no551)ON2A

else

bill:200+12SK noc - 1O00)

b: ill

80 hetoll

print

(h)

Qnputbasicsalaryoian eraployae Calcukdetheaoss salary

receivedbyaoiap.anyasperthadallosingslcla

Sasic Salas

DA HRA PE

3:

Updo

G

GSo1oL0So

28

S2/

43

LO

501-b

I8Soo

125

AR

13

bsE itCinput EnteroasicSolary

pasicsbs+bs28/460+lasoo0bs-4.5toe

hs=oSo

asks:losbs28/10o)Hlas2/1o-osA26/1doaa