Computer Science Tekie
Python I Web Development I
6
Acknowledgements
Academic Authors: Jatinder Kaur, Ayushi Jain, Anuj Gupta, Simran Singh
Creative Directors: Bhavna Tripathi, Mangal Singh Rana, Satish
Book Production: Rakesh Kumar Singh, Sakshi Gupta
Project Lead: Jatinder Kaur
VP, Learning: Abhishek Bhatnagar
All products and brand names used in this book are trademarks, registered trademarks or trade names of their respective owners.
© Uolo EdTech Private Limited
First published 2023
Second published 2024
Third published 2025
This book is sold subject to the condition that it shall not by way of trade or otherwise, be lent, resold, hired out, or otherwise circulated without the publisher’s prior written consent in any form of binding or cover other than that in which it is published and without a similar condition including this condition being imposed on the subsequent purchaser and without limiting the rights under copyright reserved above, no part of this publication may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of both the copyright owner and the above-mentioned publisher of this book.
Book Title: Tekie Computer Science Python I Web Development I
ISBN: 978-81-979364-1-8
Published by Uolo EdTech Private Limited
Corporate Office Address:
85, Sector 44, Gurugram, Haryana 122003
CIN: U74999DL2017PTC322986
Illustrations and images: www.shutterstock.com, www.stock.adobe.com and www.freepik.com
All suggested use of the internet should be under adult supervision.
Preface
Standing at the forefront of the digital and AI revolution, the importance of coding and computational skills has reached unprecedented heights. In today’s professional landscape, whether it is in the fields of medicine, space exploration, education, science, or business, no sector remains untouched by this transformative wave. To thrive in the 21st century, basic computer literacy is no longer sufficient. Learners must evolve into “digital natives” who can fluently read, write, and communicate in the languages that machines and AI comprehend. Recognising this imperative, the National Education Policy of 2020 (NEP 2020) has strongly recommended the integration of coding skills, computational thinking, critical analysis, and problem-solving abilities into the curriculum. Moreover, forward-looking subjects like AI, Data Science, Computer Applications, and IT have been introduced as elective subjects from grade 9 onwards. It would not be surprising if further transformative measures are taken even at the elementary education level.
Inspired by these insights, Uolo has introduced an innovative 360-degree program for a codingfocused computer science curriculum, known as Tekie, spanning grades 1 to 8. The program provides an experiential learning approach, going beyond theoretical knowledge. It not only covers theoretical aspects of computer science and coding, but includes hands-on activities and technology-based projects that enable students to experience computer science first hand. The program includes chapters that provide a deeper immersion in computer science that both learners and teachers may find interesting.
This coding book is a part of the larger Tekie program that also includes a main computer science textbook, covering the basics of computing, the latest technologies, and essential computer tools.
In addition to the textbooks, we provide a digital platform where students can actively engage in practical activities and hands-on learning projects. This platform is designed to enhance the learning process by allowing students to experiment and apply their knowledge in a real-world context.
We have meticulously aligned our activities with the guidelines of the National Education Policy (NEP) 2020, which emphasises a holistic approach to learning. This approach is aimed at developing critical thinking, logical reasoning, and practical skills among students. By integrating these elements into our coding program, we aim to prepare students for the future, equipping them with the necessary skills to navigate and excel in the ever-evolving world of technology.
Our mission is to cultivate a passion for coding and computer science among young learners, making the learning process enjoyable and impactful. We are confident that this series will not only help students grasp the fundamentals of coding but also inspire them to explore the endless possibilities that technology offers.
We invite you to embark on this exciting journey of learning and discovery. Let’s empower the next generation with the skills and knowledge they need to thrive in a digital world.
The NEP Tags
The National Education Policy (NEP) 2020 outlines essential skills, values, dispositions, and learning approaches necessary for students to thrive in the 21st century. This textbook identifies and incorporates these elements throughout its content, activities, and exercises, ensuring students develop coding skills and essential life skills. Referred to as “NEP Tags”, they are defined as follows:
INTEGRATED
CRITICAL THINKING
Art Integration
Bringing creativity and fun into learning by integrating art with computer science and coding
Sports Integration
Using games and sports in daily life to enrich computer-related activities
Holistic & Integrated Learning
Cross-curricular linkages to make learning-experiences more holistic and joyful and meaningful
Critical Thinking
Coding opportunities to apply higher-order skills like algorithmic and computational thinking and problem-solving
HANDS-ON
SDG
Hands-on Activity
Coding opportunities that enable learners to put theoretical knowledge into practice
Sustainable Development Goals
Coding opportunities related to real-world issues and sustainable development
SEL Social Emotional Learning
Developing emotional intelligence and collaboration skills through coding exercises
hands with soap keeps germs away, wearing clean clothes is another way to stay clean. Dirty clothes can collect sweat and germs, so washing them regularly helps keep our skin free of germs and itch.
1 Gather all the clothes you want to wash.
Here are the steps to wash clothes:
2 Sort your clothes by colour. Keep dark-coloured clothes in one pile and white or light-coloured clothes in another pile.
1 Gather all the clothes you want to wash.
3 Check the pockets for tissues, candy wrappers, and other items, and take them out.
2 Sort your clothes by colour. Keep dark-coloured clothes in one pile and white or light-coloured clothes in another pile.
4 Put your clothes in the washing machine, one pile at a time.
Discuss
3 Check the pockets for tissues, candy wrappers, and other items, and take them out.
4 Put your clothes in the washing machine, one pile at a time.
What is the difference between the stage and the backdrop?
Discuss
What is the difference between the stage and the backdrop?
We will be using block-based coding to make computers do things for us.
Block-based Coding
Block-based coding is the language in which we use colourful code blocks to tell computers what to do
Block-based Coding
You must have drawn things on a computer earlier, right?
Discuss: A multi-faceted probing question related to the concept that arouses curiosity
We will be using block-based coding to make computers do things for us.
Did You Know?
Block-based coding is the language in which we use colourful code blocks to tell computers what to do
We are going to use a block-based coding platform called Scratch 3.0 to create code for drawing and shapes.
You must have drawn things on a computer earlier, right?
What happens when you run your project? The Pencil sprite moves quickly and draws the rectangle. Steps to add a delay of 1 second:
Identify and label the components based on the clues given below.
1 Click Control category in the blocks panel.
We are going to use a block-based coding platform called drawing and shapes.
Chapter Checkup
Code Snippets: Complete code for each activity with output facilitating hands-on learning and immediate feedback
A Fill in the blanks.
NEP Tags: To show alignment with NEP skills and values
Did You Know: Interesting facts related to the topic
a I am a character in your project.
2 Drag the inside the repeat block.
e I hold all the blocks for a block category.
b I show you the options to change the name, size, and location of a character.
c I hold colour-coded categories of blocks.
d I am the area where you drag and join the blocks.
Coding Challenge
Open Scratch.
We have completed the script to draw a rectangle. Save this project with the name 'Drawing a Rectangle'.
repeat block. Code Click the Go button We have completed the script to draw a rectangle. 'Drawing a Rectangle'.
Hints menu bar untitled backdrop blocks create
Short exercises between the chapter to pause and assess comprehension
1 In Scratch, we use colourful to create our own games, stories, and drawing.
Identify and label the components based on the clues given below.
Go to the Backdrops pane. Click on Choose a Backdrop option and select Blue Sky.
Coding Challenge
Now, go to the sprites pane. Click on Choose a Sprite option and select the Amon sprite.
The stage will look like the figure below.
2 To create a project in Scratch, you need to click .
3 By default, the name of the Scratch project is .
4 The purple bar at the top of the Scratch editor is called the
Hands-on challenges to encourage and actively engage with the concepts learnt throughout the chapter
Identify and label the components based on the clues given
5 The background of the stage is called the .
Chapter Checkup
2
F Apply your learning.
What
Think and Tell: Analysis, reflection, and text-to-self connection-based prompts for discussion in class
I show you the options to change the name, size, and location of a character. c I hold colour-coded categories of blocks.
e I hold all the blocks for a block category. A Fill in the blanks.
1 Nia is making a Scratch project where she needs to move the dog from left to right. Which block should she use?
I am the area where you drag and join the blocks.
Hints menu bar untitled backdrop blocks create
Chapter Checkup: Chapter-end practice exercises aligned to different levels of Bloom’s Taxonomy
Coding Challenge
Apply your learning: Intellectually stimulating questions designed for higher-order thinking and analysis
1 In Scratch, we use colourful to create our own games, stories, and drawing.
2 To create a project in Scratch, you need to click
e I hold all the blocks for a block category. A Fill in the blanks.
below. What are the other platforms you know of that assist in block-based coding? Think and Tell
Test Papers: Designed to evaluate understanding of core concepts and application of skills
A. Fill in the blanks.
3 By default, the name of the Scratch project is
4 The purple bar at the top of the Scratch editor is called the
Hints menu bar untitled backdrop blocks create
5 The background of the stage is called the F Apply your learning.
1 In Scratch, we use colourful to create our own games, stories, and drawing.
2 To create a project in Scratch, you need to click
3 By default, the name of the Scratch project is
4 The purple bar at the top of the Scratch editor is called the
1 Nia is making a Scratch project where she needs to move the dog from left to right. Which block should she use?
Test Paper (Based on Chapters 1 to 4)
5 The background of the stage is called the F Apply your learning.
1 Nia is making a Scratch project where she needs to move the dog from left to right. Which block should she use? Chapter Checkup
Test Paper (Based on Chapters 1 to 4)
1 In Scratch, the blocks you put together in the script area are called a
A. Fill in the blanks.
2 The is the background of the stage.
1 In Scratch, the blocks you put together in the script area are called a The is the background of the stage.
1 Introduction to Python
• What Is Programming?
• Python
• Data Types
• Variables
2 Operators in Python
• Operators
• Algorithms
• Flowcharts
• Writing a Python Program
• Using Math Library in Python
3 Conditional Statements in Python
• Control Statements
• Conditional Statements
• Solved Examples
• HTML
• Web Browsers
• Basic Structure of an HTML Document
• Structure of an HTML Document
• Basic Terminologies in HTML
• Types of Tags
• Basic Tags in HTML
• More HTML Tags
Cascading Style Sheets
CSS Colour Properties
CSS Font Properties
CSS Border Property
Introduction to Python 1
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.
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 the one which can be easily improved and distributed by anyone. Python is available for download and use at no cost.
4 GUI application creation: Python also supports the creation of Graphical User Interface (GUI) applications.
Did You Know?
Python is named after a famous British comedy group called Monty Python.
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.
• 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 programming language.
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
Think and Tell
Will a syntax error stop a program from running?
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.
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:
print(‘Hello World!’) Hello World!
Do It Yourself 1A
What will be the output of the following code?
Code
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.
Creating a Variable
• In Python, variables are declared and initialised by assigning a value to a variable.
Syntax: variable_name = value
Example:
number = 5
word = “Stars” print(number, word)
5 Stars
• You can also assign a single value to multiple variables at the same time.
Syntax: var1 = var2 = value
Example:
Code
number1 = number2 = 10
print(“number 1 =”, number1) print(“number 2 =”, number2)
number 1 = 10
number 2 = 10
• You can also initialise multiple values to multiple variables in one line.
Syntax: var1, var2 = value1, value2
Example:
Code
number, word = 5, “Stars” print(number, word) 5 Stars
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
5 Variable names are case sensitive.
For example, value, Value, and VALUE are three different variables.
Example: Code
my_variable = 10
My_Variable = 20
MY_VARIABLE = 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:
text1 = input(“Enter your name:”) num1 = input(“Enter your age:”) print(type(text1)) print(type(num1))
Enter your name: Grisha
Enter your age: 10 <class ‘str’> <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
y = “Hello” z = 3.14
result = x + 2.5 print(type(x)) print(type(y)) print(type(z)) print(type(result))
<class ‘int’>
<class ‘str’>
<class ‘float’> <class ‘float’>
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
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.
Output
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
3 Which of the following is a valid variable name?
4 function helps you see the results of your code.
print()
type()
5 A is a reference name given to a location in the computer’s memory.
Data type
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?
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
Operators in Python 2
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 on values.
The values or variables are called operands.
The combination of operands and operators is called an expression.
In the adjoining picture, x, y, and z are operands. The ‘+’ and ‘=’ symbols are 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
Operators
Operands
Operand
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 divided by the second. x / y 33.3333…
Operator Name Description
// Floor Division Divides the operand on the left by the operand on the right and returns the quotient by removing the decimal part. Sometimes, it is also called integer division.
% Modulus (Remainder) Displays the remainder when the first operand is divided by the second.
** Exponentiation (Power)
Assignment Operators
Raises the first operand to the power of the second.
Assignment operators are used to assign values to variables. The following table summarises the various assignment operators:
Operator Description
= Assigns the right-hand side value to the left-hand side variable.
+= Adds the right operand to the left operand and then assigns the result to the left operand.
−= Subtracts the right operand from the left operand and then assigns the result to the left operand.
*= Multiplies the right operand with the left operand and then assigns the result to the left operand.
/= Divides the left operand with the right operand and then assigns the result to the left operand.
%= Calculates the modulus using two operands and then assigns the result to the left operand.
//= Performs floor division on operators and then assigns the value to the left operand.
**= Performs exponential calculation on operators and then assigns 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 side value; otherwise, it returns false.
!= Returns true if the left-hand side value is not equal to the righthand side value; otherwise, it returns false.
Operator Description Example Output
> Returns true if the left-hand side value is greater than the right-hand side value; otherwise, it returns false. x > y True
< Returns true if the left-hand side value is smaller than the right-hand side value; otherwise, it returns false. x < y False
>= Returns true if the left-hand side value is greater than or equal to the right-hand side value; otherwise, it returns false. x >= y True
<= Returns true if the left-hand side value is smaller than or equal to the right-hand side value; otherwise, it returns false. x <= y 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 as well as the right-hand side are true.
x < 5 and x < 10 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 true. not(x < 5 and x < 10) False
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
4 *, /, //, %
5 +, −
6 <, <=, >, >=, ==, !=
Explanation
Multiplication, division, floor division, modulu
Addition, subtraction
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)
Step 2: 16 / 4 + 5
Step 3: 4 + 5
Step 4: 9
Observe in this example that the order of precedence is changed 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.
Did You Know?
Python gives more precedence to arithmetic operators than comparison operators. Within comparison operators, every operator has the same precedence order.
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 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.
3 Dig a small hole in it and place the seed in the hole. Cover the seed with the soil.
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.
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.
4 Use another variable to store the sum, say sum.
5 Initialise sum to 0, i.e., sum = 0.
6 Calculate sum: sum = num1 + num2.
7 Display sum.
8 Stop.
Flowcharts
Symbols Used for a Flowchart
Name of the Symbol
Terminal Box—Start/End
Input/Output
Shape of the Symbol
Did You Know?
Purpose of the Symbol
The term “algorithm” originates from the name of a Muslim mathematician and scientist, Muhammad al-Khwarizmi. He introduced the concept of algorithms and is also known for inventing algebra.
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.
A flowchart consists of a number of standard symbols. The following symbols indicate various elements of a flowchart:
It is used at the beginning and end of a flowchart.
It is used to provide input and output information.
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.
Algorithm:
Step 1: Start.
Step 2: Read temperature in Fahrenheit, say 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.
Step 5: Stop.
Write an algorithm and draw a flowchart to calculate the perimeter of a rectangle.
Flowchart:
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”)
Let us analyse the code:
Hello World
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:”)
print(str)
Let us analyse the code:
Enter any string: Ritu Singh Ritu Singh
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
val1 = 100.99
val2 = 76.15
sum = float(val1) + float(val2)
print(“The sum of given numbers is:”, sum)
Let us analyse the code:
Output
The sum of given numbers is: 177.14
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. What is a console?
Think and Tell
Write a Python program to convert Celsius to Fahrenheit.
Using Math Library in Python
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.
x = min(5, 10, 25)
y = max(5, 10, 25) print(x)
The abs() function: The abs() function returns the absolute (positive) value of a specified number.
x = abs(−7.25) print(x)
The pow() function: The pow(x, y) function returns the value of x raised to the power of y (xy).
x = pow(4, 3) print(x)
The sqrt() function: The sqrt() function returns the square root of a given number.
Code Output x = sqrt(81) print(x) 9
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)?
2 Which of these is the floor division operator?
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,
4 What is the answer of this expression: 22 % 3?
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.
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?
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.
Conditional Statements in Python 3
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”.
Syntax: if condition:
# Statement to execute if condition is true
Did You Know?
Conditional statements in programming are like decisionmaking in life, where “if” is the choice, “else if” is the backup plan, and “else” is the fallback.
The flowchart for the if statement is as follows:
if(expression)
num = 10 if num > 9: print(“number is greater than 9”)
Explanation:
number is greater than 9
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: (_____)statement
Indentation
Example: Code Output
num1 = 50
num2 = 100 if num1<num2: print(“num1 is less than num2”)
Think and Tell
What happens if there is no indentation in a Python program?
File “demo_if_error.py”, line 4 print(“x is greater than y”)
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’:
The corrected code is as follows:
num1 = 50
num2 = 100 if num1<num2: print(“num1 is less than num2”)
The if…else Statement
num1 is less than num2
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 else:
#Statements to be executed if condition becomes False
The flowchart for the if-else statement is as follows:
Discuss
What is the role of the else statement in conditional statements?
Example:
num = 7 if num > 9: print(“number is greater than 9”) else: print(“number is not greater than 9”)
Explanation:
number is not greater than 9
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.
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:
Statement2
elif condition 3:
Statement3
else:
Did You Know?
Python allows you to chain multiple comparisons together, making complex conditions more readable. For example, if 1 <= x <= 10.
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:
Example:
Code Output
num1 = 50 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:
num1 is less than num2
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:
statement 3 else: statement 4
The flowchart for the nested if statement is as follows:
Explanation:
• The outer if statement checks condition1.
• If condition1 is True, the indented code block below it executes. This block can contain another if statement, creating a nested condition.
• 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
age = 12
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:
Output
You are too young to drive.
• 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 if number > 0:
Given number is positive
print(“Given number is positive”) else:
print(“Given number is negative”)
Example 2
Write code in Python to check whether a given number is divisible by 5 or not.
Code Output
number = 50 if number % 5 == 0:
print(“Given number is divisible by 5”) else:
print(“Given number is not divisible by 5”)
Example 3
Given number is divisible by 5
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, 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: “))
subject2 = float(input(“Enter marks for subject 2: “))
subject3 = float(input(“Enter marks for subject 3: “))
total_marks = subject1 + subject2 + subject3
average = total_marks / 3
print(“Average is:”, average) if average >= 80:
print(“You deserve a treat!”) else:
print(“Work hard in the next cycle.”)
Coding Challenge
Enter marks for subject 1: 68
Enter marks for subject 2: 52
Enter marks for subject 3: 72
Average is: 64.0 Work hard in the next cycle.
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
81 to 90
71 to 80
61 to 70
51 to 60
41 to 50
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
c To execute when the condition is false
b To handle exceptions
d To terminate the program
2 Which control statement is used to check multiple conditions until one of them is true?
a if Statement
c while Loop
3 In Python, which keyword is used to define an ‘if’ statement?
a when
b for Loop
d if-elif-else Statement
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
c Indentation error
5 What is the output of the given code?
x = 15
if x > 10:
print(“Above 10”) else:
print(“Below 10”)
a Above 10
c Error
b a is greater than b
d None of these
b Below 10
d None of these
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.
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.
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 Suppose you are creating a discount program for a store. Customers of 60 years of age or above are eligible for a discount. On top of the senior discount, members also receive an additional benefit. Write a Python program 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.
Introduction to HTML 4
The internet has become an inseparable part of our daily lives. We use the internet to visit various websites using a mobile phone, a laptop, or a computer. Have you ever thought how these websites are created?
Websites are a collection of many web pages. We use various computer languages or technologies to create these web pages. HTML is one of the technologies that is used to create web pages of a website. This chapter will introduce you to HTML.
HTML
HTML stands for HyperText Markup Language. It helps you to display colourful text, images, and attractive backgrounds to your web page
Did You Know?
HTML was designed and released by Tim BernersLee in the year 1993.
Advantages of HTML
Some advantages of HTML are:
• Easy to learn and use: HTML is a simple and easy language to learn.
• Platform-independent: HTML can create web pages that run on any device (computers, mobiles, and tablets).
• Helps to add graphics: HTML helps add video, image, and audio files to web pages. This feature enhances the experience for website visitors.
• Helps to create hyperlinks: Using HTML, you can link various web pages with each other. It allows users to click text or images and navigate to various websites.
Disadvantages of HTML
Some disadvantages of HTML are:
• Lack of interactivity: It cannot be used to create dynamic web pages with features such as user input and forms. However, you can enhance this capability with the use of Cascading Style Sheets, or CSS.
• Security concerns: HTML pages are vulnerable to security risks, such as SQL Injection and Cross-Site Scripting.
• Version dependence: New versions of HTML are regularly released as the language changes constantly. This implies that websites built using earlier HTML versions might not function properly with more recent browsers.
Below are some of the advantages and disadvantages of HTML. Write A for Advantage and D for Disadvantage.
1 Platform-independent
2 Security concerns
3 Easy to learn and use
4 Used to create hyperlinks
5 Lack of interactivity
Web Browsers
A web browser is a software application that processes HTML and other web technologies to display web pages to users. When a user types any website address in the address bar of a web browser, the browser sends a request to the server asking for the HTML code of the specific web page. The browser then processes the HTML markup and displays the required web page.
Some examples of web browsers are:
Basic Structure of an HTML Document
HTML documents contain two sections:
Header section: It contains information about HTML documents, such as page title, HTML, and meta tags.
Body section: It contains all the visible elements that will be displayed on the web page.
Did You Know?
A URL is a website address. A URL is a group of letters and numbers that instructs your web browser where to look for the page you want to view.
Designing Web Pages in HTML
Basic steps for designing a web page in HTML are:
1 Open an editor: There are many editors that can be used to write HTML code such as Notepad, Notepad++, and TextEdit. You can use any of these to write your HTML code.
2 Write HTML code: Use the basics of HTML to write the code for your web page. There are many tags in HTML to help you add colourful text, images, and audio, in your web page.
3 Save file: After writing the complete HTML code, save the file as ‘file_name.html’, using the Save as option.
4 Open a browser and check the web page: Test the result of the HTML code by opening the HTML file using a web browser such as Microsoft Edge or Google Chrome.
Do It Yourself 4B
Match the following.
Structure of an HTML Document
To create an HTML document, you need to know about a few essential elements. These elements are fundamental to creating a basic HTML document structure. Let us learn about them.
<!DOCTYPE html>
The <!DOCTYPE html> declaration is part of HTML5 and is used to indicate that you are using the HTML5 standard. It is not a tag in HTML; however, it is an important component of the HTML document.
• The <!DOCTYPE html> tag is referred to as the document type declaration (DTD). Technically, <!DOCTYPE > is neither a tag nor an element.
• This tag informs the browser about the document type.
• This tag is an empty element that does not have a closing tag and must not contain any content.
<html> Tag
The <html> tag is the root element of an HTML document. This tag contains all other HTML elements and is the starting point for creating an HTML page. You can see this tag at the beginning of an HTML document.
• The <html> tag informs the browser that this is an HTML document.
• The <html> tag is a container tag which requires the beginning and ending tags.
<head> Tag
The <head> tag contains metadata (data about data) and other information about the HTML document.
• The head of an HTML document is a section of the document whose content is not displayed in the browser when the page loads.
• It contains the 'behind the scenes' elements for a web page.
• It contains information about the HTML document.
• The head section of an HTML document contains the title of the web page it opens to, with the help of the <title> tag.
<title> Tag
When you visit a website, the title is shown at the top of your browser and contains the title of the active web page. The <title> tag provides a suitable title for the entire HTML document.
• When a web page is saved as a favourite or a bookmark, it appears at the top of the browser window and provides the page with a suitable name.
• A strong page title on a website ensures a higher position in search results. As a result, we must always include appropriate keyword phrases.
• The <title> element must be positioned between the <head> and </head> tags.
• There can only be one title element per document.
<body> Tag
The primary content of an HTML document that displays on the browser is specified by the <body> tag. Headings, text, paragraphs, images, tables, links, videos, etc., can all be included in a <body> tag.
• The <body> tag must appear immediately following the <head> tag.
• All HTML documents must have this tag, which should be used only once overall in a document.
Here is an example of how these elements are used:
<!Doctype html> <html> <head> <title>My Web Page</title> </head> <body> … </body> </html>
Note that the <html> element encloses the whole document, the <head> element contains metadata, the <title> sets the page title, and the <body> element holds the visible content.
Basic Terminologies in HTML
Before you start writing your HTML code, you need to know about a few terms that you can use in your HTML code. Let us look at these one by one.
Tags
A tag is a keyword that tells the browser how to display a piece of text or content. Tags are written in pairs, with an opening tag and a closing tag. The opening tag starts with < and ends with >, while the closing tag includes </ followed by the tag name and then >.
Example: <p>, </p> <b>, </b>, <br>, etc., are the tags in HTML.
Elements
An element is a building block of an HTML. This element is defined by a start tag, some content, and an end tag. The content of the element can be text, other HTML elements, or a combination of both.
Example: <title>…</title> is an element in an HTML document.
Attributes
HTML attributes are the modifiers of HTML elements. They are the keywords that hold extra information about an element or a tag. An attribute is always placed in the opening tag of an element, and it provides additional styling (an attribute) to the element.
Syntax: <tag attribute=”value”> …content of tag… </tag>
Example: <font color= ‘’red’’> This is my first HTML document. </font>
Types of Tags
There are mainly two types of tags in HTML: Container tags and Empty tags.
Container Tags: These tags consist of an opening tag as well as a closing tag. This start tag and end tag pair are known as the ON and OFF tags and are used to open and close the document.
Syntax: <tag_name>.......</tag_name>
Example: <B> tag is a container tag in HTML.
Empty Tags: An empty tag is a tag without a closing tag.
Syntax: <tag_name>
Example: <img> tag is an empty tag in HTML.
Basic Tags in HTML
Let us learn about some basic tags in HTML through an interactive project on the topic, "The Life Cycle of a Butterfly."
Paragraph: The <p> tag in HTML is used to define a paragraph of text. This tag is one of the text formatting tags in HTML and is used for structuring and formatting text content on a web page.
Syntax: <p>…</p>
Example: Code
<p>A butterfly is a beautiful insect.</p> A butterfly is a beautiful insect.
Heading tags: These tags are used to create headings. The headings are used to arrange the contents of a web page so that the users can easily read and understand the content flow on the web page. There are six heading tags in HTML, <h1>, <h2>, <h3>, <h4>, <h5>, and <h6> for various levels of headings.
Syntax: <hn>…</hn>, where n can be any number from 1 to 6
Example:
<h1>Discover the Life Cycle of a Butterfly</h1> Discover the Life Cycle of a Butterfly
Bold: This tag is used to highlight an important text. The bold text is typically displayed in a darker font.
Syntax: <b>…</b>
Example:
Code Output
<p><b>butterfly</b></p> butterfly
Italic: The italic tag is used to highlight specific words or phrases. The italic element is displayed as a slanted font.
Syntax: <i>…</i>
Example:
<p><i>vibrant colours</i></p> vibrant colours
Underline: This tag is used to indicate that the text between the opening and closing tags should be displayed with an underline.
Syntax: <u>…</u>
Example:
<p><u>delicate wings</u></p> delicate wings
Line break: This tag is used to insert a new line into the text. The line break tag is also known as the <br> tag.
Syntax: <br>
Example:
Code Output
<h1>Discover the Life Cycle of A Butterfly</h1>
<p>The journey begins as a tiny egg.<br>
The egg hatches into a larva.<br>
The caterpillar transforms into a pupa.<br>
Finally, the pupa emerges as a butterfly.<br> </p>
Discover the Life Cycle of A Butterfly
The journey begins as a tiny egg.
The egg hatches into a larva.
The caterpillar transforms into a pupa.
Finally, the pupa emerges as a butterfly.
Horizontal Line: This tag is used to insert a horizontal line on a web page. The horizontal line element is used to create divisions on a web page.
Syntax: <hr>
Example:
Code Output
<p>A normal horizontal line:</p> <hr>
<p>A horizontal line with a height of 10 pixels:</p> <hr style=”height:10px”>
Discuss
A normal horizontal line:
A horizontal line with a height of 10 pixels:
What is the difference between tags and elements? Do It Yourself 4C
Match the tags with their meanings.
Tag Meaning
hr Italics
br Horizontal rule
b Underline
i Line break
u Bold
A style in CSS is a set of rules that define the appearance of HTML elements.
More HTML Tags
You have learnt about some basic tags in the previous section. Now, let us learn about some more HTML tags.
<em> Tag: This tag is used to emphasise text and is typically displayed in italics.
Syntax:
<em>Block of text</em>
Code Output
<p>This transformation is called <em>metamorphosis</em>. <br> It is like a magical change!</p>
This transformation is called metamorphosis. It is like a magical change!
<strong> Tag: This tag is used to represent strongly emphasised text and is typically displayed in bold.
Syntax:
<strong>Block of text</strong>
Code Output
<p>A <strong>butterfly</strong> is a beautiful insect.</p>
A butterfly is a beautiful insect.
<sub> Tag: This tag is used to represent text as a subscript. A subscript is the text that is below the baseline of the surrounding text. For example, 2 in H2O is a subscript.
Syntax:
<sub>Block of text</sub>
Code Output
<p>The journey begins as a tiny <sub>egg</sub> attached to a leaf.</p>
The journey begins as a tiny egg attached to a leaf.
<sup> Tag: This tag is used to represent text as a superscript. A superscript is the text that is above the baseline of the surrounding text. For example, 2 in E = mc2 is a superscript.
Syntax:
<sup>Block of text</sup>
Code Output
<p>Finally, the pupa emerges as a fully grown <sup>adult</sup> butterfly.</p>
Finally, the pupa emerges as a fully grown adult butterfly.
<section> Tag: This tag is used to define the grouping of content in a document. This tag makes the content more organised and meaningful, which then helps understand the content in a better way.
Syntax:
<section>Block of text</section>
Code Output
<section>
<h3>What is a Butterfly?</h3>
<p>A butterfly is a beautiful insect <br> known for its vibrant colours and delicate wings.</p> </section>
<section>
<h3>How it starts?</h3>
<p>But did you know that a butterfly goes through<br> several stages in its life?</p> </section>
What is a Butterfly?
A butterfly is a beautiful insect known for its vibrant colours and delicate wings. How it starts?
But did you know that a butterfly goes through serveral stages in its life?
<article> Tag: This tag is used to represent a self-contained composition, such as a blog post or a news article. Syntax:
<article>Block of text</article>
Code Output
<article> <h3>Metamorphosis</h3>
<p>This transformation is called <em>metamorphosis</em>.<br>
It is like a magical change!</p> </article>
Metamorphosis
This transformation is called metamorphosis. It is like a magical change!
Let us combine all these snippets of code and develop our project, The Life Cycle of a Butterfly.
Code
<!DOCTYPE html> <html> <head>
<title>The Life Cycle of a Butterfly</title> </head> <body>
<h1>Discover the Life Cycle of a Butterfly</h1> <section>
<h2>Introduction</h2> <article>
<h3>What is a Butterfly?</h3> <p>A <b>butterfly</b> is a beautiful insect known for its <i>vibrant colours</i> and <u>delicate wings</u>. But did you know that a butterfly goes through several stages in its life?
</p> </article> <article> <h3>Stages of a Butterfly</h3>
Code
<p>A butterfly’s life consists of four main stages:</p> <p><strong>Egg:</strong> The journey begins as a tiny <sub>egg</sub> attached to a leaf. <br></p> <p><strong>Larva:</strong> The egg hatches into a <strong>larva</strong>, also known as a caterpillar.<br></p> <p><strong>Pupa:</strong> The caterpillar transforms into a <strong>pupa</strong>, enclosed in a chrysalis.<br></p> <p><strong>Adult:</strong> Finally, the pupa emerges as a fully grown <sup>adult</sup> butterfly.<br></p> </article> <article> <h3>Metamorphosis</h3> <p>This transformation is called <em>metamorphosis</em>. It is like a magical change!</p> </article> </section> </body> </html>
Output
Discover the Life Cycle of a Butterfly Introduction
What is a Butterfly?
A butterfly is a beautiful insect known for its vibrant colours and delicate wings. But did you know that a butterfly goes through several things in its life?
Stage of a Butterfly
A butterfly’s life consists of four main stages:
Egg: The journey begins as a tiny egg attached to a leaf.
Larva: The egg hatches into a larva, also known as a caterpillar.
Pupa: The caterpillar transforms into a pupa, enclosed in a chrysalis.
Adult: Finally, the pupa emerges as a fully grown adult butterfly. Metamorphosis
This transformation is called metamorphosis. It is like a magical change!
Coding Challenge
Create an HTML web page on the topic: India–A Sub-continent. The web page should contain information about our country, its history, some prominent states and their capitals, the culture followed in our country and the heritage for which our country is known.
Use the tags that you have learnt so far.
Arrange the information on the web page beautifully.
Chapter Checkup
A Fill in the blanks.
Hints
1 Tags are special lines or words of code in HTML, enclosed in .
2 Attributes provide extra information about HTML
3 Some examples of web browsers are Mozilla Firefox, Google Chrome, and .
4 The tag contains the main content of the web page.
5 The <p> tag is used for
B Tick () the correct option.
1 What is HTML?
a A programming language
c A style sheet
2 Which of the following is a valid HTML tag?
a <p>
c <br>
3 What is the purpose of the <hr> tag?
a To create a paragraph
c To create a link
4 What is an attribute?
a starting point for creating an HTML page
c Additional information that can be added to a tag
b A markup language
d A framework
b <h1>
d All of these
b To create a heading
d To create a horizontal line
b A piece of text that appears outside a tag
d None of these
5 Which tag is used to define grouping of content in a document?
a </p>
c <section>
b <strong>
d <head>
C
1 I’m used to view web pages.
2 I’m a tag referred to as the document type declaration, or DTD.
3 I’m used to provide data about an HTML element.
4 I’m a markup language.
5 I’m a tag used to display the text in italic.
D Write T for True and F for False.
1 HTML is a markup language for creating web pages.
2 Browsers such as Chrome and Firefox are used to display web pages.
3 HTML document is written using special syntax within square brackets.
4 The <b> tag is used to create line breaks in an HTML document.
5 The closing tag should have a closing bracket at the end.
E Answer the following questions.
1 What is HTML? Write its features.
2 What is a web browser?
3 Differentiate between container tags and empty tags.
4 Write the basic structure of an HTML document.
5 Differentiate between the <sub> tag and the <sup> tag.
F Apply your learning.
1 Shreya wants to underline text in the HTML code. What does she need to do?
2 Anmol wants to divide his web page into several sections. Which tag can he use to do so?
3 You are asked to create a web page on the topic ‘Renewable Energy Resources’. What basic tags will you make use of to make the web page visually appealing?
4 Create a web page showing information about your favourite sports persons. Separate each section of the web page sport-wise and then display the information.
5 Create an HTML page with the title as ‘Formulae in Maths’. The page should contain the area of a circle, square, rectangle, and a triangle.
Introduction to CSS 5
When you write a story, you create a clear plot, interesting characters, and a series of events to keep the readers engaged. But what if the story was presented in a plain text document, with no formatting or visuals? It would not be interesting, right? This is also the case with the web pages created using HTML only. HTML provides the content and structure, but to add a style – the colours, fonts, layouts, and everything that makes a web page visually appealing and engaging, CSS is required.
Cascading Style Sheets
Cascading Style Sheets (CSS) is a language used to define the presentation of a document written in a markup language like HTML. This includes aspects like background colour, font colour, font size, layout, margins, borders, text decorations, and many more things. CSS is mainly used to enhance the look of web pages by applying various formatting styles to the elements or the entire web page. It allows us to apply a style to a specific element of a web page, an entire web page, or all the web pages of a website. It makes it easy to add or change the look and feel of web pages without re-creating them. The main purpose of CSS is to separate the styles from the structure of web pages.
Syntax of CSS
Did You Know?
Håkon Wium Lie proposed CSS at CERN on October 10, 1994.
CSS consists of style rules. Style rules are made up of selectors, properties, and values. All style rules are enclosed within curly brackets {}.
The syntax for using CSS is as follows:
selector{property: value;} where,
• a selector is any HTML element to which you want to apply a style, like <p>. Always remember that an HTML element is written without angle brackets while creating CSS style rules.
• a property is like an HTML attribute, like colour, which adds additional features to an element.
• a value is similar to an attribute’s value assigned to a CSS property. Every CSS property has a value associated with it. The colon (:) sign is used to assign a value to a property. When using multiple properties in a style rule, each property-value pair is separated by a semicolon (;) sign.
Let us now create a CSS style rule to change the font size and font colour of the <p> element.
p{font-size: 14px; color: blue}
In the preceding CSS rule, p is an HTML element, font-size and color are the CSS properties, and 14px and blue are the values assigned to these properties.
Methods to Use CSS
There are three methods to use CSS in an HTML document: inline, internal, and external.
Inline CSS
The purpose of inline CSS is to apply CSS style rules only to a particular element in an HTML document. The style attribute is used within the opening tag of the element to which you want to apply CSS. In this method, there is no need to use curly brackets. For example:
Code Output
<p style=”font-size: 20px; color: green”>
I am a paragraph.
</p>
Internal CSS
I am a paragraph.
If you want to apply CSS style rules to multiple elements or an entire web page, then the internal CSS method is used. The <style> and </style> tags of HTML are used for this purpose. You should use the <style> tag within the <head> and </head> tags. It improves the loading process of the web page. However, you can use the <style> tag anywhere on a web page. For example:
Code Output
<html> <head> </head> <style>
p {font-size: 20px; color: green;} </style> <body>
<p> I am a paragraph. </p> </body>
</html>
External CSS
I am a paragraph.
The external CSS method allows you to apply style rules to multiple web pages of a website. In this method, the CSS style rules are written in a separate file, and this file is saved with the .css extension. You need to add the reference to this CSS file to the web page, using the <link> tag. The <link> tag can be written in the <head> section of the web page. For example:
<link rel=”stylesheet” href = “style.css”>
The rel attribute of the <link> tag is used to specify that the linked document is a stylesheet. For this purpose, a stylesheet value is assigned to this attribute. The href attribute is used to specify the Uniform Resource Locator (URL) of the CSS file. Ensure that the CSS file is saved at the same location where you had saved the HTML file. Otherwise, you need to provide the complete path of the CSS file.
Write the following code in the editor and save the file by assigning it the name “style.css”.
p{font-size: 20px; color: green;}
Let us create an HTML web page containing the <link> tag:
Code
<html> <head>
<link rel=”stylesheet” href = “style.css”> </head> <body>
<p> I am a paragraph. </p> </body> </html>
Discuss
Output
I am a paragraph.
Which method of adding CSS to an HTML document is better in your point of view?
1 Write T for True or F for False.
a CSS stands for Cascading Style Selector.
b CSS is used to define the structure of a web page.
c The colon (:) sign is used to assign a value to a property.
2 Identify the mistake in the following code and rewrite it correctly. <link href=”stylesheet” rel = “style.css”>
CSS Colour Properties
CSS provides two colour properties: color and background-color.
Property Description
Example
color It applies colour to the text of an element. This property takes the name of the colour as a value. color: red
background-color It applies a colour to the background of an HTML document. background-color: green
You can also provide the hexadecimal code of the colour instead of the colour name. The hexadecimal code starts with the # symbol and is made up of six characters (including 0–9 and A–F). They represent the intensity of red, green, and blue (RGB) components of a colour.
In the 6-digit code, the first 2 digits are used for the red colour, the next two digits are used for the green colour, and the last 2 digits are used for the blue colour. For example, the following hexadecimal code represents the black colour, as all the values are 0: #000000—black
The following table contains both types of codes for some colours:
Colour Name 6-digits Hexadecimal Code
Black #000000
White #ffffff
Red #ff0000
Blue #0000ff
Green #00ff00
Yellow #ffff00
CSS Font Properties
Did You Know?
Hexadecimal codes can be of 3-digits if both the digits of red, green, and blue are the same. For example, #556677 can be written as #567 #ffaabb can be written as #fab.
CSS font properties are used to format text on web pages. Some of the font properties are as follows:
Property
Description
font-family It applies various font styles to the text according to the specific font family, like Arial and Comic Sans MS.
Example
Arial or Comic Sans MS
font-size It sets the size of the text in pixels, points, percentage, or em. 20px or 20pt or 20% or 1.5em
font-weight It specifies the thickness of characters. normal or bold or bolder or lighter
text-align It aligns the text. left or right or justify or center
text-decoration It sets the decoration of text. underline or overline or line-through
line-height It maintains the spacing between the lines. pixels or points or percentage or em
Example:
Code Output
p{
font-family: comic sans ms; font-size: 25px; font-weight: bolder; text-align: right; text-decoration: underline; line-height: 1.5 em;
}
CSS Border Property
I am a paragraph.
The border property allows you to add a border around an HTML element. It is a shorthand property that allows you to set the width, style, and colour of all four borders (top, right, bottom, and left). The syntax of the border property is:
div {
border: border-width border-style border-color;
}
For example, the following code sets a 5-pixel solid black border around all sides of the <div> element.
div {
border: 5px solid #333333;
}
Did You Know?
The <div> tag in HTML is a generic container used to group other HTML elements together.
You can also specify border-width, border-style, and border-colour properties individually. For example:
Code
div {
border-width: 5px; border-style: solid border-color: #333333
}
Output
This is div
You can also provide various border styles, like dotted, double, dashed, and solid, to an element. Some 3-dimensional border styles are groove, ridge, inset, and outset.
Let us create a web page using some of the properties you have learnt so far.
Code
<html>
<head>
<title>English Word Meanings</title>
<style>
body {
font-family: comic sans ms;
line-height: 1.6; }
h1 { text-align: center; color: #0066cc; }
h2 { color: #009933; }
</style> </head> <body>
<h1>Word Meanings</h1>
<h2>Word 1: Curious</h2>
<p>Meaning: Eager to know or learn something.</p>
<p>Example: The students were curious about the new lesson.</p>
<h2>Word 2: Magnificent</h2>
<p>Meaning: Extremely beautiful, elaborate, or impressive.</p>
<p>Example: The castle had a magnificent view of the mountains.</p>
<h2>Word 3: Ponder</h2>
<p>Meaning: To think about something carefully and thoroughly.</p>
<p>Example: She sat by the window, pondering the mysteries of the universe.</p> </body> </html>
Output
Word Meanings
Word 1: Curious
Meaning: Eager to know or learn something.
Example: The students were curious about the new lesson.
Word 2: Magnificent
Meaning: Extremely beautiful, elaborate, or impressive.
Example: The castle had a magnificent view of the mountains.
Word 3: Ponder
Meaning: To think about something carefully and thoroughly. Example: She sat by window, pondering over the mysteries of the universe.
Match the CSS property with its possible value.
CSS Property Value
background-color 14pt
font-size red
text-align double
text-decoration justify border-style overline
Chapter Checkup
A Fill in the blanks.
Hints .css # style font-weight structure
1 The main purpose of CSS is to separate the styles from the of the web pages.
2 rules are made up of selectors, properties, and values.
3 CSS file is saved with the extension.
4 The property of CSS specifies the thickness of characters.
5 The symbol is used at the beginning of hexadecimal code.
B Tick () the correct option.
1 Which of the following brackets is used to enclose style rules with a selector? a {} b [] c () d <>
2 Which of the following is not a method of using CSS in an HTML document? a Inline b Outline c Internal d External
3 Hexadecimal codes are made up of: a six characters b four characters c two characters d eight characters
4 What does R stand for in RGB? a Rich b Red c Real d Rose
5 The property sets the size of the text in pixels, points, percentage, or em. a font-family b font-size c font-weight d text-align
1 I’m a sign used to assign a value to a CSS property.
2 I’m a method used to add CSS to an HTML file to apply the style to a single element.
3 I’m a CSS property that is used to apply colour to the text of an element.
4 I’m one of the font properties used to maintain spacing between lines.
5 I’m the method of applying CSS in which the style rules are defined in a separate file.
D Write T for True and F for False.
1 A property is like an HTML attribute.
2 The purpose of inline CSS is to apply CSS style rules only to a particular element in an HTML document.
3 The rel attribute is used to specify the Uniform Resource Locator (URL) of the CSS file.
4 The border property allows you to add a border around an HTML element.
5 You cannot save the CSS style in a separate file.
E Answer the following questions.
1 What is CSS?
2 What does CSS consist of? Mention the syntax of CSS.
3 Write the CSS style rule to set the font colour of the <H1> tag.
4 Mention the various values of the border-style property.
5 Name the three methods of using CSS style sheets.
F Apply your learning.
1 Create a web page to display the text within the <div> tag. The background colour of the <div> should be red, and the font family should be Arial.
2 Sangeeta has created a website with 20 web pages. After creating the website, she realised that the look and feel of the website were not up to the mark. She decided to change the look and feel of all web pages. Suggest her the best method to quickly apply CSS to all the web pages.
3 Romi wants to align the text on to the right edge on a web page. Which CSS property should she use to do so?
4 Create a .css file and specify the properties of the <font> element in it. Use the external method to use this file in the HTML code.
5 Sharvi wants to create an HTML document and apply the border property to it. Which CSS property should she use to do so?
Test Paper (Based on Chapters 1 to 5)
A. Fill in the blanks.
1 The combination of operands and operators is called an . 2 refers to the space at the beginning of a code line.
3 A is a software application that is used to display web pages.
4 In the 6-digit hexadecimal code for a colour, the first 2 digits are used for the colour.
B. Tick () the correct option.
1 Which CSS property is used to specify the thickness of characters.
a Font-family b Font-size
c Font-color d Font-weight
2 Which tag is used to emphasise text and display text in italics?
a <h2> b <p>
c <em> d <strong>
3 Which of the following has the highest precedence in an expression?
a Exponential b Addition
c Multiplication d Parentheses
4 function helps you see the results of your code.
a print() b input()
c type() d output()
C. Write T for True and F for False.
1 Python is case-sensitive.
2 You need not follow the operator precedence in Python.
3 The decision box is used in a flowchart when a condition is applied in the process.
4 You cannot use an if-statement inside another if-statement in Python.
D. Answer the following questions.
1 What do you mean by cross-platform compatibility in Python?
2 What is if-else statement? Give syntax.
3 Differentiate between empty and container tags in HTML.
E. Apply your learning.
1 Amisha wants to fence her rectangular garden with braided wire. The garden measures 12 metres in length and 8 metres in width. Braided wire costs ₹25 per metre. How much will it cost Amisha to purchase enough wire to fence the entire garden perimeter? Create a Python program to calculate the amount.
2 Preeti has created a web page on the topic, “Soil and its types.” She has used HTML tags. However, she feels that there is no style applied to the text of the web page. What can she do to improve the aesthetics of the web page?
3 Riya’s teacher has asked her to create a web page for the Robotics club in the school. She wants to give a nice background colour to the web page and a border around the text. Which CSS properties she can use to enhance the looks of her web page?
About the Book
This coding book is supplementary to the main “Mel and Conji” content book. This book represents a 21st-century approach to learning coding concepts and developing computational thinking and problem-solving skills. To prepare students for the digital age, the curriculum is interwoven with well-thought-out concept progression, real-life examples, and practice problems.
Special Features
• Project-based learning: Engaging hands-on projects encouraging practical application of computer science and coding.
• NEP Tags: To showcase alignment with NEP skills and values.
• Code snippets: Complete code for each activity with output facilitating hands-on learning and immediate feedback.
• Coding challenges: Includes projects through which learners can demonstrate their learning outcomes in coding and computer science.
• Test Papers: Designed to evaluate understanding of core concepts and application of skills.
About Uolo
Uolo partners with K-12 schools to provide technology-enabled learning programs. We believe that pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. Uolo is trusted by over 15,000+ schools across India, Southeast Asia, and the Middle East.
ISBN 978-81-979364-1-8