[go: up one dir, main page]

0% found this document useful (0 votes)
33 views18 pages

G6 Computers Ch6 Python-2

This document outlines Unit 6 of a Python programming curriculum for Grade 5, focusing on conditional statements and loops. It covers essential concepts such as IF-ELIF-ELSE statements, FOR and WHILE loops, and user input handling, along with examples and syntax. The unit aims to help students understand efficient programming and simulate real-world problems using Python.

Uploaded by

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

G6 Computers Ch6 Python-2

This document outlines Unit 6 of a Python programming curriculum for Grade 5, focusing on conditional statements and loops. It covers essential concepts such as IF-ELIF-ELSE statements, FOR and WHILE loops, and user input handling, along with examples and syntax. The unit aims to help students understand efficient programming and simulate real-world problems using Python.

Uploaded by

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

SCHO0LS

Unit 6:Python -2

Overview:
unit continues on the basic
to build
This Python
IF-ELIF-ELSE, concepts
about FOR and WHILE introduced in
Grade 5.
learn loops. Students will
have been provided using Programming solutions to
problems conditional and loop constructs. simple
unit, students are numerical
this exp0sed
Through to various
constructs of
program solutions to problems.
a
write programminglanguageand

.
Essential Questions:
What makes a program efficient?
How can programs simulatereal
world problems and solutions2

Enduring understanding:
Students will understand that:
An program uses less memory,
efficient
considers all possible user input and takes care of
all foreseeableerrors that could take place while
the program runs.
• A real world problem can be simulated by inputting necessary data and quantifying the
problem.Object oriented programming languages have many features that allow us to
model real world situations in programming terms.

Content:

• Recap of Python Fundamentals Simple IF in Python

• IF-ELSEStatement • IF-ELIF-ELSE Block

• Built in functionsin Python • FOR loop in Python

• WHILE loop in Python • Break statement

Essential
Vocabulary:
Punctuators, While,
Variables, Operators,
Coding, IDLE, Syntax, Keywords, For, ldentifiers,
Boolean, String, User Input,
Separators, Arithmetic, Break, Float, Integer,
Relational, Data types,
Conditional, Sequential, Function, Builtin,Iterative, List, Range

59
EKYA
SCHOOLS

Unit 6 -PYTHON
A. Quick Recap
We Python by double clicking on the Python shortcut icon on the
start
desktop or on the taskha.
You can use Cortanato search for IDLE and open it.
also

Python IDLE stands for Integrated Development and Learning


Environment. Python IDLF is
interactive mode ofPython where we type programn commands one line (or one block of codel o
time. This line of code getsexecuted instantly and the output is displayed on the IDLE.

A.1 Python IDLE:

Python 68 Shell
Fie Et Shelbug Opthens Windew Help

ype heip "copight, *credit* o 1icense or Or nora.t icn.

Print function in Python 3 version performs the same task as the Python print statement in
2.7. It
helps us display things. If you want to print some text like the example given below,
you put the text
within quotes. Python allows both single as well as double quotes for inputting text.

If you want to print a numeric value, then do not


use quotes. >>>print (5+ 5)
10

HeltoWorid
>>>in(5."r tgy ater)
5is my lucky number

SyntaxError: EOL whiie scanning string iteral

The first print function causes 10to be Since it


printed. is a number, we do not use quotes
while printing it.

The second print function prints text. So,we need to use


quotes.
The third print function uses a combination of number and text. We use a comma to separate
numbers and text here.

The fourth print function


uses double quotes atthe beginning of text and
single quotes at tie
end. This causes Python to return an error. You can see
that an error is returned by Pytno
(line in red). Let us correct this error by
matching the single quote at the end with one at tne
beginning.

60
EXYA
SCHOOLS
CMR
A.2 ScriptMode in Python:

A Script in Python is a
setof code that is saved
A script is also known
as a file. The extension for a
as a module or a program. To Python script file is .py.
1. Click on File in IDLE. create a new
script/program/module in Python:
2. Click on New File.

Python3.68She
File Edit Shell Debug Options Window
New File

Open... Ctrl+O
: Help

3c6b436a57, Dec 24 20

Open Module... Alt+M "credits" ox "1cense


Recent Files
Module Browser Alt+C
Path Browser

Save Ctri+S

Save As.. Ctrh+ Shit+S


Save Copy As.. At+Shift+S

Print Window Cut+p

Ciose
Exit

The New File that opens is a text editor and looks like this:

Menu Options

61
EKYA
SCHOOLS

CMR
gebeyod

We can execute a program by following these steps:


1. Click on Run and select Run Module.

Untitled

File Edit Format Run Options Window Help


roara to add 1S and 30
print (The sum of 15 and 30 is', 15+30)

2. You will see a dialog box open that asks you to save your program first. Give
a suitable na
for the program and save it. In Windows, the default location is the Python folder

Save Before Run or Check

Source Must Be Saved


OK to Save?

OK Cancel

UntitedR

Save As

() s « Programs Python Python36

Organise New older

Favourites Nne
ate modified
Type
Desktog DLS
Downlcads 2-01-210
Recent places
inciude

Lit

Homegroup bs -0-20SNOS
Scripts
This PC
tct

Desktop Tools
2-01-2019 90S
Documents 02-01-2019 09:05 Fite foier

Downloads
Music

File nane: gr
first
Save as type: Python files

Hide Folders

Save Cancel

62
EKYA
SCHOOLS
CMR (go tseyond
3. IDLE pops up
with the output:

sTART : :/Use/USER/ AppData/Local/ Programa/


Python/ Python36/ gr5
fizstPY
Every time we run a module, the Python shell (IDLE)
s restarted.
A.3 Arithmetic
operators in Python:
Arithmetic operators are used for numerical
calculations.
A+ B Addition operation

A - B
Subtraction operation

A *B Asterisk is used to denotethe


multiplication operation
A/B Forward slash is used to
denote division operation.
Gives the quotient when A is
divided by B.

Division when A and B are integers:


When we have 2integers,then the answer for
division is also an integer (in Python 2.7). Ex: 5/2
gives 2 instead of 2.5. 10/3 gives 3 instead of 3.3333.
If any of the variables is float, then the answer is in float. Ex: 5.0/2 gives 2.5.

A %B % operator is known as the modulo operator and gives the remainderwhen A is


divided by
B.
A.4 Relational Operators:

Relational operators areused when we need to compare two quantities.

A>B Checks if Ais greater than B

A<B Checks if A is less than B

A== B Checks if A is equal to B. == operator is different from = operator. = is used for


assigning avalue to a variable. == is used for checking 2 values are equal.
if

A >= B Checks if A is greater than or equal to B

A <= B Checks if A is less than or equal to B

A <> B Checks ifA is not equal to B. There is no difference between <> and !=.

A != B

63
EKYA
SCHOOLS

A.5 User Input in Python:

We use the input( )


to accept user value
function in Python 3. This has the same
raw_input) functionality as
InPython 2.7. Observe the example given below:

#Program to display name and age of user


=
name input('Enter your name )
age = input('Enter your age)
print ("Your name is', name)
print(Your age is',age)

Output seen in IDLE:

Enter your name Ria


Enter yOur age 11
Yor nanme is Ria

input) accepts any value given by the user and assigns it to the
variable on the left hand side. The
text that appears inside the input() is the prompt given to the user. If
yoU want to ask the user to
input his name, then the prompt can be
'Enter your name.

Note:input)accepts any input given by the user as string


(text) value. But numbers are not text. If

we want to accept numbers,we need to use an


additional function outside the input).

If the user has to input an integer, we use int) which encloses input(). If the user has to input
decimal fractions, we use float().

#Program to add two integers


=
n1 int(input('Enter first nuber )
=
n2 int(input'Entersecond number )
sn1 +n2
print (Sumof entered numbers is', s)

Note: A comma separator print function


in
adds space automatically in output. In input), we
a
need to putan extra space when typing our prompt so that there is a space seen
when after the prompl
it appears on IDLE.

B. IF Statements in Python
Ifstatement checks a
if condition is true. We have already seen how
conditions can be
checked in the Algorithmsand
Flowchartsunit. When a condition is true, one branch of the
program gets executed.Otherwise,
anotherbranch of the program gets
statements form a block of statements.(A executed. In Python, IT
block is a set of statements
which are executed as
a unit.)
EKYA
SCHOOLS
CMR
B.1 Simple IF Statement
Syntax for asimple IF statement:
In this case, a condition is tested. If it is true, then a
if <condition to be tested>: code block is executed.
<statementsto be executed>

Notice that the statements to be


executed are indented.
statementswhen Python autormatically indents
it reads the
colon separator. Colon
separator indicates the beginning
block. of a code

Usingsimple IF statement:
The program given below checks
the integer entered
if
is positive. We will get an output only for
positive integers.

#Program to check if a number is positive


a int(input(Enter an integer))
a>0:#check if a is positive
print (a,'is positive')

Output forthe program:

Enter an integer 9
9is positive

Enter an integar-5

But wouldn't it be more informative if we had an output when the entered number is not positive? We need
an IF-ELSE block in order to achievethis.

B.2 IF-ELSEStatement

Syntaxfor IF-ELSEStatement:
if <condition to be tested>:
<statementsto be executed if condition is true>

else:

<statements to be executed if condition is not true>

65
EKYA
SCHOOLS
CMR

Using IF-ELSEStatement:
Let us add the ELSE clause in our program to find an integer
if is positive. If it is not positive ue
display an output that says the number is not
positive.

#Program to check if a number is p0sitive


a int(input(Enter an integer ))
ifa> 0: #check if a is positive

print (a, is positive')


else:
print (a,'is negative')

Output for this program:

Enter an integer 6
S is positive

Enter an integer-6
-6 is negative

B.3 IF-ELIF-ELSE Statement in Python

If we want to test the truth of a


condition, we can use IF or IF-ELSE statements. But,
what we if

have multiple conditions that need to be tested? One


example of such a scenario is when we
check the marks obtained by a student and allot a
grade.
Look at the table given below:

Marks Grade

Marks < 35 F

35 <= Marks < 50

50<= Marks <75 B


75 <= Marks <= 100 A

When the marks lie between a particular range, a


corresponding grade will be given. This requiles
not just one IF statement, but multiple
statements. This type of IF statements are
Concatenated IF statements. known ds

Syntax for IF-ELIF-ELSE Block:


if <condition1>:

<statements>

6
EKYA
SCHOOLS
CMR
elif <condition2>:
<statements>

elif <condition3>:
<statements>

else:
<statements>

Example 1:Program to allot grade


based on marks given by user.
#Program that outputs grade
name =input('Enter your name )
based on marks input

m= float(input(Enter your marks')


print() #eavea line before starting output

mprint(Name",

> 75 a9
print(Grade:
name)

<
A)#Assign
100: #arc cCperator
gradeA
hecks fo both inmts sirssaneosiy

elif m >= 50:


print( Grade: B')#Assign grade B

elif m >=35:
print(Grade: C)#Assign grade C

eise:
print(Grade: FAssign gradeF

Output:

Enter your name Ria


Enter your marks 77

Name: Ria
Grade: A

zz
Enter your name Gaurav
REST

Enter your marks 35

Name: Gaurav
Grade: C

67
EKYA
SCHO0LS

CMR

Points to

and
ponder :
operator ensures that marks are in the range 75 to 100. It is a logical
operator. There
are three Logical operators in Python: not, and, or. When we want to check if
conditions are simultaneously true, we use and. When we want to check if any multiple
one of the
Conditions is true out of many, we use or.
o The upper limitof marks is not checked in the elif statements.Why do you think we e.
not check it?
o What happens if a user inputs a negative number? How can we modify the program such
that theuser gets amessage Invalid input' if negative numbers are input.

Example 2:Accept a number and check if it is positive, negative or neutral.

n int(input(Enter

print (n, is negative')


an integer )
ifn>0:
print (n, spositive')

print(n, isneutral)

Output:

Enter an integer 4
4 is positive

0 is neutrai

-9 isnegative

C. Builtin Functions In Python

A function is a routine or a procedurein programming.


It accepts some
input, modifies the inpul a
returns an output. Examples of Python
functions you have seen before include:
etc. These are known as input0), float). Iniy
Built-in functions since they already exist
in Python and
created by anyone. The input have not be
given to a function is
known as an argument. The
function is known as its return output givell by
value.

68
EKYA
SCHO0LS

Let us take a look at some importantbuiltin


compare values of functions in
Pvthon: (AIthese
different data types but this functions can be used
aspect is beyond the to
scope of this unit.)
Name
Description
Example
max( x, y, Z, .. ) It
the largest
returns
of its

arguments. >>> max(12,-9,100)


100

min( x, y, z, ..) It returns the smallest of


its

arguments. >>> nin(5, 0, 2)

len (s) It returns the


>>>len(red rose')
length of a 8
Python string
>>> len([1,2,3,4])
or a list.
4

range (start, stop, This is very useful to generate


step) sequences of numbers. range) in >> range(5)

|
Python 3 returns an iterable
object.What this means is that it
range(0, 5)
holds a set of numbers that we >>> list(range(5)
willtypically use in loops. How do
we know what these numbers 0,1,2,3. 4.
are? |>>>list(range(2,20,2)
As seen in the output, we cannot

really see the numbers, but only 2,4,6,8, 10,12,14,16, 18]


what we have givenas input. Why is 20 not
In order to see the numbers stored part of the list?

in the created iterable object, we The upper limit is excluded


can use list(). while generating the iterable.

>>> list(range(10,3))
A list in Python is a series of

values, which are separated by


comma and placed inside square
brackets. Each of these values is
Why do we get an empty list
known as an element.
here?
Parameters in range()
Python assumes that starting
Start indicates the starting value

69
EKYA
SCHOO.S

of the number in the iterable. value is

Stop value indicates the ending 10 and stop value is 3.


Step size
value in the list. is 1,
However, in Python the end value that means by incrementing
is excluded from the iterable. 1 from
Step value indicates increment / 10, Python should reach 3.

decrement size from the first Sincethat


number. is never possible, it returns an
If we do not give the start value, empty
Python assumes to be 0. it list.

If we do not give the step size,

Python assumes to be 1. it
>>>list(range(10,3,-1)
If two arguments are given,

Python will assume they are the [10, 9, 8,7, 6,5,4]


startand stop values, not stop
and step values.
A negative step size means,
Python
keeps decrementing 1 from
10to
arrive at 3. Remember, the stop

value
will not be included in the
list.

round(x [)
n] This function returns a float value
by rounding off a value upto n
>>> rond(5.67,1)
digits.
>>> round(5.6777, 2)

C.Loops in Python

A loop the programmer's way of telling the


is
computer to do something and keep doing l
something changes. If we know the number of times dn
a block of instructions has to be executeu, w
use the FOR loop. If we do not know how
many times a specific block of instructions needs O
executed, we use the WHILE loop in
Python.

Real life examples of FOR loop:


Completing 10 rounds of jogging around
the park.
Making 15 rotis for dinner.
Reciting the multiplication table for any number.
SEKYA
CMR

Real life examples of WHILE loop:


Tossing acoin repeatedly until you get Heads.
Running around the park until you get tired.
e Blending pasta sauce ingredients into a paste until the right consistency is arrived at.

C.1 FOR loop using range():

FOR loop Syntax:


for iin range(start, stop, step):
<statements>

We use the range function to create an iterable based on the start, >>> for in range(1,11):
i

print(i)
stopand step values. The variable istands for each of the numbers
present in the iterable object.

Example 1: Considerthe following example that prints the numbers


1to 10 using for loop:

Notice that the stop value is 11 and not 10. range(1,11) returns the

collection of numbers: 1, 2, 3, 4, 5, 6, 7,8, 9, 10. Sincethere are 10


elements in the iterable object, the loop runs 10 times. Each time
the loop is run,the value of the variable changes from 1 to 2 to 3
i
and so on.
10

We print each element using the print() function.

the above
Example 2:What would be the output for
>>> foriin range(30, 20, -3):
exarnple?
print(i)
Let us create the list thatwould be created with the range

function: (30,27,24,21].
So, the output should display each of
these elements.

Output:

27
24
21

71
EKYA
SCHOOS
CMR

Example 3:Write a program that acceptsuser


name and prints it 6 times. #Accept user name and print it 6 times
name =input('Enter your name )
for iin range(6):
print(name)

range(6) creates thelist [0, 1, 2, 3,


4, 5). In this example,the for loop's only
purpose is to keep traol
of the number times the statementsare executed. Since the
of
name has to be printed 6 times
need the loop to run 6 times. In other words,the number
of elements present inside the list shoud
be 6. If we start from 0
and stop at 5, we have 6 elements in the list. We can achieve
the same result usingthis range
function: range(1,7).

Output:
Priya

Example 4: To print a multiplication table for a user given number.

#Accept a number and print the multiplication


tablefor the number
n int(input(ntera nantber )
for i in range(1, 11):
prini(n, ,i,,n" )
The rangefunction creates this list:[1,
2,3,4, 5,6, 7,8, 9, 10]

The variable takes on the values present


i
in the list. Let us assume that the user inputs
3 for n. Multiplication table for 3 should be: a value of

3x1=3
3 x 2 =6
3 x3=9

Enter a nurber l6
RSAR /0se
So,the print statement looks like this: 16 1 16
n xi=n*i 16 2 32
16 3 48

Output: 16

12
EKYA
SCHOOS
CMR

D.1FORloops without using range()


We can use the FOR statement without
using the range function, Instead of creating an iterable
obiect, we can use a list of values in
our loops.

Example 5:What will be the output of these lines of code?


>>>L=[a', b,'c, 'd]
>>> for i in L:
print(4"i)

Output:

itakes the value of 'a' first, then 'b' and so on.


What does 4*i mean? We are multiplying a string value with a number.

The * operator is known as replication operator when used with


strings. It replicates the string that many times.
>>> 'abe'*3
'abcabcabc'

What happens if we multiply one string with another?

We can use the replication operator with strings only when there is one
Python returns an error.

number andone string as operands.

Example 6:What will be the output of these lines of code?

>>>S='racecar

>> for i in s:
print (i, end )
a sequence that has elements, just like a list. The variable
Here s is a string, not a list. But, s is still
takes on the values from the string -r, 'a, ',e'
etc.
i

causes the next value to be printed on the same line

What is the use of end ="'in print(0? This

instead of a new line.

Output:

Eace
73
EKYA
SCHOOLS
CMR

D.2 Introductionto While Loops

While Loop Syntax:


while <condition>:
<statements>

In a while loop, we can test a condition. As long as the condition is true, the block of statermars.
keeps getting executed. When the condition is no longer satisfied, control passes to the immediate
statement after the while block.

Example 1: Accept a number from the user and print 'Hello that many times using a while In
(Note:This program is easier using FOR. This example is given to demonstrate how the While loon
works.)

# tinputtter #taeber )numer of tmes thelo shoid te risted

print (Helio ')

Output:

Hello
Hello
Hello
Hello
Hello

The condition in the program is that as long as the


number entered is greaterthan 0, 'hello'
printed. Within
will be
the body of the loop, everytime we print
'helo', we have to reduce n by 1. This
statement,n =n -1is known as the update
statement.What will happen if we do not decrement n?

When n is not decremented:

#Accept a number and print hello that many times


n= int(input('Enter a number )#number of times hello should be printed
while n > 0:

#1
print (Hello ')
#Thisis the same asn=n-1
EKYA
SCHOOLS
CMR

Output:
The word Hello keeps printing on IDLE and the program
execution willnot
end unless we stop it by closing IDLE. He1lo

Hel1o
Hello

If an updatestatement is not given in a while block, we will have an infinite loop. An infinite loop

keeps running until we close the program.

Example 2: Accept number a n and print

numbers 1 to n as output.
nninputtEntea unba greater han or equal to 1 )
Output: print (0)
i+*1Move to ne next number

75
EKYA
SCHOOLS

CMR go
tbeyons

Example 3: Acceptnumber n1 and number n2. Print thefirst 'n2' multipless of 'n1'. If n1 = 5and
n2 =
3, then the program needs to print the first 3 multiples of 5.
#print

n1
n2
|=1
while
=
n2 multiples
int(input(Enter

int(input(Enter

< n2:
of a number, n1
a number )
number of multiples )
using while loop

i
print (Multiple', I, is, n1"i)

+=1 #update statement

Output:

Enter a number 6
Enter nunber of multiples
Multiple 1 is 6
Multiple 2 is 12
Multiple 3 is 18
Multiple 4 is 24
Multiple 5 is 30
Multiple 6 is 36
4ultiple 7 is 42

76

You might also like