Python Coding Grade 6
Python Coding Grade 6
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.
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.
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.
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:
• Data analysis: Python helps analyse data for making decisions in various
fields, including science and business.
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.
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.
Syntax: print(prompt)
Example:
Code Output
print(‘Hello World!’) Hello World!
Do It Yourself 1A
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.
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.
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)
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
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.
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))
Do It Yourself 1B
Code Output
a = 10
print(type(a))
b = 4.2
print(type(b))
c=a+b
print(type(c))
Chapter Checkup
2 In Python, we use the function to check the dynamic data type assigned to a variable.
5 are the rules that tell us how to define structure, format, and organisation of code in a
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.
1 Define a prompt.
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
a 123var1=10
b Name1=Seema
Operators
Python is a language in which you can perform various operations. To perform these operations, operators and
operands are required.
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.
10
Assignment Operators
Assignment operators are used to assign values to variables. The following table summarises the various
assignment operators:
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:
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.
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:
12
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
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.
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?
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.
Let us now write an algorithm for calculating the sum of two numbers.
1 Start.
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.
14
Example: Write an algorithm to convert temperature value from Fahrenheit (°F) to Celsius (°C) and draw a
flowchart for the same.
INTEGRATED
Algorithm: Flowchart:
End
Do It Yourself 2B
HANDS-ON
Code Output
print(“Hello World”) Hello World
Code Output
str = input(“Enter any string:”) Enter any string: Ritu Singh
print(str) Ritu Singh
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)
16
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)
Code Output
x = sqrt(81) 9
print(x)
Do It Yourself 2D
Chapter Checkup
a / b // c % d #
18
i Exponential ii Parentheses
v Addition vi Subtraction
a 7 b 1 c 0 d 5
C Who am I?
2 I’m a built-in Math function that returns the square root of a number.
5 I’m the arithmetic operator which returns the remainder of two values.
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.
3 What is the order in which operations are evaluated? Write the order of precedence.
100 + 200 / 10 − 3 * 10
20
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.
• 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.
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
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.
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
Code Output
num1 = 50 num1 is less than num2
num2 = 100
if num1<num2:
print(“num1 is less than num2”)
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:
Condition
False True
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.
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.
Test
False
Expression
of if
True
Test
False
Expression
Body of if of elif
True
24
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.
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:
Explanation:
• 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 licence == True:
else:
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.
• 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
Code Output
number = 15 Given number is positive
if number > 0:
print(“Given number is positive”)
else:
print(“Given number is negative”)
26
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.
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:
Hints none of the conditions hierarchy and structure any one code block
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.
2 Which control statement is used to check multiple conditions until one of them is true?
a when b then
c if d condition
x = 15
if x > 10:
print(“Above 10”)
else:
print(“Below 10”)
a Above 10 b Below 10
28
1 I’m a Python control statement used to evaluate a condition and execute a code block if the condition is true.
3 I’m a Python control statement used to evaluate a condition and execute a code block if the condition is false.
2 The ‘if-elif-else’ statement allows you to check multiple conditions, but only one block of code
is executed.
4 In an ‘if... else’ statement, both the ‘if’ and ‘else’ blocks are executed if the condition is true.
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?
4 Differentiate between the ‘if’ statement and the ‘if... else’ statement in Python.
2 Write a Python program that prints the absolute value of a given number after checking its sign.
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.
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.
30