Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python Coding Grade 6

This document serves as an introduction to Python programming, explaining its features, applications, and basic syntax. It covers essential concepts such as programming languages, built-in functions, data types, and variable creation, along with examples. Additionally, it highlights Python's ease of use, versatility, and dynamic typing capabilities.

Uploaded by

agrimapandey505
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Coding Grade 6

This document serves as an introduction to Python programming, explaining its features, applications, and basic syntax. It covers essential concepts such as programming languages, built-in functions, data types, and variable creation, along with examples. Additionally, it highlights Python's ease of use, versatility, and dynamic typing capabilities.

Uploaded by

agrimapandey505
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

1 Introduction to Python

SEL Have you ever observed the traffic lights at a crossing? You stop when the light is red, you prepare to go when
the light is yellow and then you start when the light turns to be green.

Let us try to show this as a sequence of statements.

Step 1: Turn on the red light.

Step 2: Wait for 30 seconds.

Step 3: Turn off the red light.

Step 4: Turn on the yellow light.

Step 5: Wait for 5 seconds.


Step 6: Turn off the yellow light.

Step 7: Turn on the green light.

Step 8: You can go now.

Step 9: Turn off the green light.

Now, if you want to simulate this in the computer, then you need to write this as a program and in a language
that a computer can understand. This language is called programming language.

What Is Programming?
Programming is the process of giving instructions to tell a computer to perform a specific task. But instead of giving
the instructions verbally, you write them down in a structured manner in a language that a computer can
understand. This language is called a programming language. A programming language has its own vocabulary
and syntax or rules just like we have in English, Hindi, and other languages. There are many computer languages,
such as C, C++, Java, Python, and so on. Let us learn about Python in this chapter.

Python
Python is a high-level programming language that is easy to learn and simple to use. It is a powerful language
used for general-purpose programming.

It was created by Guido van Rossum and first released in 1991.

Features of Python
Let’s learn about some of the features of Python.
1 
Easy to code: The language used to write Python codes is similar to the English language, making it easy
for programmers to write and understand code.

CS_Coding Grade 6.indb 1 7/30/2024 11:28:32 AM


2 Cross-platform compatibility: Python can be used on
various operating systems, including Windows, macOS,
and Linux.
3 Open-source language: An open-source language is
Did You Know?
Python is named after a
the one which can be easily improved and distributed
famous British comedy
by anyone. Python is available for download and use group called Monty Python.
at no cost.
4 GUI application creation: Python also supports the
creation of Graphical User Interface (GUI) applications.
5 Interactive execution modes: Python offers script and
interactive modes for running programs. The code can be interactively tested and debugged in the
interactive mode. In this mode, only one statement is executed, whereas the script mode allows you to
execute a set of statements at a time.
6 Interpreted language: Python is an interpreted programming language, which means that the code is
executed line by line. This can make it easier to identify and correct errors as they occur. So you do not
need to wait for the entire program to be compiled before running it.
7 Dynamic typing: Python defines data type dynamically for the objects according to the value assigned.
Also, it supports dynamic data type checking.

Applications of Python
Python is a versatile programming language with a wide range of applications across various domains. Some of
the key applications of Python are:

• Programming and coding: Python is a versatile programming language used


to create software, games, and applications.

• Web development: Python is used to build web applications and websites.

• Data analysis: Python helps analyse data for making decisions in various
fields, including science and business.

CS_Coding Grade 6.indb 2 7/30/2024 11:28:33 AM


• Artificial intelligence: Python helps create computer programs that can chat
with you, recognise your voice, etc., making computers smarter.

• Scientific research: Scientists use Python to process and analyse data in


research, from studying diseases to exploring space.

Syntax
Programming languages have their own set of rules for writing. These
rules called syntax tell us how to define structure and organise code in a Think and Tell
programming language. Will a syntax error stop a
program from running?
Python too has its own rules. One important rule in Python is that it is
case-sensitive. This means that ‘num’, ‘Num’, and ‘nUm’ have different
meanings.

Built-in Functions
A function is a block of code used to perform a specific task. Built-in functions are the functions that are already
defined in Python. You can use them as many times as you want without defining them again.

In Python, there are numerous built-in functions readily available. These functions help simplify and accelerate
the development of programs.

One such built-in function is the input() function.

The input() Function


The input() function of Python is used to read input from a user.

Syntax: input(prompt)

The prompt is a message that is displayed on the screen to instruct the user on what input is expected. The input()
function always returns a string value (text) even if you entered a number as input.

Example:

Code Output
name = input(‘Enter your name:’) Enter your name: Neha

In this example, a user is prompted with ‘Enter your name:’, and the user’s input is ‘Neha’.

Let us now learn about another built-in function of Python: the print() function.

Chapter 1 • Introduction to Python 3

CS_Coding Grade 6.indb 3 7/30/2024 11:28:34 AM


The print() Function
The print() function helps you to see the results of your code and understand how it is working.

Syntax: print(prompt)

Example:

Code Output
print(‘Hello World!’) Hello World!

Do It Yourself 1A

What will be the output of the following code?

Code Output
message = input(“Enter your message”)
print(“Here is your message:”)
print(message)

Data Types
A data type specifies the type of value a variable can contain. A data type also determines how data is stored in
memory. For example, a student’s name should be stored as a string value because a string data type is used to
represent text or a sequence of characters. A student’s age should be stored as an integer as the value of age
must be a whole number. Also, the student’s weight should be stored as a floating-point number because the
weight may have a decimal part.

Data types in Python are:


1 
int: Positive or negative whole numbers (without any fractions or decimals).
Examples: 30, 180, 89, etc.
2 
float: Any real number with decimal points.
Examples: 6.3, 9.5, 320.0, etc.
3 
string: A string value is a collection of one or more characters put in a single or double quotes.
Examples: ‘Python’, ‘hello’, ‘1495’, etc.

Variables
A variable is a reference name given to a location in a computer’s memory. The names given to the variables are
known as identifiers. Variables allow you to store a value on that location and refer to it as needed. Variables
are dynamic, meaning their values can be changed as the program runs.

CS_Coding Grade 6.indb 4 7/30/2024 11:28:34 AM


Creating a Variable
• In Python, variables are declared and initialised by assigning a value to a variable.
Syntax: variable_name = value
Example:

Code Output
number = 5 5 Stars
word = “Stars”
print(number, word)

• You can also assign a single value to multiple variables at the same time.
Syntax: var1 = var2 = value
Example:

Code Output
number1 = number2 = 10 number 1 = 10
print(“number 1 =”, number1) number 2 = 10
print(“number 2 =”, number2)

• You can also initialise multiple values to multiple variables in one line.
Syntax: var1, var2 = value1, value2
Example:

Code Output
number, word = 5, “Stars” 5 Stars
print(number, word)

Rules for Naming a Variable


There are certain rules to name a variable. Let us learn about these rules.
1 Spaces are not allowed when naming variables. You can instead use an underscore (_) symbol.

2 A variable name can contain only alphanumeric characters (all the letters of the alphabet and numbers)
and underscores (_).
3 Variable names cannot contain any special character or symbol.
For example, v@lue is an invalid name for a variable.
4 A variable name must start with a letter or an underscore (_) symbol. This name cannot start with a number.
Examples of valid names for a variable:
My_variable_1
_my_variable2
Examples of invalid names for a variable:
1myvariable
2_myvariable

Chapter 1 • Introduction to Python 5

CS_Coding Grade 6.indb 5 7/30/2024 11:28:35 AM


5 Variable names are case sensitive.
For example, value, Value, and VALUE are three different variables.
Example:

Code Output
my_variable = 10 10
My_Variable = 20 20
MY_VARIABLE = 30 30
print(my_variable)
print(My_Variable)
print(MY_VARIABLE)

Dynamic Typing
Dynamic typing in Python means that you can assign a value to a variable, and the variable automatically takes
the data type of that assigned value at runtime. In other words, you do not have to specify the data type of a
variable when you declare it; Python figures it out for you based on the value assigned to it.

The type() Function


In Python, we use the type() function to check the dynamic data type assigned to a variable. It is a built-in
function that returns the type of an object. The object can be a variable, a value, or an expression.

Syntax: type(object_name)

Example:

Code Output
text1 = input(“Enter your name:”) Enter your name: Grisha
num1 = input(“Enter your age:”) Enter your age: 10
print(type(text1)) <class ‘str’>
print(type(num1)) <class ‘str’>

The input() function always returns a string value, even if it takes a number, string, or any other value as input.
And, as you have assigned user input to the two variables, both the variables are of the string type.
Example:

Code Output
x=5 <class ‘int’>
y = “Hello” <class ‘str’>
z = 3.14 <class ‘float’>
result = x + 2.5 <class ‘float’>
print(type(x))
print(type(y))
print(type(z))
print(type(result))

CS_Coding Grade 6.indb 6 7/30/2024 11:28:35 AM


In this example, we use the type() function to check the data types of the variables x, y, and z, as well as the
result of an expression. The dynamic data typing in Python makes the variables change their data type based on
the assigned value.

Do It Yourself 1B

1 What will be the output of the given code?

Code Output
a = 10
print(type(a))
b = 4.2
print(type(b))
c=a+b
print(type(c))

2 What is the full form of GUI?

Chapter Checkup

A Fill in the blanks.

Hints type() string identifiers syntax Guido van Rossum

1 Python was created by .

2 In Python, we use the function to check the dynamic data type assigned to a variable.

3 The names given to the variables are known as .

4 The input() function always returns a value.

5  are the rules that tell us how to define structure, format, and organisation of code in a
programming language.

B Tick () the correct option.

1 The language used to write Python codes is similar to the language.

a Chinese b German c English d French

2 Which of the following is a data type in Python?

a int b float c string d All of these

Chapter 1 • Introduction to Python 7

CS_Coding Grade 6.indb 7 7/30/2024 11:28:35 AM


3 Which of the following is a valid variable name?

a Color_1 b 1_color c &color d color 1

4 function helps you see the results of your code.

a print() b input() c type() d output()

5 A is a reference name given to a location in the computer’s memory.

a Data type b Variable c Function d Syntax

C Write T for True and F for False.

1 Python is a low-level programming language.

2 Python offers the script and interactive modes for running programs.

3 Python helps create computer programs that can chat with you, recognise your voice, etc.

4 Any real number with decimal points has the string data type.

5 A variable name can start with a number.

D Answer the following questions.

1 Define a prompt.

2 State any two features of Python.

3 Differentiate between the int and float data types.

4 Explain dynamic typing.

5 What are the applications of Python in the field of AI?

CS_Coding Grade 6.indb 8 7/30/2024 11:28:35 AM


E Apply your learning.

1 What will be the output of the following program?

a x = input (‘Enter your name:’)


y = input (‘Enter your height:’)
z = input (‘Enter your contact number:’)
print(type(x))
print(type(y))
print(type(z))

b fruit = ‘apple’
Fruit = ‘orange’
print(fruit)

2 Rohan wants to declare a variable in his program, but he is unaware of the rules for naming a variable. Help him
by mentioning all the rules you have learnt.

3 Shivam is creating a Python program. He has heard that Python has built-in functions to simplify and speed up
the development of programs. Name any two built-in functions that he can use.

4 What will be the data type of the values that these variables hold?

a num1 = 10

b var1 = ‘How are you?’

5 Find the errors in the following statements:

a 123var1=10

b Name1=Seema

Chapter 1 • Introduction to Python 9

CS_Coding Grade 6.indb 9 7/30/2024 11:28:36 AM


2 Operators in Python

Operators
Python is a language in which you can perform various operations. To perform these operations, operators and
operands are required.

An operator is a symbol that is used to perform operations on variables or Operators


on values.

The values or variables are called operands.

The combination of operands and operators is called an expression.


x + y = z
In the adjoining picture, x, y, and z are operands. The ‘+’ and ‘=’ symbols are
Operands Operand
called operators. The combination of x, y, z, ‘+’, and ‘=’ is called an expression.

Types of Operators
The Python language supports the following types of operators:

• Arithmetic operators
• Assignment operators
• Relational/Comparison operators
• Logical operators
Let us discuss all the operators one by one.

Arithmetic Operators
These operators are used with numeric values to perform common mathematical operations.
Arithmetic operators supported by Python are listed in the following table.
For the examples given below, consider the values x = 100 and y = 3.

Operator Name Description Example Output


+ Addition Adds two operands. x+y 103
− Subtraction Subtracts the value of one operand from the other. x−y 97
* Multiplication Multiplies two operands. x*y 300
/ Division Displays the quotient when the first operand is x/y 33.3333…
divided by the second.

10

CS_Coding Grade 6.indb 10 7/30/2024 11:28:36 AM


Operator Name Description Example Output
// Floor Division Divides the operand on the left by the operand on x // y 33
the right and returns the quotient by removing
the decimal part. Sometimes, it is also called
integer division.
% Modulus Displays the remainder when the first operand is x%y 1
(Remainder) divided by the second.
** Exponentiation Raises the first operand to the power of the x ** y 1000000
(Power) second.

Assignment Operators
Assignment operators are used to assign values to variables. The following table summarises the various
assignment operators:

Operator Description Example Same As


= Assigns the right-hand side value to the left-hand side variable. x = 11 x = 11
+= Adds the right operand to the left operand and then assigns the x += 11 x = x + 11
result to the left operand.
−= Subtracts the right operand from the left operand and then x −= 11 x = x − 11
assigns the result to the left operand.
*= Multiplies the right operand with the left operand and then x *= 11 x = x * 11
assigns the result to the left operand.
/= Divides the left operand with the right operand and then assigns x /= 11 x = x / 11
the result to the left operand.
%= Calculates the modulus using two operands and then assigns x %= 11 x = x % 11
the result to the left operand.
//= Performs floor division on operators and then assigns the value x //= 11 x = x // 11
to the left operand.
**= Performs exponential calculation on operators and then assigns x **= 11 x = x ** 11
the value to the left operand.

Relational/Comparison Operators
These operators are used to compare two values. The comparison operators are also known as Relational
Operators. The following table summarises the various types of relational operators used in Python.

Consider the values x = 100 and y = 3 for the examples in the following table:

Operator Description Example Output


== Returns true if the left-hand side value is equal to the right-hand x==y False
side value; otherwise, it returns false.
!= Returns true if the left-hand side value is not equal to the right- x != y True
hand side value; otherwise, it returns false.

Chapter 2 • Operators in Python 11

CS_Coding Grade 6.indb 11 7/30/2024 11:28:36 AM


Operator Description Example Output
> Returns true if the left-hand side value is greater than the x>y True
right-hand side value; otherwise, it returns false.
< Returns true if the left-hand side value is smaller than the x<y False
right-hand side value; otherwise, it returns false.
>= Returns true if the left-hand side value is greater than or equal x >= y True
to the right-hand side value; otherwise, it returns false.
<= Returns true if the left-hand side value is smaller than or equal x <= y False
to the right-hand side value; otherwise, it returns false.

Logical Operators
These operators are used to combine conditional statements. Logical operators evaluate to True or False
based on the operands on their either side. There are three logical operators in Python, as summarised in the
following table.

Consider the value x = 2 for the examples given below:

Operator Description Example Output


and Returns true if the statements on the left-hand side x < 5 and x < 10 True
as well as the right-hand side are true.
or Returns true if any one of the statements is true. x < 5 or x < 1 True
not Reverses the result and returns false if the result is not(x < 5 and x < 10) False
true.

Operator Precedence
If there are more than one operator in an expression, then we need to follow operator precedence to evaluate
the expression.

Operator precedence describes the order in which operations are to be performed on the operand.

You need to follow the PEDMAS rule for evaluating the mathematical expressions. The PEDMAS rule is as follows:

• P—Parentheses
• E—Exponentiation
• D—Division
• M—Multiplication (Multiplication and division have the same precedence.)
• A—Addition (Addition and subtraction have the same precedence.)
• S—Subtraction
The following table describes the precedence level of the operators from the highest to the lowest:

Precedence Level Operator Explanation


1 (highest) () Parentheses
2 ** Exponentiation
3 −a, +a Negative, positive argument

12

CS_Coding Grade 6.indb 12 7/30/2024 11:28:36 AM


Precedence Level Operator Explanation
4 *, /, //, % Multiplication, division, floor division, modulu
5 +, − Addition, subtraction
6 <, <=, >, >=, ==, != Less than, less than or equal, greater, greater or
equal, equal, not equal
7 not Boolean Not
8 and Boolean And
9 or Boolean Or

Let us evaluate the following expression to understand operator precedence.

Evaluate: 16 / 4 + (8 – 3)

Solution:

Step 1: 16 / 4 + (8 – 3)
Did You Know?
Step 2: 16 / 4 + 5
Python gives more precedence
Step 3: 4 + 5 to arithmetic operators
than comparison operators.
Step 4: 9 Within comparison operators,
every operator has the same
Observe in this example that the order of precedence is changed
precedence order.
using parentheses (), as it has higher precedence than the division
operator. Therefore, the subtraction operation ‘–’ is performed
prior to the division operation as ‘–’ is within the parentheses.

Do It Yourself 2A

What will be the output of the following expressions?

1 (10 + 15 /5 * 8 // 2)

2 (10 > 6 + 3 − 1)

3 100 / 10 * 10

4 5 − 2 + 3

Algorithms
Any problem can be solved if a specific sequence of steps is followed.

An algorithm can be defined as a logical, step-by-step procedure for solving a problem.

You need to provide a set of inputs to the algorithm, and the algorithm provides you the output.

Let us understand using an example. Do you know, trees play a very important role in our lives. Have you ever
SDG
planted a tree?

Let us look at the steps that you follow:


1 Take a pot and put soil in it. The soil should be of good quality.
2 Loosen the soil with a small trowel.

Chapter 2 • Operators in Python 13

CS_Coding Grade 6.indb 13 7/30/2024 11:28:37 AM


3 Dig a small hole in it and place the seed in the hole. Cover the seed with 1 Dig up 2 Plant seeds
the soil. the ground

4 Take care to not dig too deep a hole. The hole should be shallow and the
seed not too tightly covered with the soil.
5 Water the soil to make it moist.
6 The seed is planted and it is ready to germinate and grow.
The seeds
3 water
4 sprouted
the plant
Rules for Writing an Algorithm
While writing an algorithm, there are rules that you must follow:
1 Start with a clear goal.

2 Use a simple and precise language.

3 Break tasks into smaller steps.

4 Provide clear and logical instructions.

5 Ensure that you get a tangible output at the end.

Let us now write an algorithm for calculating the sum of two numbers.
1 Start.

2 Input the first number, say num1.

3 Input the second number, say num2. Did You Know?


4 Use another variable to store the sum, say sum. The term “algorithm”
originates from the name
5 Initialise sum to 0, i.e., sum = 0. of a Muslim mathematician
and scientist, Muhammad
6 Calculate sum: sum = num1 + num2. al-Khwarizmi. He introduced
7 Display sum. the concept of algorithms and
is also known for inventing
8 Stop. algebra.

Flowcharts
A flowchart is a graphical or visual representation of an algorithm that uses various symbols, shapes, and arrows to
show a process or program. A flowchart helps a user readily understand a problem. The primary goal of using a
flowchart is to evaluate various ways to solve a problem.

Symbols Used for a Flowchart


A flowchart consists of a number of standard symbols. The following symbols indicate various elements of a
flowchart:

Name of the Symbol Shape of the Symbol Purpose of the Symbol


Terminal Box—Start/End It is used at the beginning and end of a
flowchart.

Input/Output It is used to provide input and output


information.

14

CS_Coding Grade 6.indb 14 7/30/2024 11:28:39 AM


Name of the Symbol Shape of the Symbol Purpose of the Symbol
Process It is used for processing and calculating
statements.

Decision It is used when a condition is applied in


the process.

Arrow It represents the direction of the process.

Example: Write an algorithm to convert temperature value from Fahrenheit (°F) to Celsius (°C) and draw a
flowchart for the same.
INTEGRATED

Algorithm: Flowchart:

Step 1: Start. Start

Step 2: Read temperature in Fahrenheit, say F.


Read F
Step 3: Apply the formula to calculate the value in Celsius, i.e., C=5/9*(F−32).

Step 4: Display the value of C. C=5/9*(F – 32)


Step 5: Stop.
Print C

End

Do It Yourself 2B

Write an algorithm and draw a flowchart to calculate the perimeter of a rectangle.

HANDS-ON

Chapter 2 • Operators in Python 15

CS_Coding Grade 6.indb 15 7/30/2024 11:28:40 AM


Writing a Python Program
When you communicate with your friends, you use a language. Every language has a grammar that you need to
follow to make proper sentences. Similarly, in the Python language, you need to follow certain rules for writing
programs. These rules are called syntax.
Syntax is like the grammar rules for writing code in a programming language.
In the previous chapter, you learnt about input() and print() functions. Let us create some programs using these
functions and see how they work.
1 
Write a Python program to display Hello World on the screen.

Code Output
print(“Hello World”) Hello World

Let us analyse the code:


The print() function is used to print the statement given inside the double quotes, that is, the string ‘Hello
World’ is displayed in the output area.
2 Write a Python program to get a string input from the user and display it.

Code Output
str = input(“Enter any string:”) Enter any string: Ritu Singh
print(str) Ritu Singh

Let us analyse the code:


Line 1: The input() function is used to take input from the user. On the output screen, the message ‘Enter
any string:’ is displayed, and the console waits for the user to enter any string. The value entered is stored
in the variable ‘str’.
Line 2: The print() function is used to display the value stored in the variable ‘str’ on the output screen.
3 Write a Python program to add two numbers.

Code Output
val1 = 100.99 The sum of given numbers is: 177.14
val2 = 76.15
sum = float(val1) + float(val2)
print(“The sum of given numbers is:”, sum)

Let us analyse the code:


Lines 1 and 2: Two variables val1 and val2 are assigned the values 100.99 and 76.15, respectively.
Line 3: The two numbers are added, and their sum is stored in the sum variable.
Line 4: The print() function displays the statement, “The sum of given number is:” along with the value of the sum.

Think and Tell


What is a console?

16

CS_Coding Grade 6.indb 16 7/30/2024 11:28:40 AM


Do It Yourself 2C

Write a Python program to convert Celsius to Fahrenheit.

Using Math Library in Python


INTEGRATED In the previous section, you have learnt about the basic arithmetic operators. Apart from using these arithmetic
operators, there are various mathematical operations for which Python has many built-in methods. These
methods or functions are stored in a library known as the math library of Python. Let us learn some of these
functions.

Built-in Math Functions


The min() and max() functions: The min() and max() functions can be used to find the lowest or highest value.

Code Output
x = min(5, 10, 25) 5
y = max(5, 10, 25) 25
print(x)
print(y)

The abs() function: The abs() function returns the absolute (positive) value of a specified number.

Code Output
x = abs(−7.25) 7.25
print(x)

The pow() function: The pow(x, y) function returns the value of x raised to the power of y (xy).

Code Output
x = pow(4, 3) 64
print(x)

Chapter 2 • Operators in Python 17

CS_Coding Grade 6.indb 17 7/30/2024 11:28:40 AM


The sqrt() function: The sqrt() function returns the square root of a given number.

Code Output
x = sqrt(81) 9
print(x)

Do It Yourself 2D

1 Write a Python program to find the minimum of five given numbers.

2 Write a Python program to find 6 raised to the power of 3.

Chapter Checkup

A Fill in the blanks.

Hints pow(x, y) operator algorithm logical precedence

1 The is a logical step-by-step procedure for solving a problem.

2 An is a symbol that performs mathematical operations on variables or on values.

3 Operator describes the order in which operations are performed.

4 operators are used to combine conditional statements.

5 The function returns the value of x to the power of y (xy).

B Tick () the correct option.

1 Which is the correct operator for calculating the power(xy)?

a X^y b X**y c X^^y d x*y

2 Which of these is the floor division operator?

a / b // c % d #

18

CS_Coding Grade 6.indb 18 7/30/2024 11:28:41 AM


3 What is the order of precedence of operators in Python?

i Exponential ii Parentheses

iii Multiplication iv Division

v Addition vi Subtraction

a i, ii, iii, iv, v, vi b ii, i, iii, iv, v, vi

c i, ii, iv, iii, v, vi d i, ii, iii, iv, vi, v

4 What is the answer of this expression: 22 % 3?

a 7 b 1 c 0 d 5

5 Which of the following has the highest precedence in an expression?

a Exponential b Addition c Multiplication d Parentheses

C Who am I?

1 I’m a set of rules to be followed for writing Python programs.

2 I’m a built-in Math function that returns the square root of a number.

3 I’m at the highest precedence of arithmetic operators.

4 I’m the operator which compares two values.

5 I’m the arithmetic operator which returns the remainder of two values.

D Write T for True and F for False.

1 The expression 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).

2 Operands (values) operate on operators and return a result.

3 The value of the expression 100/25 is 0.

4 A flowchart is a graphical or visual representation of an algorithm that uses various symbols, shapes,
and arrows to show a process or program.

5 Python gives arithmetic operators more precedence than comparison operators.

Chapter 2 • Operators in Python 19

CS_Coding Grade 6.indb 19 7/30/2024 11:28:41 AM


E Answer the following questions.

1 What is the difference between the * and ** operators in Python?

2 What do you mean by an assignment statement?

3 What is the order in which operations are evaluated? Write the order of precedence.

4 Give an example each of the min() and max() functions.

5 Explain the concept of floor division.

F Apply your learning.

1 What will be the output of the following?


INTEGRATED

100 + 200 / 10 − 3 * 10

2 Write a Python program to convert the distance entered in metres to kilometres.

3 Write a Python program to calculate your body mass index (BMI).

4 Write an algorithm for making a vegetable sandwich.

5 Draw a flowchart for showing the progress of a plant’s growth.

20

CS_Coding Grade 6.indb 20 7/30/2024 11:28:41 AM


Conditional Statements
3 in Python

Control Statements
Control statements in the Python programming language are used to manage the sequence of execution within
a program. It allows you to make decisions, repeat actions, and control the overall flow of your code. These
statements will ensure that a program will move smoothly and purposefully.

Here are the main types of control statements in Python:

• Sequential Statements • 
Conditional Statements • 
Iterative Statements or Loops

Until now, you have learnt only to write programs using sequential statements. Let us now learn about
conditional statements.

Conditional Statements
Using conditional expressions, we may tell a computer to look for a specific condition and to
take action if the condition occurs.

These statements enable you to execute various sections of code, based on whether a given
condition is true or false.

For example: If it rains, then take an umbrella.

Types of Conditional Statements


In Python, there are three types of conditional statements that allow us to make decisions in our programs.
These include the:

• if Statement • if...else Statement • if-elif-else Statement

The if Statement
The ‘if’ statement is used to evaluate a condition and execute
a code block if the condition evaluates to true. Otherwise,
the code block will be skipped. You should use the ‘if’
keyword to write an “if statement”. Did You Know?
Conditional statements in
Syntax:
programming are like decision-
if condition: making in life, where “if” is the
choice, “else if” is the backup
# Statement to execute if condition is true plan, and “else” is the fallback.

21

CS_Coding Grade 6.indb 21 7/30/2024 11:28:42 AM


The flowchart for the if statement is as follows:

True
if(expression)

False
statement(s)

rest of code

Example:

Code Output
num = 10 number is greater than 9
if num > 9:
print(“number is greater than 9”)

Explanation:
1 In the above program, a variable num is assigned a value 10.
2 The condition in the if statement checks whether the value of num variable is greater than 9 or not.

3 If it is greater than 9, then the statement that follows the if statement is executed and the message
“number is greater than 9” is displayed.
4 Otherwise, the control comes out of the program.

Indentation in Python
Indentation refers to the space at the beginning of a code line.

In Python, indentation is used to define blocks of code. It is a fixed number of spaces added at the beginning of
each line of code. It is used to define the hierarchy and structure of the code. The statements at the same level
of indentation are considered to be a part of the same block.

Consider the following if statement:


if condition: Think and Tell
What happens if there is no
(_____)statement
indentation in a Python program?
Indentation

Example:

Code Output
num1 = 50 File “demo_if_error.py”, line 4
num2 = 100 print(“x is greater than y”)
if num1<num2: ^
print(“num1 is less than num2”) IndentationError: expected an indented block

Observe in the above code, lines 3 and 4 are at the same indentation level, but line 4 must be a part of the ‘if’
statement; therefore, there must be some indentation before ‘line 4’:

22

CS_Coding Grade 6.indb 22 7/30/2024 11:28:42 AM


The corrected code is as follows:

Code Output
num1 = 50 num1 is less than num2
num2 = 100
if num1<num2:
print(“num1 is less than num2”)

The if…else Statement


In the previous section, you learnt that output is displayed only in the case when the condition results to be true.
In case the condition evaluates to be false, then there will be no output. What if you want to display a message
even in case the condition evaluates to be false? In Python, you can use the if…else statement for this purpose.

Using the if...else statement, the block of code after the if statement is executed if the condition is true, and the
block of code after the else statement is executed if the condition is false.

Syntax:

if condition:

#Statements to be executed if condition becomes True


Discuss
else: What is the role of the else statement
in conditional statements?
#Statements to be executed if condition becomes False

The flowchart for the if-else statement is as follows:

Condition

False True

statements of else block statements of if block

rest of the code

Example:

Code Output
num = 7 number is not greater than 9
if num > 9:
print(“number is greater than 9”)
else:
print(“number is not greater than 9”)

Explanation:
1 In this program, the variable num is assigned a value 7.

2 The condition given in the if statement checks whether the value of num variable is greater than 9 or not.

Chapter 3 • Conditional Statements in Python 23

CS_Coding Grade 6.indb 23 7/30/2024 11:28:42 AM


3 If it is greater than 9, then the statement that follows the if statement is executed and the message
“number is greater than 9” is displayed.
4 Otherwise, the statement following the else part is executed and the message “number is not greater than
9” is displayed.

if-elif-else Statement
The if-elif-else statement is an extension of the if...else statement. The if-elif-else statement allows you to check
multiple conditions in a program. Python checks each condition until any one of them is true.

Syntax:

if condition1:
Statement1
elif condition2: Did You Know?
Statement2 Python allows you to chain
multiple comparisons together,
elif condition 3:
making complex conditions
Statement3 more readable.
.. For example,
.. if 1 <= x <= 10.
else:

Final_Statement

Explanation:

• If condition1 becomes true, then the statement1 is executed, and the rest of the statements are ignored.

• Otherwise, the interpreter moves on to condition2. if it becomes true, then it executes Statement2.

• 
This process continues until a true condition is found. Otherwise, the ‘else’ statement is executed if none of
the conditions are true.

The flowchart for the if-elif-else statement is as follows:

Test
False
Expression
of if

True
Test
False
Expression
Body of if of elif

True

Body of elif Body of else

24

CS_Coding Grade 6.indb 24 7/30/2024 11:28:42 AM


Example:

Code Output
num1 = 50 num1 is less than num2
num2 = 100
if num1 > num2:
print(“num1 is greater than num2”)
elif num1 == num2:
print(“Numbers are equal”)
else:
print(“num1 is less than num2”)

Explanation:
1 In this program, the values of num1 and num2 are 50 and 100, respectively.

2 The condition with the if statement is checked. In this case, the condition evaluates to false.

3 The control will move on to the elif part.

4 The condition num1 == num2 is checked, which is also false.


5 So, the control moves to the else part directly and the statement “num1 is less than num2” is executed and
hence displayed in the output.

Nested if Statement
Sometimes in programming, we need to make complex decisions which depend on multiple conditions. For
those decisions, we use an if-elif-else statement inside the body of another if-elif-else statement. This is called
nesting of statements.

Syntax:

if condition1:

statement 1
if condition2:

statement 2

else:
False
Condition1 Condition2
statement 3

else:

statement 4 True True False

The flowchart for the nested if statement is


as follows: Body of if Body of Nested if Body of Nested else

Explanation:

• The outer if statement checks condition1.


• If condition1 is True, the indented code
block below it executes. This block can Statement
contain another if statement, creating a just below if
nested condition.

Chapter 3 • Conditional Statements in Python 25

CS_Coding Grade 6.indb 25 7/30/2024 11:28:42 AM


• The inner if statement checks condition2.
• If condition2 is True, the code within its indented block executes. If condition2 is False, the else block within
the outer if (if present) executes.

• The outer else block (optional) executes if condition1 is False from the beginning.
Example:

Code Output
age = 12 You are too young to drive.
licence = True

if age >= 18:

if licence == True:

print(“You can drive!”)

else:

print(“You need a licence to drive.”)

else:
print(“You are too young to drive.”)

Explanation:

• The above code checks the eligibility to drive based on age and the possession of licence.

• The outer if checks if age is greater than or equal to 18.

• If age is greater than or equal to 18, then the inner if checks if the value of the licence variable is True.

• If both conditions are met (age and licence), the message “You can drive!” is displayed.

• If licence is False within the True block of age, the message “You need a licence to drive” is displayed.

• If age is less than 18 (outer if becomes False), the message “You are too young to drive” is displayed.

Solved Examples
Example 1

Write code in Python to check if an integer is positive or negative.

Code Output
number = 15 Given number is positive
if number > 0:
print(“Given number is positive”)
else:
print(“Given number is negative”)

26

CS_Coding Grade 6.indb 26 7/30/2024 11:28:43 AM


Example 2
Write code in Python to check whether a given number is divisible by 5 or not.

Code Output
number = 50 Given number is divisible by 5
if number % 5 == 0:
print(“Given number is divisible by 5”)
else:
print(“Given number is not divisible by 5”)

Example 3
Suppose you want to check your results in a monthly cycle test according to the marks scored by you in three
main subjects. If the average of the marks you scored is greater than 80, then you deserve a treat. Otherwise,
HANDS-ON
you need to work hard in the next cycle.

Create a Python program for the given condition.

Code Output
subject1 = float(input(“Enter marks for subject 1: “)) Enter marks for subject 1: 68
subject2 = float(input(“Enter marks for subject 2: “)) Enter marks for subject 2: 52
subject3 = float(input(“Enter marks for subject 3: “)) Enter marks for subject 3: 72
total_marks = subject1 + subject2 + subject3 Average is: 64.0
average = total_marks / 3 Work hard in the next cycle.
print(“Average is:”, average)
if average >= 80:
print(“You deserve a treat!”)
else:
print(“Work hard in the next cycle.”)

Coding Challenge
Write a Python program to check the marks of a student and print the remark accordingly.
You can refer to the following criteria:

Marks in the range 91 to 100 Excellent


81 to 90 Very Good
71 to 80 Good
61 to 70 Average
51 to 60 Fair
41 to 50 Try Again

Chapter 3 • Conditional Statements in Python 27

CS_Coding Grade 6.indb 27 7/30/2024 11:28:43 AM


Chapter Checkup

A Fill in the blanks.

Hints none of the conditions hierarchy and structure any one code block

1 Indentation in Python is used to define of code.

2 The ‘if-elif-else’ statement allows you to check multiple conditions until condition is true.

3 The ‘if’ statement is used to evaluate a condition, and if the condition is true, a specified is executed.

4 The ‘else’ part of the ‘if...else’ statement is executed if is true.

B Tick () the correct option.

1 What is the purpose of the ‘else’ part in an ‘if...else’ statement?

a To execute when the condition is true b To handle exceptions

c To execute when the condition is false d To terminate the program

2 Which control statement is used to check multiple conditions until one of them is true?

a if Statement b for Loop

c while Loop d if-elif-else Statement

3 In Python, which keyword is used to define an ‘if’ statement?

a when b then

c if d condition

4 What is the output of the given code?


a=5
b = 20
if b > a:
print(“b is greater than a”)

a b is greater than a b a is greater than b

c Indentation error d None of these

5 What is the output of the given code?

x = 15
if x > 10:
print(“Above 10”)
else:
print(“Below 10”)

a Above 10 b Below 10

c Error d None of these

28

CS_Coding Grade 6.indb 28 7/30/2024 11:28:43 AM


C Who am I?

1 I’m a Python control statement used to evaluate a condition and execute a code block if the condition is true.

2 I’m used to check multiple conditions in Python.

3 I’m a Python control statement used to evaluate a condition and execute a code block if the condition is false.

D Write T for True and F for False.

1 Indentation is optional in Python.

2 The ‘if-elif-else’ statement allows you to check multiple conditions, but only one block of code
is executed.

3 Indentation refers to the space at the beginning of a code line. 

4 In an ‘if... else’ statement, both the ‘if’ and ‘else’ blocks are executed if the condition is true.

E Answer the following questions.

1 What are control statements? How many types of control statements are there in Python?

2 What do you mean by conditional statements? How many types of conditional statements are used in Python?

3 Explain the purpose of indentation in Python code.

4 Differentiate between the ‘if’ statement and the ‘if... else’ statement in Python.

5 How does the ‘if-elif-else’ statement work in Python?

F Apply your learning.


INTEGRATED
1 Write a Python program that checks if a given number is even or odd and prints an appropriate message.

2 Write a Python program that prints the absolute value of a given number after checking its sign.

Chapter 3 • Conditional Statements in Python 29

CS_Coding Grade 6.indb 29 7/30/2024 11:28:44 AM


3 Write a Python program that determines whether a given year is a leap year or not and prints the result.
[Hint: If a year’s value is divisible by 4, then it is a leap year.]

4 Write a Python program to check whether it is possible to make a triangle or not. A triangle is possible if the sum
of all its angles is equal to 180 degrees.

5  uppose you are creating a discount program for a store. Customers of 60 years of age or above are eligible for
S
a discount. On top of the senior discount, members also receive an additional benefit. Write a Python program
HANDS-ON
that calculates the discount rate for a customer based on their age and membership status.

The program should consider the following scenarios:

Senior citizen (60 years or older) and member: Receives a 20% discount.

Senior citizen (60 years or older) but not a member: Receives a 10% discount.

Customer under 60 years of age, but a member: Receives a 5% discount.

Customer under 60 years of age and not a member: Receives no discount.

30

CS_Coding Grade 6.indb 30 7/30/2024 11:28:44 AM

You might also like