G8_Coding_AY25

Page 1


Revised Edition

Computer Science Tekie

Python III Web Development III

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 III Web Development III

ISBN: 978-81-979364-8-7

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

GAMES

Here are the steps to wash clothes:

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.

2 Drag the block to after the repeat block. Code

3 Check the pockets for tissues, candy wrappers, and other items, and take them out.

Discuss What is the difference between the stage and the backdrop?

4 Put your clothes in the washing machine, one pile at a time.

Discuss

What is the difference between the stage and the backdrop?

Click the Go button

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.

Block-based Coding

We will be using block-based coding to make computers do things for us.

Block-based coding is the language in which we use colourful code blocks to tell computers what to do

Block-based Coding

Did You Know?

You must have drawn things on a computer earlier, right?

We are going to use a block-based coding platform called Scratch 3.0 to create code for drawing and shapes.

Identify and label the components based on the clues given

Did You Know: Interesting facts related to the topic

Block-based coding is the language in which we use colourful code blocks to tell computers what to do

You must have drawn things on a computer earlier, right?

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

a  I am a character in your project.

What happens when you run your project? The Pencil sprite moves quickly and draws the rectangle. Steps to add a delay of 1 second: 1 Click Control category in the blocks panel. 2 Drag the inside the repeat block. Code

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.

We have completed the script to draw a rectangle. Save this project with the name 'Drawing a Rectangle'.

d  I am the area where you drag and join the blocks.

Coding Challenge

 Open Scratch.

Hints menu bar  untitled  backdrop  blocks  create

HANDS-ON 2

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

Hands-on challenges to encourage and actively engage with the concepts learnt throughout the chapter

We have completed the script to draw a rectangle. 'Drawing a Rectangle'. Identify and label the components based on the clues given HANDS-ON

4 The purple bar at the top of the Scratch editor is called the .

5 The background of the stage is called the

2

F Apply your learning.

Chapter Checkup

What are the other platforms you know of that assist in block-based coding? Think and Tell

Think and Tell: Analysis, reflection, and text-to-self connection-based prompts for discussion in class

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?

Hints menu bar  untitled  backdrop  blocks  create

Chapter Checkup: Chapter-end practice exercises aligned to different levels of Bloom’s Taxonomy

Apply your learning: Intellectually stimulating questions designed for higher-order thinking and analysis

Test Papers: Designed to evaluate understanding of core concepts and application of skills

A. Fill in the blanks.

1 In Scratch, we use colourful to create our own games, stories, and drawing.

Chapter Checkup

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

e  I hold all the blocks for a block category. A Fill in the blanks. 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.

1 Nia is making a Scratch project where she needs to move the dog from left to right. Which block should she use?

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

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?

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.

1 In Scratch, the blocks you put together in the script area are called a

2 The is the background of the stage.

2 The is the background of the stage.

• Introduction to Python

• Python Data Types

• Variables

• Operators

• Conditional Statements

• Iterative Statements

• Strings

• String Manipulation in Python

• What Is HTML?

• Basics of HTML

• Basic Tags of HTML

• Understanding CSS

• What Are HTML Forms?

• Form Structure

• Creating and Displaying a Form

• Form Attributes

• Form Validation

• Setting Properties of a Form Using Internal CSS

• Lists

• Tuples

• Difference Between Lists and Tuples

• Adding Images

• Creating Links

Adding Audio

Adding Video

Fundamentals of Python 1

Introduction to Python

Python is a dynamic programming language that is high-level, interpreted, and focused on code readability

Guido van Rossum, a developer, released it in 1991. Python is one of the world’s most popular and fastest-growing programming languages. It is a sophisticated, adaptable, and user-friendly programming language. It is widely used in many organisations since it supports a variety of programming paradigms. It also manages memory automatically.

Features of Python Language

Following are the features of Python language:

• Free and Open Source: Python is free and open-source software, which means you can download, use, and distribute it without cost.

• High-level Language: Python is a high-level programming language.

• Interpreted: Python is an interpreted language. Unlike C and C++, there are no distinct compilation and execution steps. It can run the application directly from the source code.

• Simple and Easy to Learn: Python is a very simple and easy language, which makes it a popular choice for both students and experienced programmers.

• Platform Independent: Python can be used on a variety of operating systems, including Linux, Windows, Macintosh, Solaris, and others.

• Dynamic Typing: Python defines data types dynamically for the objects according to the value assigned. Also, it supports dynamic data types.

Python Syntax

The rules that define the structure of a language are referred to as syntax.

• Like other programming languages, Python also has symbols, punctuation, and words.

• Python is case-sensitive. This means that ‘nUm,’ ‘Num,’ and ‘num’ are all considered different things in Python.

• Python follows indentation. The spaces at the beginning of a code line are referred to as indentation. Whereas indentation in code is just for readability in other programming languages, it is crucial in Python.

Python Data Types

The type of a variable is specified using Python data types.

The data type specifies the kind of information that will be stored in a variable. Different kinds of data can be stored in memory. For instance, a person’s address is stored as a string of alphanumeric letters, and his age is stored as a numeric value.

Let us have a look at the various data types available in Python: Data Type

Int

This data type is used for storing integers (whole numbers), both positive and negative.

Float The float data type is used to store positive and negative numbers with a decimal point.

Strings Python Strings are identified as a contiguous set of characters represented in quotation marks. It can be used to store text-based (collection of letters, words, and sentences) information. Python allows pairs of either single or double quotes.

List A list is an orderly grouping of items. It can include a variety of items, such as numbers, words, or even additional lists. Items in a list are enclosed in square brackets.

Tuple A tuple is similar to a list in which its elements cannot be modified once specified. It is like a predetermined list of items. Items of tuple are enclosed in parentheses.

Dictionary A dictionary is a collection of key-value pairs that are not ordered. It can be used to store and retrieve data, using particular keys. A dictionary functions as a book of definitions. Words serve as keys, and their definitions serve as values. Every word conveys a distinct meaning.

Dictionaries are enclosed by curly braces { } and the individual keys are separated from their values by colons.

Boolean A Boolean is a built-in data type that represents one of two values: True or False.

Boolean data type is often used for making decisions and controlling the flow of a program.

Set A set is an unordered collection of unique elements. It is a data type that allows for the storage of many values while automatically removing duplicates.

Variables

var1 = 5

var2 = –15

b=50.45

name="Anita"

str1 = 'Hello World!'

list = ['Steve', 589, 5.56, 'Elon', 150.2]

tuple = ('Steve', 589, 5.56, 'Elon', 150.2)

Animals = {"lion": "Lions are known as the kings of the jungle", "elephant": "Elephants have a great memory"}

x = True # display the value of x

y = False # display the value of y

favourite_fruit = {"Mango", "Peach", "Kiwi"}

If we need to store something in real life, we need a container or box to do so. The variables in Python represent containers for storing data of various types, such as int, float, string, Boolean, list, tuple, etc.

The reserved memory areas used to hold values in a Python program are known as variables.

Creating Variables

To reserve memory space for a variable or to assign values to variables, you can use the equal sign (=).

The name of the variable is written to the left of the ‘=’ operator, and the value is written to the right.

Example:

Code

ctr = 1000 # Creates an integer variable distance = 1000.0 # Creates a float variable

str1 = "Sunita Sood" # Creates a string variable

Rules for Naming a Variable

• A variable name starts with a letter or the underscore character. It cannot start with a number or any special character like $, (, *, %, etc.

• A variable name can only contain alphanumeric characters.

• Python variable names are case-sensitive, which means str1 and STR1 are two different variables in Python.

• Python keywords cannot be used as variable names.

Printing Python Variables

The print() function can be used to output a Python variable.

Example:

Code

ctr = 1000 distance = 1000.0

str1 = "Sunita Sood"

print(ctr)

print(distance)

print(str1)

Multiple Assignments

Output

Sood

You can create several variables in a single statement with Python because it allows you to assign a single value to many variables at once.

Example: Assignment of single value to many variables.

Code Output

a = b = c = 700 print (a) print (b) print (c)

Example: Assignment of multiple values to multiple variables.

Code Output

x, y, z = 111, 112, "Sunita Sood" print (x) print (y) print (z)

Dynamic Typing

In Python, when you assign a value to a variable, you do not need to define the variable’s type like in other languages. However, you can check the data type of a variable by using the type() function.

Python specifies the kind of variable used during program execution. This concept is known as dynamic typing.

Example:

y = [11, 12, 13] # assigning a value to a variable print(type(y))   # y is a list here y = True   # reassigning a value to the ‘y’ print(type(y))   # y is a bool here

Do It Yourself 1A

<class ‘list’> <class ‘bool’>

Identify and write valid or invalid for the following variable names. Ctr ctr name1 city:Delhi

name-1

Operators

Operators are predefined symbols that perform operations on one or more operands.

Types of Operators

The Python language supports the following types of operators:

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

Let us have a look at all the operators one by one.

Arithmetic operators are used with numeric values to perform common mathematical operations. Consider x=10 and y=3:

111
112

Precedence of Arithmetic Operators in Python

Operator precedence describes the order in which operations are performed. The precedence of arithmetic operators in Python is as follows:

• P—Parenthesis

• E—Exponentiation

• D—Division

• M—Multiplication (multiplication and division have the same precedence)

• A—Addition (addition and subtraction have the same precedence)

• S—Subtraction

Assignment operators are used to assign values to variables.

Consider the variable x and let us assign values to it.

Did You Know?

The ‘#’ operator is used for giving comments in a Python program.

Comparison operators are used to compare two values. Comparison operators are also known as relational operators. Consider x=10 and y=3:

Logical operators are used to combine conditional statements.

Operator Description

Example

Output and Returns True, if both the statements are true x < 5 and x < 10 False or Returns True, if one of the statements is true x < 5 or x < 4 False not Reverse the result, that is, returns False, if the result is true not(x < 5 and x < 10)

True

Did You Know?

Python gives more precedence to arithmetic operators than comparison operators. Within comparison operators, every operator has the same precedence order.

Conditional Statements

Think and Tell

What will be the output of the following?

• print(10+15/5*6//2)

• print(10>5+3–1)

In real life, there are times when we must make choices, and based on those choices, we determine what to do next. Programming encounters similar scenarios where we must make choices and then carry out the following block of codes in accordance with those choices.

The programming languages use conditional statements that make decisions to control the direction or flow of the program execution. Conditional statements are also known as decision-making statements.

Types of Conditional Statements

In the Python programming language, the types of conditional statements are:

1 The if statement

2 The if-else statement

3 The if-elif-else statement

The if Statement

The simplest statement for making decisions is the if statement. If the condition associated with if is true, then only it will execute a specific statement or block of statements associated with it; otherwise, it will skip the statements.

Syntax: if condition:

# statements to execute if condition is true

Did You Know?

Python uses indentation to identify a statement associated with if.

Let us understand this with the help of an example given below.

Code Output

# Python program to illustrate if statement i =10

if(i > 15):

print("10 is greater than 15")

#indented statement print("I am Not in if")

I am Not in if

In the above example, the value of i (10) is not greater than 15. So, the condition is false, and it will not execute the statement associated with the if statement.

Another example:

Code

a = 133

b = 1200

if b > a:

print("b is greater than a")

Output

b is greater than a

In the above example, the value of b is greater than the value of a. So, the condition is true, and thus it will execute the statement associated with if.

Flowchart of if Statement

The if statement alone tells us that if a condition is true, a block of statements will be executed; if the condition is false, the block of statements will not be executed. However, if the condition is false, we may use the else statement in conjunction with the if statement to execute a block of code when the condition is false.

Syntax:

if (condition):

# Executes this block if condition is true

else:

# Executes this block if # condition is false

Flowchart of Python if-else Statement

Let us understand it with the help of an example:

Code

i = 220 if (i< 155):

print("i is smaller than 155")

print("I’m in if Block") else:

print("i is greater than 155")

print("I’m in else Block") print("I’m not in if and not in else Block")

Output

i is greater than 155 I’m in else Block I’m not in if and not in else Block

In the above example, after invoking the statement that is not in the block (without spaces), the block of code that follows the else statement is executed since the condition in the if statement is false.

Shorthand if-else Statement

When only one statement is required in both the if and else blocks, this can be used to write the if-else statements on a single line.

Syntax:

statement_when_True if condition else statement_when_False

Let us illustrate this with the help of an example. In the given example, we are printing True if the number is less than 145; otherwise, it will print False.

Program Output

i = 10

print(True) if i< 145 else print(False)

The if-elif-else Statement

Sometimes, we need to evaluate multiple conditions. In such cases, we use the ‘elif’ statement, which stands for ‘else if’. It allows us to check multiple conditions in sequence, and Python checks each condition until one of them is True.

Syntax: if condition_1:   Statement_1

elif condition_2:   Statement_2 .. else:   Statement_n

If condition_1 becomes True, Statement_1 will be executed, otherwise, the interpreter moves on to condition_2 and if it becomes True then it will execute Statement_2. This process continues until a True condition is found, otherwise the ‘else’ statement (Statement_n) will be executed if none of the conditions is True.

Code Output

number = int(input("Enter a number: ")) if number > 0:

print("The number is positive.") elif number < 0:

print("The number is negative.") else:

print("The number is zero.")

Iterative Statements

Enter a number: 23

The number is positive.

Iterative statements are also called loops in programming. Loops are useful in Python because they allow you to execute a block of code repeatedly. You will frequently encounter circumstances in which you will need to utilise a piece of code repeatedly but do not want to write the same lines of code several times. Then those repeated sets of statements can be enclosed within a loop.

Python has two primitive loop statements:

• while loop

• for loop

The while Loop

With the while loop, we can execute a set of statements as long as the condition is true.

Syntax: while expression:

statement(s)

Flowchart of while Loop

A block of code consists of all the statements that follow a programming construct and are indented by the same number of character spaces. Python groups statements together with the same indentation. In the while loop, the condition is assessed initially in a Boolean context. If it returns True, the loop body is executed. The expression is then verified again, and if it is still True, the body is executed again, and so on until the expression becomes False. Let us illustrate this with the help of an example.

Code Output

#Python program to print "Hello" 5 times count = 0

while (count < 5):

count = count + 1

print("Hello")

The count variable is considered as a counter for loop to control the iterations. Remember to increment the count variable, or else the loop will continue forever. Code

#Python program to print 1 to 5 count = 0

while (count < 5):   count = count + 1   print(count)

Single Statement while Block

If the while block consists of a single statement, we can define the entire loop in a single line, just like the if block. If there are numerous statements in the loop body block, they can be separated by semicolons (;). Let us illustrate this with the help of an example:

Code Output

# Program to illustrate single statement while block count =0

while(count < 5): count +=1; print("Hello")

Loop Control Statements

Loop control statements change the execution of the statements from their normal sequence. There are two types of loop control statements:

The continue Statement

The Python continue statement returns control to the beginning of the loop. Let us illustrate this with the help of an example:

Code Output

# Python program to print all letters except 'i' and 'o'

i = 0

a = 'This is Python' while i<len(a):

if a[i] == 'i' or a[i] == 'o': i += 1

continue print('Current Letter :', a[i])

i += 1

The break Statement

Current Letter : T

Current Letter : h

Current Letter : s

Current Letter :

Current Letter : s

Current Letter :

Current Letter : P

Current Letter : y

Current Letter : t

Current Letter : h

Current Letter : n

The Python break Statement brings control out of the loop. Let us illustrate this with the help of an example:

Code

# Program to break the loop as soon it sees 'e' or 's' i = 0

a = 'This is Python' while i<len(a):

if a[i] == 'e' or a[i] == 's': i += 1

break print('Current Letter :', a[i])

i += 1

The for Loop

Output

Current Letter : T

Current Letter : h

Current Letter : i

The for loop is used to iterate over an iterable like a string, tuple, list, set, or dictionary sequentially. Syntax: for var in iterable: # statements

Flowchart of for Loop

• The iterable in this case is a group of items like lists and tuples.

• For each item in an iterable, the indented statements inside the for loops are once again executed. Every time the loop is executed, the variable var is set to the value of the iterable’s subsequent item.

• The Python for loop is used to iterate over an iterable like a string, tuple, list, set, or dictionary sequentially.

Let us illustrate this with the help of an example:

This code employs a for loop to cycle through a list of numbers, printing each number on a new line. The loop assigns each item to the variable ‘i’ and repeats until the entire list has been iterated.

Code Output

# Python program to illustrate iterating over a list numbers = ["1", "2", "3"] for i in numbers:

The range() Function

Python provides range() function to generate a set of numbers within the specified range. This function can be used with loops in Python.

Syntax:

range(start, stop, step)

Here,

start: The starting value of the sequence (default is 0).

stop: The end value of the sequence (not included).

step: The step between numbers in the sequence (default is 1).

We can skip start and step values. In that case Python considers the default values of these two parameters. Let us understand this with an example.

Code Output

#Python Program to print from 9 to 14

i in range(9,15):

Python for Loop with a Step Size

This code generates a series of numbers with a step size of 2, starting from 9 and going up to (but not including) 15, using a for loop and the range() function. The loop uses the print() method to print the value of each number in the series. The numbers 9, 11, and 13 will be displayed in the output.

#Program to print from 9 to 14 with a step value of 2

i in range(9,15,2):

#Program to print even numbers starting from 220 till 230   for i in range(220,232,2):

print(i)

Solved Examples

Example 1.1

# Python program to reverse a number using while loop Code

n=int(input("Enter a number: "))

rev=0

while(n>0):

dig=n%10

rev=rev*10+dig

n=n//10

print("Reverse of the number:",rev)

Example 1.2

Enter a number: 8709

Reverse of the number: 9078

#Python program to count the number of digits in a number

n=int(input("Enter a number:")) count=0

while(n>0): count=count+1 n=n//10

print("The number of digits in the number are:",count)

Enter a number: 652348

The number of digits in the number are: 6

1 Write a Python program to find the sum of digits in a number.

2 Write a Python program to display the multiplication table of the entered number.

3 Write a Python program to convert metres to centimetres.

Coding Challenge

Geometry Calculator

Create a Python program with a menu that lets the user choose from various options. The program should perform calculations based on the user's choice and show the result. After displaying the result, the program should ask if the user wants to continue or exit.

The available options are:

1 Calculate the area and perimeter of a circle

2 Calculate the area and perimeter of a rectangle

3 Calculate the area and perimeter of a square

Chapter Checkup

A Fill in the blanks.

Hints iterate   indentation  end  dictionary  precedence

1 In Python, defines a block of statements.

2 Operator describes the order in which operations are performed.

3 The for loop in Python is used to over a sequence or other iterable objects.

4 The continue keyword is used to the current iteration in a loop.

5 A is a collection of key-value pairs that are not ordered.

B Tick () the correct option.

1 Among the following, who is the developer of Python programming?

a Guido van Rossum b   Denis Ritchie

c Y.C. Khenderakar d   Mark Zuckerberg

2 List, tuple, and set are the of data types.

a Default Types

b   Binary Types

c Boolean Types d   Sequence

3 What is the name of the operator ** in Python?

a Exponentiation b   Modulus

c Floor division d   Multiplication

4 Conditional statements are also known as statements.

a Loops b   Array

c List d   Decision-making

5 What will be the output of the following Python code? a=7 if a>4: print("Greater")

a Greater b   7

c 4 d   No output

C Who am I?

1 I am a comparison operator that is used to check the equality of two values.

2 I am one of the conditional statements in Python that allows you to check multiple conditions.

3 I am a statement in Python that ends the execution of a loop.

4 I am a function in Python that is used to generate a set of numbers within the specified range.

5 I am a built-in data type in Python which represents one of two values, True or False.

D Write T for True and F for False.

1 The type() function can be used to get the data type of any object.

2 The % operator returns the quotient.

3 The if statement is the most fundamental decision-making statement.

4 In Python, an else statement comes right after the block after ‘if’.

5 Loop control statements change the execution of the statements from their normal sequence.

E Answer the following questions.

1 Differentiate between a for loop and a while loop.

2 Differentiate between break and continue statement.

3 What are the different rules for declaring a variable?

4 What is data type? Name the basic data types used in Python.

5 What are conditional statements? Describe the use of if-else.

F Apply your learning.

1 What is the output of the following lines of code? x = False print(type(x))

2 Write a Python program that uses the range function to print all the numbers from 1 to 10.

3 Write a program to calculate the area of equilateral triangle having a side of 7 cm.

4 Write a Python program to get the next number and previous number of a given number.

Strings in Python 2

Strings

A string is a data type that represents a sequence of characters. In Python, strings are enclosed in single quotes (' ') or double quotes (" "). These values can be words, symbols, characters, numbers, or a combination of all these. A string cannot be changed once it has been created because it is an immutable data type. Strings are commonly used for storing and manipulating text data, as well as representing names, addresses, and other types of information that can be represented as text.

There are two types of strings in Python:

• Single-line string

Single-line String

• Multi-line string

A single-line string can be enclosed in either single quotes or double quotes.

Code Output

name1="Mohit"

name2='Mohit'

print(name1)

print(name2)

Multi-line String

Mohit Mohit

A multi-line string can be enclosed in either three single quotes (‘‘‘ ’’’) or three double quotes (""" """).

Code Output

proverb_1= '''Don't judge a book by its cover. '''

proverb_2= """ Beauty is in the eye of the beholder.

"""

print(proverb_1) print(proverb_2)

Don’t judge a book by its cover. Beauty is in the eye of the beholder.

The

eval() Function

The eval() function evaluates a string expression and returns the result.

Syntax: result = eval(expression)

Code Output

expression = "2 * 3 + 4 / 2" result = eval(expression) print(result)

x = 5 y = 3

expression = "x + y" result = eval(expression) print(result)

Creating a String in Python

Did You Know?

A single character in Python is just a string of length 1, since there is no such thing as a character data type.

In Python, single, double, or even triple quotes can be used to create strings.

Let us define a string with the help of a few examples:

Code Output

String1 = 'Welcome to the World of Python'

print("Single Quote String")

print(String1)

# Creating a string using double quotes

String1 = "I am using Python"

print("\n String with double quotes") print(String1)

# Creating a string with triple quotes

String1 = '''I am using Python and I live in a world of "Python"''

print("\n String with triple quotes")

print(String1)

# Creating triple quotes string with multiple lines

String1 = ‘’’Programmer For Life’’’

print("\n Multiline String")

print(String1)

Single Quote String

Welcome to the World of Python

String with double quotes I am using Python

String with triple quotes I am using Python and I live in a world of "Python"

Multiline String Programmer For Life

Note that ‘\n’ is an escape character used to create a new line. The text written after ‘\n’ character comes in the new line.

String Manipulation in Python

String manipulation in Python involves various operations to process and modify string data. Python provides a set of string methods to perform these operations. Let us learn about some of the important string operations.

Concatenation

Concatenation means to join two or more strings together to form a single string. Two strings can be concatenated or joined with the plus ‘+’ symbol, which is known as concatenation operator. Let’s understand it with the help of an example:

Code

# concat strings with + str1 = "Welcome to"

str2 = "World of Python"

sentence = str1 + ‘ ‘ + str2

print(sentence)

Replication

Output

Welcome to World of Python

Replication of strings means to repeat a certain string a specified number of times. The replication operation can be performed with the help of the asterisk symbol '*', which is known as the replication operator.

Look at the given example:

Code

str1='hello'

str2='hello'*3

print(str1)

print(str2)

Replacing a String

Output

hello hellohellohello

If you wish to replace a string, just call the replace() function on any string and specify the string you want to replace it with. Look at the following example:

Code

sentence = "Welcome to World of Python"

print(sentence)

print(sentence.replace("Python","Disneyland"))

Finding the Length of a String

Output

Welcome to World of Python

Welcome to World of Disneyland

To find the length of a string, the len() function is used. The len() function returns the number of characters in a string, including spaces, punctuation, and special characters.

Code Output

str = "Python, World!"

length = len(str)

print("The length of the string is:", length)

The length of the string is: 14

Accessing Characters in Python String

The indexing method in Python can be used to access specific characters within a String.

• Through indexing, characters at the beginning of the string can be accessed using positive address references, starting from 0 for the first character, 1 for the next character, 2 for the next to the next character (as shown in the image), and so on.

• Through indexing, characters at the end of the string can be accessed using negative address references, such as –1 for the last character, –2 for the next-to-last character, and so on.

Let us understand it with the help of an example:

In this example, we will define a string in Python and access its characters using positive and negative indexing. The 0th element will be the first character of the string, whereas the –1th element is the last character of the string.

Code Output

String1 = "Python World"

print("Initial String: ")

print(String1)

# Printing First character

print("\nFirst character of String is: ")

print(String1[0])

print(String1[-12])

# Printing Last character

print("\nLast character of String is: ")

print(String1[-1])

print(String1[11])

# Printing Fifth character

print("\nFifth character of String is: ")

print(String1[4])

print(String1[-8])

String Slicing

Initial String: Python World

First character of String is:

Last character of String is:

Fifth character of String is:

The string slicing function in Python is used to gain access to a selection of characters in the String. A colon (:), known as a "slicing operator", is used to access a part of the string.

• The string provided after slicing includes the character at the start index but not the character at the last index, so keep that in mind while using this method.

• Subsets of strings can be taken using the slice operators ([ ] and [:]) with indexes starting at 0 at the beginning of the string and working their way from -1 at the end.

Let us understand it with the help of an example:

In the following example, we will slice the original string in order to extract a substring. The expression [4:12] indicates that the string will be divided into segments starting at index 4 and continuing through index 11. In string slicing, negative indexing is another option.

Code Output

# Creating a String String1 = "Python World"

print("Initial String: ")

print(String1)

# Printing 4th to 12th character

print("\nSlicing characters from 4-12: ")

print(String1[4:12])

# Printing characters between 4th and 3rd last character

print("\nSlicing characters between 4th and 3rd last character: ")

print(String1[4:-3])

Using In-built String Methods

Initial String: Python World

Slicing characters from 4-12: on World

Slicing characters between 4th and 3rd last character: on Wo

Python provides several in-built methods to change the case of strings. These methods are helpful for formatting and standardising text. Here are some main functions for changing the case of Python strings:

1. upper()

The upper() method converts all lowercase letters in a string to uppercase.

Code Output

str = "python world" result = str.upper() print(result)

2. lower()

The lower() method converts all uppercase letters in a string to lowercase.

Code Output

str = "PYTHON WORLD" result = str.lower() print(result)

3. capitalize()

python world

The capitalize() method converts the first character of a string to uppercase and the rest to lowercase.

Code Output

str = "python world" result = str.capitalize() print(result)

Python world

PYTHON WORLD

4. title()

The title() method converts the first character of each word to uppercase and the rest to lowercase. Words in a string should be separated by whitespace or punctuation marks.

Code Output

str = "welcome to the world of python" result = str.title() print(result)

5. swapcase()

Welcome To The World Of Python

The swapcase() method converts uppercase characters to lowercase and lowercase characters to uppercase.

Code Output

str = "Python World" result = str.swapcase() print(result) pYTHON wORLD

Decision-making Using String Methods

Apart from these text formatting methods in Python, there are some more methods that are used for decision making using strings. These methods can determine whether a string or character is in uppercase, lowercase, title case, or whether it contains digits or alphanumeric characters. Here are some of the main functions for checking the properties of strings:

1. isupper()

The isupper() method returns True if all the alphabetic characters in a string are uppercase. If the string contains no alphabetic characters, the method returns False.

Code Output

str = "PYTHON WORLD" result = str.isupper() print(result)

str = "Python World" result = str.isupper() print(result)

2. islower()

The islower() method returns True if all the alphabetic characters in a string are lowercase. If the string contains no alphabetic characters, the method returns False.

Code Output

str = "python world" result = str.islower() print(result)

str = "Python World" result = str.islower() print(result) True False

3. istitle()

The istitle() method returns True if a string is title-cased, which means the first character of each word is uppercase and the rest are lowercase.

Code Output

str = "Python World" result = str.istitle() print(result)

str = "python world" result = str.istitle() print(result)

4. isdigit()

The isdigit() method returns True if all the characters in a string are digits.

Code Output

str = "987654321" result = str.isdigit() print(result)

str = "python98765" result = str.isdigit() print(result)

5. isalpha()

The isalpha() method returns True if all the characters in a string are alphabets.

Code Output

str = "Hello" result = str.isalpha() print(result)

str = "987654321" result = str.isalpha() print(result)

6. isalnum()

The isalnum() method returns True if all the characters in a string are alphanumeric (letters and numbers).

Code Output

str = "987654321" result = str.isalnum() print(result)

str = "python98765" result = str.isalnum() print(result)

Solved Examples

Example 2.1

#Python program to perform String operations

Code Output

str2 = 'Hello Sunita' print (str2) # Prints complete string print (str2[0]) # Prints first character of the string print (str2[2:5]) # Prints characters starting from 3rd to 5th print (str2[2:]) # Prints string starting from 3rd character print (str2 * 2) # Prints string two times print (str2 + "TEST") # Prints concatenated string

Example 2.2

#Python program to count the number of vowels in a string

Hello Sunita H llo

Hello SunitaHello Sunita

Hello SunitaTEST

Code Output

string=input("Enter string:")

vowels=0 for i in string:

if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or

i=='E' or i=='I' or i=='O' or i=='U'):

vowels=vowels+1

print("Number of vowels are:", vowels)

Example 2.3

Enter string:ritu

Number of vowels are: 2

#Python program to count number of lowercase characters in a string

Code Output

string=input("Enter string:") count=0 for i in string: if(i.islower()): count=count+1

print("The number of lowercase characters is:", count)

Example 2.4

Enter string:Ritu Singh

The number of lowercase characters is: 7

#Python program to count the number of words and characters in a string

Code Output

string=input("Enter string: ")

char=0

word=1 for i in string: char=char+1

if(i==' '):

word=word+1

print("Number of words in the string:", word)

print("Number of characters in the string:", char)

Enter string: Ritu is a good girl

Number of words in the string: 5

Number of characters in the string: 19

1 Write a Python program that accepts a string and calculates the number of digits and letters.

2 Write a Python program to check whether a letter is a vowel or a consonant.

Chapter Checkup

A Fill in the blanks.

Hints single  indexing  concatenate  double  changed

1 In Python, strings are put inside quotes or quotes.

2 Strings in Python are immutable, which means they cannot be once they have been created.

3 The method in Python can be used to access specific characters within a string.

4 The plus ‘+’ symbol is used to two strings in Python.

B Tick () the correct option.

1 Which of the following is the correct way to define a string in Python?

a  string = ‘Hello’

c  Both a and b

b  string = "Hello"

d  None of the above

2 How do you access the last character of a string using negative indexing?

a  string[-0]

c  string[-2]

b  string[-1]

d  string[-3]

3 Which of the following functions is used to replace a part of a string with another string?

a  eval() b  replace() c  slice() d  concat()

4 Which of the following is a multi-line string in Python?

a  ‘’’This is a multi-line string’’’ b  "This is a multi-line string"

c  ‘This is a multi-line string’ d  All of the above

C Who am I?

1 I am a data type in Python that represents a sequence of characters.

2 I am a function that evaluates a string expression and returns the result.

3 I am an operator used to replicate a string multiple times.

4 I am a method of accessing specific characters within a string in Python.

D Write T for True and F for False.

1 Strings in Python can be enclosed in either single quotes or double quotes.

2 The string slicing function includes the character at the last index.

3 The replace() function can modify a string directly.

4 The eval() function can execute a string expression and return its result.

E Answer the following questions.

1 Write the difference between single-line strings and multi-line strings in Python.

2 How does the indexing method work for accessing characters in a string in Python?

3 How can you use the slicing operator to extract a substring in Python?

4 What does it mean that strings in Python are immutable?

F Apply your learning.

1 Write a Python program that concatenates two strings, "Hello" and "World", and prints the result.

2 Using string slicing, extract the substring "Python" from the string "Learning Python is fun!" and print it.

3 Write a Python program to replace the word "fun" with "awesome" in the string "Learning Python is fun!" and print the result.

4 Write a Python program that uses the eval() function to evaluate the string "3 + 4" and print the result.

Lists and Tuples in Python 3

Lists

Lists are a fundamental data type in Python.

It is a collection of various kinds of values. It can hold multiple values in a single variable

In Python, lists are used to store multiple values simultaneously. Python includes a built-in list type named "list". In lists, items are written within square brackets [ ].

A list can:

• Store different types (integer, float, string, etc.) of elements.

• Store duplicate elements.

• Store the elements in an ordered manner.

Example: mylist = [2, 4, 6, 8, "Python", 10, 10]

Characteristics of Lists

The characteristics of the lists are given below:

• Ordered: In a list, the values or items have a defined order, and this order does not change. If you add new values to a list, they are placed at the end of the list.

• Accessed via the Index: You can access list elements using an index, which starts at 0. Hence, the first element of a list is present at index 0, not 1.

• Allows Duplicate Values: A list can contain duplicate values. Since values are indexed in a list, it can have items with the same value but a different index.

• Mutable: The meaning of mutable is "liable to change". In Python, list items are mutable. It means elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.

• Variable Size: Lists can store a variable number of elements, allowing you to store and manage different quantities of data.

Creating a List in Python

In Python, you can create a list by enclosing the values or elements within square brackets [ ], separated by commas. There is no need for a built-in function to create a list.

Syntax: list_name = [element_1, element_2, … , element_n]

Example:

Suppose you need to record the percentage of marks for six students. For this, you can simply create a list.

markslist = [70, 88, 90.2, 75, 68, 59.5]

print(markslist)

Creating a List with Duplicate Elements

[70, 88, 90.2, 75, 68, 59.5]

A list can have duplicate values. Let us see the following example:

Code

list = [3, 4, 9, 3, 8, 9]

print(list)

Creating a List with Mixed Types of Elements

[3, 4, 9, 3, 8, 9]

You can have elements of different data types in a list. They can be of numeric type, string type, Boolean type, etc.

Example: Code

list1 = ["Ankit", 34, False, 55.5, "Mala"]

print(list1)

Accessing Elements of a List

[‘Ankit’, 34, False, 55.5, ‘Mala’]

Indexing is used in Python to access list elements. Suppose there are n number of elements in a list. Therefore, the list indexing will start at 0 for the first element and n-1 for the last element. You can use these index values to access the items in the list. The index must be an integer. Let us see how to access elements in a list. Look at the following image to understand the concept of indexing:

Example:

Print the third and fifth item of the list.

[Hint: The third element has an index 2 and the fifth 4.]

markslist = [70, 88, 90.2, 75, 68, 59.5]

print(markslist[2])

print(markslist[4])

List Methods

Python has a set of built-in methods that you can use on lists.

append(): This method is used to add an element at the end of the list. An element can be of any type (string, number, object, etc.).

Syntax: list.append(element)

For example, add the item "eggs" to the shopping_list = ["bread", "butter", "milk", "apples"].

Code Output

shopping_list = ["bread", "butter", "milk", "apples"]

shopping_list.append("eggs")

print(shopping_list)

[‘bread’, ‘butter’, ‘milk’, ‘apples’, ‘eggs’]

clear(): This method is used to remove all the elements from the list.

Syntax: list.clear()

For example, remove all elements from the shopping_list = ["bread", "butter", "milk", "apples"].

Code Output

shopping_list = ["bread", "butter", "milk", "apples"]

shopping_list.clear() print(shopping_list)

count(): This method is used to return the number of the specified element.

Syntax: list.count(value)

For example, to count the number of times the value ‘3’ appears in the list = [3, 4, 9, 3, 8, 9]:

Code Output

list = [3, 4, 9, 3, 8, 9] x=list.count(3) print(x)

2

pop(): This method is used to remove the element at the specified position.

Syntax: list.pop(position)

For example, remove the third element from the list = [3, 4, 9, 3, 8, 9].

[Hint: The third element has an index 2.]

Code Output

list = [3, 4, 9, 3, 8, 9] list.pop(2) print(list)

[3, 4, 3, 8, 9]

Note: If the position is not specified, by default, the pop() method removes the last element from the list.

remove(): This method is used to remove the first occurrence of the specified element.

Syntax: list.remove(element)

For example, remove 3 from the list = [3, 4, 9, 3, 8, 9].

Code

list = [3, 4, 9, 3, 8, 9] list.remove(3) print(list)

[4, 9, 3, 8, 9]

index(): This method is used to find the position of the first occurrence of the specified element. Syntax: list.index(value)

For example, find the first occurrence of the value 9, and return its position in the list = [3, 4, 3, 9, 8, 9].

Code

list = [3, 4, 3, 9, 8, 9] x = list.index(9) print(x)

3

sort(): This method is used to sort the list in ascending order, by default. To sort the list in descending order, the attribute reverse is used. If its value is set to ‘True’, then the list will be sorted in descending order.

Syntax: list.sort()

Example 1: Sort the list = [3, 4, 9, 3, 8, 9] in ascending order.

Code

list = [3, 4, 9, 3, 8, 9] list.sort() print(list)

[3, 3, 4, 8, 9, 9]

Example 2: Sort the list = [3, 4, 9, 3, 8, 9] in descending order.

Code

list = [3, 4, 9, 3, 8, 9] list.sort (reverse=True) print(list)

Solved Examples

Example 3.1

[9, 9, 8, 4, 3, 3]

Create a list of subjects (Maths, English, Science, Hindi, and Computer). Print all subjects in the list, one by one. Ans:

Code

subject_list = ["Maths", "English", "Science", "Hindi", "Computer"] for x in subject_list:   print(x)

Example 3.2

Sort the list alphabetically:

List [s, u, n, s, c, r, e, e, n]

Ans:

list = ["s", "u", "n", "s", "c", "r", "e", "e", "n"] list.sort() print(list)

Tuples

[‘c’, ‘e’, ‘e’, ‘n’, ‘n’, ‘r’, ‘s’, ‘s’, ‘u’]

A tuple is an ordered, immutable collection of things or values. Tuples are sequences, just like lists, but they cannot be modified, unlike lists. Lists use square brackets, while tuples use parentheses () to enclose the elements. Tuples are faster than lists.

For example, mytuple = (1, 2, 3, 4, 5)

Characteristics of Tuples

The characteristics of tuples are given below:

• Ordered: In a tuple, the values or items have a defined order, and this order does not change.

• Accessed via the Index: The tuple element can be accessed via the index. It means that the tuple index always starts with 0. Hence, the first element of a tuple is present at index 0, not 1.

• Immutable: The tuple items are immutable. The meaning of immutable is "unable to be changed". It means that we cannot add, modify, or remove items in a tuple after it has been created.

• Allows Duplicate Values: A tuple can contain duplicate values. Since values are indexed in a tuple, it can have items with the same value and a different index.

Creating a Tuple

In Python, you can create a tuple by placing the values or elements inside the parentheses ( ), separated by commas.

Syntax: tuple_name = (element_1, element_2, … , element_n)

Creating a Tuple with a Single Item

To create a tuple with a single item, you have to add a comma after the item; otherwise, Python will not recognise it as a tuple.

Example: Code

mytuple = ("Delhi",) print(mytuple) Delhi

Creating a Tuple with Duplicate Elements

A tuple can contain duplicate elements. Their index values will be different.

Example: Code

tuple = (3, 4, 9, 6, 4, 9)

print(tuple)

Creating a Tuple with Mixed Elements

A tuple can have elements of mix data type.

Example:

Code

tuple = ("Delhi", 4, 9, "Japan", 4, 9)

print(tuple)

Accessing Elements of a Tuple

(3, 4, 9, 6, 4, 9)

(‘Delhi’, 4, 9, ‘Japan’, 4, 9)

Indexing is used in Python to access tuple elements. You can access a tuple entry using indexing. In Python, tuple indexing starts at 0 for the first element. You can use the index operator [ ] to access an item in a tuple. The index must be an integer. Here is how you can access elements in a tuple:

For example: Print the first item in the tuple.

Code

tuple1 = ("Delhi", "Punjab", "Haryana", "Gujarat")

print(tuple1[0]) Delhi

Tuple Methods

Python has two built-in methods that you can use on tuples.

count(): This method is used to compute the occurrence of a specified value that appears in the tuple.

Syntax: tuple.count(value)

Example: How many times the value 9 appears in the tuple = (3, 4, 9, 6, 4, 9)?

Code

tuple = (3, 4, 9, 6, 4, 9)

x = tuple.count(9)

print(x)

2

Index(): This method is used to find the position of the first occurrence of the specified value.

Syntax: tuple.index(value)

Example: Find the first occurrence of the value 9, and return its position in the tuple = (3, 4, 9, 6, 4, 9).

Code Output

tuple = (3, 4, 9, 6, 4, 9)

x= tuple.index(9) print(x)

Deleting Elements of a Tuple

2

As you are aware, the tuple items are immutable. It implies that once a tuple is created, its elements cannot be changed, added to, or removed without creating a new tuple. However, there is a workaround using the steps that follow:

• You can convert the tuple into a list

• Change the list

• Convert the list back into a tuple

Example: Convert the tuple into a list, remove "Haryana", and convert it back into a tuple:

Code Output

tuple1 = ("Delhi", "Punjab", "Haryana", "Gujarat")

x = list(tuple1) x.remove("Haryana")

tuple1 = tuple(x) print(tuple1) mytuple = ("Delhi") print(mytuple)

Solved Examples

Example 3.3

Combine or merge two given tuples.

tuple1 = (1, 3, 5)

tuple2 = (2, 4, 6)

Ans:

Tuple concatenation is used to merge the tuples.

Think and Tell

Are lists and tuples heterogeneous or homogeneous data structures?

Code Output

tuple1 = (1, 3, 5) tuple2 = (2, 4, 6) result_tuple = tuple1 + tuple2 print(result_tuple)

Example 3.4

Multiply the given tuple by 3. tuple1 = (1, 2, 3)

(1, 2, 3, 4, 5, 6)

You can use the ‘*’ operator to multiply the tuple. This feature is known as replicating a tuple.

(‘Delhi’, ‘Punjab’, ‘Gujarat’)

Code Output

tuple1 = (1, 2, 3)

tuple1 = tuple1*3

print(tuple1)

Difference Between Lists and Tuples

(1, 2, 3, 1, 2, 3, 1, 2, 3)

Lists and tuples are both used to store items and organise data. They are a fundamental concept in Python. But they have a major difference. In lists, the elements can be changed after they are defined, while in tuples, the elements cannot be changed at all. In real-life, you might use a shopping list where items can be added, removed, or modified. The tuples can be used to represent days of the week, as these do not change.

S. No. Lists Tuples

1 Lists are mutable. Tuples are immutable.

2 You can easily insert or delete data items in a list. You cannot directly insert or delete data items in a tuple.

3 Lists have several built-in methods. Due to immutability, a tuple does not have many built-in methods.

4 Lists are generally slightly slower than tuples because of their mutability. Tuples are faster than lists.

5 Lists are created using square brackets []. Tuples are created using parentheses ().

6 Example: list1 = [1, 2, 3] Example: tuple1 = (1, 2, 3)

Do It Yourself 3A

1 Create a tuple of vegetables (potato, tomato, brinjal, ginger, garlic). Print all vegetables in the tuple, one by one.

2 Make a list of the things you want to buy and write a Python code that organises the list alphabetically.

Chapter Checkup

A Fill in the blanks.

Hints mutable  faster  unlimited  immutable  reverse

1 A list can contain elements.

2 Tuples are than lists.

3 Lists are

4 Tuples are .

5 The attribute of sort() method is used to reverse the order of the list.

B Tick () the correct option.

1 The list.pop() function will:

a remove the first element from the list.

c remove both first and last elements.

2 Which of the following are true about Python lists?

a There is no limit to the size of a list.

b   remove the last element from the list.

d   not remove any element from the list.

b   All elements in a list must be of the same size.

c A list may contain the same type of objects. d   A list is immutable.

3 List L is given below:

L = [0, 1, 2, 3, 4]

Choose the correct answer to delete the element 3 from the list.

a L.delete(3)

c del L[2]

4 Which of the following is mutable?

b   L.remove(3)

d   L.pop(3)

a String b   List

c Tuple d   Set

5 What will be the output of the given code?

tuple = (1, 8, 7, 5, 4, 8, 5)

x = tuple.count(5) print(x)

C Who am I?

1 I am a method that helps to sort a list.

2 I am a collection of values which is ordered and unchangeable.

3 I am a dynamic and change-oriented collection of values.

4 I am a method that helps to add an element at the end of the list.

5 I am an operator that helps to replicate a tuple.

D Write T for True and F for False.

1 The sort() function is used to reverse the order of the list.

2 You cannot directly insert or delete data items in a tuple.

3 Lists are immutable.

4 The list allows duplicate values.

5 Lists cannot store different types of elements.

E Answer the following questions.

1 Explain any three characteristics of a list.

2 Write a code to create a tuple with a single element.

3 Differentiate between pop() and remove() with a suitable example.

4 Write three differences between list and tuple.

5 Discuss any three characteristics of a tuple.

F Apply your learning.

1 Write the code to convert the given list L to tuple: L = [1, 5, 8, 9, 15]

2 Write a code to create a list with single element.

3 Write a code to create a tuple T with the given data: 9, ‘Ram’, 7, 5, ‘Hema’

4 Add a student’s name, "Sushma", at the end of the given list: Stu_list = ["Lata", "Rama", "Ankit", "Vishal"]

5 Create a list of strings and access the elements using index.

More on HTML 4

What Is HTML?

HTML stands for HyperText Markup Language. HTML is a markup language used to design web pages. It defines the structure of a web page and tells the web browser how and where to display the content of the web page. A web page is a document placed on the World Wide Web (WWW) as a part of a website.

The term ‘hypertext’ is a combination of two words ‘hyper,’ which means beyond, and ‘text,’ which means written words. The main goal of hypertext is to go beyond the linear reading process and navigate to the desired location on the web with the help of interconnected web pages.

The term ‘markup language’ refers to a language which creates layout of web pages and applies formatting on them. It makes the objects on the web page like text, image, audio, etc. more interactive, and it also enriches the look and feel of the web pages.

To create a web page in HTML, you need two main things:

• A Text Editor: Text editor is software used to write the code of HTML documents. Some of the popular text editors are Notepad, Notepad++, Sublime Text, etc.

• A Web Browser: A web browser is used to access and view web pages. Examples of web browsers are Google Chrome, Apple Safari, Microsoft Edge, Opera, Mozilla Firefox, etc.

Basics of HTML

An HTML document consists of HTML tags, elements, and attributes.

Tags

Did You Know?

The first web page was developed by Tim BernersLee, a British scientist, in 1991.

A tag is a basic building block of an HTML document that specifies how the content is displayed on the web page. HTML provides several built-in tags. Each of these tags has a specific purpose. For example, the <p> tag is used to create a paragraph in a web page. Each tag has a name which is enclosed in angle brackets < and >. For example, <html>, <body>, <hr>, etc., are some tags in HTML.

Most of the tags in HTML have opening and closing tags. Opening tag is the name of the tag enclosed in the angle brackets. Whereas, the closing tag has a forward slash in the beginning of the tag name and is enclosed in angle brackets. For example,

<html> is the opening tag.

</html> is the closing tag.

The effect of a tag is restricted only to its closing tag. Between opening and closing tags, content is placed.

Elements

The combination of opening tag, content and closing tag is known as element. For example, the paragraph element is as follows:

<p> I am a paragraph. </p>

There are two types of elements in HTML which are as follows:

• Container Elements: Container elements contain other elements or text within them. They have both an opening tag and a closing tag to enclose their content.

Examples: <html></html>, <head></head>, <body></body>.

• Empty Elements: Empty elements, also known as void elements or self-closing elements, do not contain any content. They do not require a closing tag.

Examples: <br>, <hr>, <img>.

Attribute

An attribute provides additional information about an HTML element and modifies its behaviour. Attributes are always placed inside the opening tags of HTML elements. The syntax to add an attribute is as follows: <element attribute=”value”>Content</element>

Where,

• Element: The HTML element to which the attribute belongs.

• Attribute: The name of the attribute.

• Value: The value assigned to the attribute.

For example,

<p align = “right”> I am a paragraph with right alignment </p> Here, align is the attribute of <p> element.

Structure of an HTML Document

Did You Know?

Multiple attributes can be used in an element.

The structure of an HTML document is divided into two main parts: the head and the body. <html> <head>

<title> Title of the web page</title> </head> <body>

Body of the web page </body> </html>

Head Body

Think and Tell

How are tags and attributes different?

The head contains information about the document, such as the title. The title appears on the title bar or tab of the web browser.

The body contains the content of the web page, such as text, images, and videos. The content of the body is displayed in the browser window.

HTML document structure has four tags to describe the document structure, which are as follows:

1 The <html> and </html> tags enclose the entire document.

2 The <head> and </head> tags enclose the head section of the document.

3 The <title> and </title> tags enclose the title of the document.

4 The <body> and </body> tags enclose the body section of the document.

Basic Tags of HTML

Some of the basic tags of HTML are as follows:

Tag

Description

<h1> to <h6> Used to create headings and subheadings on a web page. <h1> is the biggest heading and <h6> is the lowest heading

<h1> Heading 1 </h1>

<h2> Heading 2 </h2>

<h3> Heading 3 </h3>

<h4> Heading 4 </h4>

<h5> Heading 5 </h5>

<h6> Heading 6 </h6>

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5

Heading 6

<sub> Used to lower the text below the baseline H2<sub>2</sub>O H2O

<sup> Used to raise the text above the baseline A<sup>2</sup> A2

<b> Used to make the text bold

<i> Used to make the text italic

<em> Used to emphasise text

<a> Used to create a hyperlink

<b> Bold </b> Bold

<i> Italic </i> Italic

<em> Emphasised </em> Emphasised

<a href = ”www.google.com”>

Home </a> Home

<p> Used to create a paragraph <p> I am a paragraph </p> I am a paragraph

Let’s create a web page using some of these tags:

<html> <head>

<title> Text Formatting Example </title> </head> <body>

<h1> Welcome to My Web Page </h1>

Code

<p> This is a simple paragraph with some <em> emphasised </em> text. We can also use superscript and subscript: </p>

<p> The chemical formula for water is H<sub>2</sub>O, and the famous equation is E = mc<sup>2</sup>. </p>

<p> Feel free to explore the content on this page. Thank you for visiting! </p> </body> </html>

Output

Welcome to My Web Page

This is a simple paragraph with some emphasised text. We can also use superscript and subscript.

The chemical formula for water is H2O, and the famous equation is E = mc2.

Feel free to explore the content on this page. Thank you for visiting!

Do It Yourself 4A

1 Write any three examples of container elements of HTML.

2 Write the name of the tag used for:

a   Making the text bold

b   Making a paragraph

c   Making the text italic

Understanding CSS

Cascading Style Sheets (CSS) is a language used to style the HTML elements. It allows us to change the look and feel of the web pages.

Selectors

CSS uses selectors to target HTML elements. Selectors can target elements by tag name, class, ID, attribute, and more. For example,

body { font-family: sans-serif; background-color: blue;

}

.highlight { color: red;

}

Here, .highlight is the class selector which can be used in HTML tag with the help of the class attribute.

Properties and Values

CSS is used in a property-value pair. The colon (:) sign is used to separate the property from a value. CSS properties define the styles that are to be applied to the selected elements, and values specify the settings for those properties. For example:

selector { property: value; } p{ font-size: 24px; }

There are several properties of CSS. Let us discuss some of them in the following table:

Property

Description

color Sets the colour of the text.

Example

color: blue background-color Sets the background colour of the HTML element. background-color: red

font-family Sets the font family of the text.

font-family: cambria font-size Sets the size of the text.

font-size: xx-small

Note: x-small, small, medium, large, x-large, xx-large can also be used as values.

font-weight Sets the weight or thickness of the text. font-weight: bold

Note: lighter, or any number can also be used

padding Sets the space around the content of the element. padding: 40px

margin Sets the space around the element itself. margin: 20px

border Specifies the border around the element. border: 2px border-radius Specifies the radius of the corners of the element border. border-radius: 5px

opacity Specifies the transparency of the element. opacity: 50 text-align Aligns the text horizontally within a box. text-align: centre box-sizing Controls how the sizing of an element is calculated. There are two possible values for this property: content-box and border-box.

box-sizing: border-box

How to Use CSS in a Web Page

CSS can be used in three ways in a web page which are as follows:

1 Inline CSS: It allows us to apply style to a particular element on a web page with the help of the style attribute. For example, <p style=”color: red; font-size: 15px;”>This is a paragraph</p>

2 Internal CSS: It allows us to apply style to the whole web page with the help of <style> element.

Code Output

<head> <style> p { color: red; font-size: 15px; } </style> </head> <body>

<p>This is a paragraph </p>

<p>This is another paragraph </p> </body>

This is a paragraph

This is another paragraph

3 External CSS: It allows us to style multiple pages with the help of <link> element.

Code Output

<head> <link rel=”stylesheet” href=”style.css”> </head> <body>

<p>This is a paragraph </p> </body>

The style.css file would contain the following CSS: p { color: red; font-size: 15px; }

This is a paragraph.

Let us use some of these CSS properties, that we have learnt in the previous section, in the following web page:

Code

<html> <head> <title> Text Formatting Example </title> <style> body{ background-color:lightgreen; } h1{ color: red; } </style> </head> <body>

<h1> Welcome to My Web Page </h1>

<p> This is a simple paragraph with some <em>emphasised</em> text. We can also use superscript and subscript: </p>

<p> The chemical formula for water is H<sub>2</sub>O, and the famous equation is E = mc<sup>2</sup>. </p> <p> Feel free to explore the content on this page. Thank you for visiting! </p> </body> </html>

Welcome to My Web Page

This is a simple paragraph with some emphasised text. We can also use superscript and subscript. The chemical formula for water is H20, and the famous equation is E = mc2 Feel free to explore the content on this page. Thank you for visiting!

Here, in this web page, the background colour is changed and the colour of the heading is also changed.

Chapter Checkup

A Fill in the blanks.

Hints <sub>  HTML  inline  element

1 is a markup language used to design web pages.

2 The combination of opening tag, content, and closing tag is known as .

3 The tag is used to raise the text below the baseline.

4 The CSS allows us to apply style on a particular element on a web page with the help of style attribute.

B Tick () the correct option.

1 What is the need of a text editor while creating web pages?

a To write the code of web pages

c   Both a and b

2 The effect of a tag is restricted only up to its tag.

a opening

c   the end of the web page

b   To view the web pages

d   None of these

b   closing

d   All of these

3 Which of the following elements is used to enclose the title of the web page?

a <title> and </title>

c   <head> and </head>

b   <body> and </body>

d   <h1> and </h1>

4 Which of the following CSS properties is used to set the space around the content of the element?

a margin

c   border

C Who am I?

1 I am an HTML tag that is used to emphasise text.

2 I am a sign that is used to separate a CSS property from its value.

3 I am a method to apply CSS to all the web pages of a website simultaneously.

4 I am used to specify the transparency of the element.

b   padding

d   opacity

D Write T for True and F for False.

1 HTML stands for Hypertext Making Language.

2 CSS is used in a property-value pair.

3 The <a> tag is also known as anchor tag.

4 The <sub> tag is used to raise the text above the baseline.

E Answer the following questions.

1 What is the meaning of the term ‘markup language’?

2 Write the syntax to define an attribute with a tag and explain each part.

3 What is the difference between padding and margin properties of CSS?

4 What is the role of selectors?

F Apply your learning.

1 Write the HTML code to display the following output on a web page: a3 − b3 Factorisation: (a − b) × (a2 + ab + b2)

2 Write the CSS code to create a box using <div> tag with the following specifications: Height = 400px Width = 500px

Border size = 5px

Border colour = grey

Creating Forms in HTML 5

In this chapter, you will study the most interactive and essential element of web development, i.e., HTML forms. Forms are used to collect information from users, such as their names, email addresses, and hobbies. In this chapter, you will learn to create forms and understand how they work.

What Are HTML Forms?

HTML forms are commonly used when websites need to gather information from users. For example, if someone wants to buy a bag online, they would first fill their address details in one part of the form and then enter their payment information in another part to complete the purchase. An HTML <form> element is used to create fields where users can provide information in an interactive way. It includes fields where users can type text, numbers, email addresses, and passwords, and indicate choices like selecting check boxes or clicking buttons.

Form Structure

In HTML, the structure of a form is how you organise and align the various elements that make up the form. A basic form consists of several elements. Let us learn about these elements and options.

The <form> Element

The <form> element is a container for all form elements. It helps define where the form begins and ends on a web page.

Example: <form> <-- Form elements --> </form>

The <input> Element

The <input> element is used to create various fields to collect different types of information from users, such as text, email addresses, passwords, and more. The <label> element is used to attach a text with the input fields. Some common types of input fields are:

1 Text Input: It is used to take textual information from the user like name, age, roll number, etc. Use type="text" attribute:

Example:

Code Output

<label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name">

2 Email Input: It is used to take the email address as information from the user. It verifies the format of the email address, which means you must enter the email address in the correct format. It shows a message if you enter an incorrect email. It also gives suggestions of email addresses that you have used earlier in the web browser.  Use type="email" attribute:

Example:

Code

<label for="email">Email:</label>

<input type="email" id="email" name="email">

Output

3 Password Input: It is used to take sensitive information like passwords, bank account numbers, etc., from the user. The characters you entered in this field appear in the form of stars or dots. An eye icon also appears in this field which allows you to view the text in readable form. Use type="password" attribute:

Example:

Code Output

<label for="password">Password:</label>

<input type="password" id="password" name="password">

4 Date Input: It is used to take date as input from the user. It displays a calendar to select the date. Use the type="date" attribute:

Example:

Code

<label for="dob">Date of Birth:</label>

<input type="date" id="dob" name="dob" required>

Output

5 Radio Buttons: The Radio button option allows users to select one option from a list. Use the type="radio" attribute:

Example:

Code Output

<label>Gender:</label>

<input type="radio" id="male" name="gender" value="male">

<label for="male">Male</label>

<input type="radio" id="female" name="gender" value="female">

<label for="female">Female</label>

<input type="radio" id="other" name="gender" value="other">

<label for="other">Other</label>

6 Check Boxes: The check box option allows users to select multiple options from a list. Use the type="checkbox" attribute:

Example:

Code Output

<label>Interests:</label>

<input type="checkbox" id="sports" name="interests" value="sports">

<label for="sports">Sports</label>

<input type="checkbox" id="music" name="interests" value="music">

<label for="music">Music</label>

<input type="checkbox" id="movies" name="interests" value="movies">

<label for="movies">Movies</label>

The <textarea> Element

The <textarea> element is used for long text input, such as comments or messages: Example:

Code Output

<label for="address">Address:</label>

<textarea id="address" name="address" rows="4" required>

The <button> Element

Did You Know?

How is a text input field different from a password input box?

The <button> element is used to create buttons within forms. You can use it to perform any action on the form. The type attribute is a must to use with the <button> element. It takes any one value out of button, submit, and reset values.

Example:

Code Output

<button type="button"> Login </button> <button type="button"> Cancel </button>

The <select> Element

The <select> element is used to create drop-down menus. The <option> element is used in combination with the <select> element to create items in the drop-down menu.

Example:

Code

<label for="course">Course:</label>

<select id="course" name="course" required> <option value="math">Mathematics</option> <option value="science">Science</option> <option value="history">History</option> <option value="english">English</option> </select>

Think and Tell

Output

Imagine you are designing a website for a local library. The librarian wants to use an HTML form to allow users to request the issuing of books. Think about the various form elements you would include in this form.

Creating and Displaying a Form

Use the following code to create a form:

<html> <head>

<title>Student Details Form</title> </head> <body>

<h1>Student Details</h1> <form>

Code

<label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name" required><br><br>

<label for="last_name">Last Name:</label>

<input type="text" id="last_name" name="last_name" required><br><br>

<label for="dob">Date of Birth:</label> <input type="date" id="dob" name="dob" required><br><br>

Code

<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br><br>

<label for="phone">Phone Number:</label>

<input type="tel" id="phone" name="phone" required><br><br>

<label for="address">Address:</label>

<textarea id="address" name="address" rows="4" required></textarea><br><br>

<label for="course">Course:</label>

<select id="course" name="course" required> <option value="math">Mathematics</option> <option value="science">Science</option> <option value="history">History</option> <option value="english">English</option> </select><br><br>

<label for="gender">Gender:</label>

<input type="radio" id="male" name="gender" value="male" required> <label for="male">Male</label>

<input type="radio" id="female" name="gender" value="female" required> <label for="female">Female</label> <input type="radio" id="other" name="gender" value="other" required> <label for="other">Other</label><br><br>

<button type="submit" value="Submit">Submit</button> </form> </body> </html>

Output

Form Attributes

Forms can have various attributes to control the behaviour of a form:

• Action: Specifies the URL to which form data will be submitted.

• Method: Specifies the HyperText Transfer Protocol (HTTP) method to be used (either "GET" or "POST"). GET is better for submitting non-sensitive information, whereas POST is used to submit sensitive information.

• Name: Assigns a name to the form for easy identification.

• Target: Specifies where to display the response after form submission (e.g., in the same window or in a new one). It takes any one value from the _blank, _self, _parent and _top values.

Here is an example of a form with attributes:

Did You Know?

HTML forms not only collect user data but can also be used for interactive quizzes, surveys, and feedback on websites. They are versatile tools for engaging with online visitors.

<form action="submit_student_details.php" method="post" target="_blank">

The form action is set to ‘submit_student_details.php’, which is where you can process the form data on the server side.

The form method is set to ‘POST’, signifying the HTTP method used.

Form Validation

Form validation is crucial to ensure that users provide the correct type of information. HTML introduced built-in form validation, using attributes like required, min, max, and pattern.

For example:

<label for="age">Age:</label>

<input type="number" id="age" name="age" required min="18" max="99">

The required attribute makes the field mandatory, and min and max specify the acceptable value ranges. The pattern attribute can be used to enforce a specific format such as a valid email address.

Setting Properties of a Form Using Internal CSS

Setting properties of a form using internal CSS is also known as embedded CSS or inline CSS. You can make your HTML forms look attractive and arrange them on your web page by using the <style> element. This <style> element is placed in the <head> section of your HTML document.

Steps to set properties of a form using internal CSS are:

1 Open an HTML Document: Start by creating a standard HTML document structure, including the <!DOCTYPE html>, <html>, <head>, and <body> elements.

2 Include the <style> Element: Inside the <head> section of your HTML document, include a <style> element. This element is where you will define the CSS rules for styling your form elements.

3 Select the Form Element: To target the form you want to style, use the form selector. For example, to style all forms in your document, you can use form {}. To style a specific form, you can use an ID or class selector like #myForm {}.

4 Define CSS Properties: Within the selected form CSS block, you can define various CSS properties to control the appearance of the form. Common properties include width, margin, padding, background-color, border, border-radius, font-size, color, and many more. You can style form elements individually or collectively.

5 Style Form Elements: Inside a form block, you can target specific form elements such as labels, input fields, buttons, and other related elements. Use CSS selectors such as label {}, input[type="text"] {}, and input[type="submit"] {} to style these elements individually.

6 Save and Apply: When you have defined your internal CSS rules, save the HTML document. When you load the HTML document in a web browser, the CSS styles you have defined will be applied to the form elements.

Code

<html> <head>

<title>Form Styling</title> <style>

/* Internal CSS styles for the form */ form { width: 400px; /* Set the width of the form. */ margin: 0 auto; /* Center-align the form. */ padding: 50px; /* Add some padding for spacing. */ background-color: #f2f2f2; /* Set the background colour.*/ border: 1px solid #ccc; /* Add a border. */

}

/* Style for form labels */ label { display: block; /* Display labels as block elements for better spacing. */ margin-bottom: 10px; /* Add some space between labels */ font-weight: bold; /* Make labels bold. */ }

/* Style for form input fields */ input[type="text"], input[type="email"] { width: 100%; /* Set input fields to 100% width. */ padding: 10px; /* Add padding for input fields. */ margin-bottom: 15px; /* Add space between input fields. */ border: 1px solid #ccc; /* Add a border to input fields. */ }

/* Style for the submit button */ input[type="submit"] { background-color: #007bff; /* Set a background colour for the button. */ color: #fff; /* Set text color to white. */ padding: 10px 20px; /* Add padding for the button. */ border-radius: 3px; /* Add rounded corners to the button. */ }

</style> </head> <body> <form>

<label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="email">Email:</label> <input type="email" id="email" name="email"> <button type="submit" value="Submit">Submit</button> </form> </body> </html>

Did You Know?

HTML forms can be styled extensively using CSS to match website design and branding for creating visually appealing and cohesive user interfaces.

1 Who am I?

a I am a button that allows users to select one option from a list.

b I am a form attribute that specifies the URL to which the form data will be submitted.

c I am an HTML element that makes a form look attractive, and I am placed in the <head> section of the HTML document.

2 Answer the following questions.

a Explain the ‘method’ attribute of a form.

b What is the use of radio buttons in an HTML form?

Chapter Checkup

1 HTML is used to create a space where users can provide information by using various interactive options.

2 The element is used for long text input, such as comments or messages.

3 The type attribute is used for radio buttons, allowing users to select one option from a list.

4 The attribute makes a field mandatory in an HTML form.

5 Setting properties of a form using internal CSS is also known as CSS.

B Tick () the correct option.

1 Which of the following HTML elements is used to create a container for form elements?

a <input> b   <form>

c <label> d   <select>

2 Which of the following input types is used for collecting the name of a student?

a email b   text

c password d   radio

3 Which of the following elements helps create a drop-down menu in HTML forms?

a <select>

c <textarea>

4 Which attribute can be used to apply a specific format?

a required

b   <input>

d   <button>

b   specific

c validate d   pattern

5 What is the purpose of the <button> element in HTML forms?

a To display text b   To create hyperlinks

c To submit the form d   To add images

C Write T for True and F for False.

1 Form validation is crucial to ensure that users provide correct information.

2 The <input> element can collect various types of input, including text, email addresses, and passwords.

3 Check boxes allow users to select only one option from a list.

4 The ‘action’ attribute in a <form> element specifies where the form data will be submitted.

5 HTML introduced in-built form validation, using attributes like ‘required’ and ‘min’.

D Answer the following questions.

1 What is the primary purpose of the HTML <form> element in web development?

2 What is the purpose of form validation in HTML? Name the attributes that support form validation.

3 How can internal CSS (embedded) be used to style HTML forms?

4 Name the various attributes that control the behaviour of a form.

5 What is the <input> element? Explain any two <input> fields with their syntax.

E Apply your learning.

1 Create a simple HTML form for receiving parents’ feedback on a school event. Include fields for the student and parent names, class, section, email address, and comments. Apply form validation to ensure that all fields are filled correctly. Use internal CSS to style the form. Customise the background colour, font styles, and appearance of the ‘Submit’ button on the form.

2 Imagine that you are conducting a survey about students’ favourite school subjects. Design an HTML form with radio buttons for subjects such as Mathematics, Science, History, and English. Allow the students to select their favourite subject and submit their choice.

3 Create a basic HTML form for an ice-cream parlour where customers can indicate their preferred ice-cream flavours. The HTML form should include check boxes with these options: chocolate, vanilla, choco-chip, strawberry, and butterscotch. Ensure that users can select multiple flavours and provide a ‘Submit’ button at the end to complete the submission process.

Inserting Multimedia in HTML 6

Multimedia elements like images, links, audio, and video are used to enhance the user experience on a web page. They are used to make the content more informative. Let us learn how to insert different types of multimedia in HTML.

Adding Images

The <img> tag of HTML allows us to add images to the web page. The attributes of the <img> tag are as follows:

Attribute

Description

Alt Used to specify the alternate text which appears only if the specified image is not loaded due to some reason.

Height Used to specify the height of the image.

Src Used to specify the path of the image.

Width Used to specify the width of the image.

Apart from src, all attributes are optional to use with the <img> tag. Height and width of the image can also be set with the height and width properties of CSS.

Let us create a web page to display images of famous Indian mathematicians with information about them:

Code

<html> <head>

<title>Famous Indian Mathematicians</title> <style> body { font-family: sans-serif; margin: 0; padding: 0; box-sizing: border-box; } h1 { background-color: lightgreen; color: green; text-align: center; padding: 1em; } .main {

display: flex; justify-content: space-around; flex-wrap: wrap; padding: 20px; }

.mathematician-card { border: 1px solid #ddd; border-radius: 8px; margin: 10px; padding: 15px; width: 300px; box-shadow: 0 4px 8px; }

.mathematician-card img { max-width: 100%; border-radius: 4px; }

</style> </head> <body>

<h1>Famous Indian Mathematicians</h1>

<div class = "main">

<div class="mathematician-card">

<img src="ramanujan.jpg" alt="Srinivasa Ramanujan">

<h2>Srinivasa Ramanujan</h2>

<p>Contributions: Number Theory, Mathematical Analysis</p> </div>

<div class="mathematician-card">

<img src="shakuntala-devi.jpg" alt="Shakuntala Devi">

<h2>Shakuntala Devi</h2>

<p>Contributions: Mental Calculation, Author of Mathematics Books</p> </div>

<div class="mathematician-card">

<img src="abhay-ashtekar.jpg" alt="Abhay Ashtekar">

<h2>Abhay Ashtekar</h2>

<p>Contributions: Quantum Gravity, Loop Quantum Gravity</p> </div> </div> </body> </html>

While creating this web page, place the images with the same names at the same location where the web page is saved.

Creating Links

The <a> tag is used to create links in HTML. A link, also known as hyperlink, is a text with the functionality to navigate you to some other web page of the website. The <a> tag is also known as anchor tag. This tag helps us to interlink several web pages of a website, even we can link other websites too. The attributes of the <a> tag are as follows:

Attribute Description

href

It takes the URL of the web page that will open when the link is clicked. download It allows a file to download when the link is clicked. It does not take any value.

We can arrange the links with the help of <nav> tag. The <nav> tag allows us to create a set of links.

Let us create a navigation bar with the help of <a> and <nav> tags.

Code

<html> <head> <title>Home Page</title> <style>

h1 { background-color: purple; color: white; text-align: center; padding: 1em; } nav { background-color: grey; overflow: hidden; }

Srinivasa Ramanujan Contribution: Number Theory, Mathematical Analysis
Shakuntala Devi Contribution: Mental Calulation, Author of Mathematics Books
Abhay Ashtekar Contribution: Quantum Gravity, Loop, Quantum Gravity

Code

nav a { float: left; display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; }

nav a:hover { background-color: olive; color: white; } </style> </head> <body> <h1>Navigation</h1> <nav>

<a href="https://uolo.com/index.html">Home</a>

<a href="https://uolo.com/about-us.html">About Us</a>

<a href="https://uolo.com/request-demo.html">Contact</a> </nav> </body> </html> Output

When we hover over the links, the colour of the background of the link is changed.

1 Write one or two lines of code for the following: a To embed ‘flower.jpg’ image on a web page Do It Yourself 6A

b To create a link with the text ‘Flower’ for downloading ‘flower.jpg’ image

2 Write the CSS code to set the border of an image as 10px.

Adding Audio

HTML provides the <audio> tag to insert audio files to a web page. The <source> tag is used with the <audio> tag to specify the path of the audio file. There can be more than one <source> tag inside the <audio> tag. The browser chooses any one <source> tag at a time. Currently HTML supports .mp3, .wav, and .ogg audio formats.

Attributes of the <audio> tag are as follows:

Attribute Description

Autoplay It specifies that the audio will start playing as soon as the web is loaded in the web browser. Controls It specifies that audio controls should be displayed (such as a play/pause button etc).

Loop It specifies that the audio will start over again, every time it is completed.

Muted It specifies that the audio output should be muted.

Src It specifies the URL of the audio file.

Except src attribute, all attributes do not take any value. They are simply written in the opening tag.

Let’s create a web page to add audio file:

Code Output

<html> <head>

<title> Adding Audio </title> </head> <body>

<h1>Let’s Play Music</h1> <audio controls loop> <source src="music.mp3"> </audio> </body> </html>

The audio file is added to the web page with controls. You can pause the audio, increase/decrease the volume of sound, forward/reverse audio, etc.

Adding Video

Similar to audio, HTML allows us to add video to a web page using the <video> tag. The <source> tag is used with the <video> tag to specify the path of the video file. There can be more than one <source> tag inside the <video> tag. The browser chooses any one <source> tag at a time. Currently HTML supports .mp4, .webm, and .ogg video formats. The attributes of the <video> tag are as follows:

Attribute

Description

autoplay It specifies that the video will start playing as soon as the web is loaded in the web browser. controls It specifies that video controls should be displayed (such as a play/pause button etc). height It specifies the height of the video player.

loop It specifies that the video will start over again, every time it is completed. muted It specifies that the audio output of the video should be muted. src It specifies the URL of the video file. width It specifies the width of the video player.

Except src, height, and width attributes, all attributes do not take any value. They are simply written in the opening tag.

Let’s create a web page to add a video:

Code Output

<html> <head> <style> video { border: 5px groove darkblue; padding: 30px; width: auto; height: auto; } </style> <title> Adding Video </title> </head> <body> <h1>Let’s Play Video</h1> <video controls> <source src="video.mp4"> </video> </body> </html>

Let’s Play Video

The video is displayed on the web page. You can pause the video, increase/decrease the volume of sound, forward/reverse the video, view the video on full screen, etc.

Discuss

What will happen if the specified audio/video is not found at the specified path?

1 Match the following questions.

CSS Sets the background colour of the HTML element.

background-color

Aligns the text horizontally within a box.

margin Allows us to change the look and feel of the web pages.

text-align Sets the space around the element itself.

2 Write the names of any three attributes of the <audio> tag.

Coding Challenge

Take photos of any four national symbols of India and create a web page to display them. The name of each national symbol should appear at the top of the photo. Photos should work as hyperlinks, and when the user clicks on any photo, a web page appears containing the larger photo of it.

Chapter Checkup

A Fill in the blanks.

Hints controls  audio  images  URL

1 The <img> tag allows us to add to the web page.

2 The href attribute in the <a> tag takes the of the web page that will open when the link is clicked.

3 The <audio> tag in HTML provides the functionality to insert files in a web page.

4 The controls attribute in the <video> tag specifies that video should be displayed.

B Tick () the correct option.

1 Which of the following attributes of the <img> tag is used to specify the path of the image? a alt b   src c width d   height

BHARAT

2 Which attribute of the <audio> tag specifies that the audio will start playing as soon as the web page is loaded? a controls b   loop c autoplay d   muted

3 The <a> tag is also known as: a image tag b   source tag c anchor tag d   video tag

4 Which of the following video formats is supported by HTML? a mp4 b   avi c mkv d   mov

C Who am I?

1 I am a tag used to create links in HTML.

2 I am a tag used to embed audio content in a web page.

3 I am a tag used to embed video content in a web page.

4 I am an attribute of the <audio> tag that specifies which audio controls should be displayed.

D Write T for True and F for False.

1 The alt attribute in the <img> tag specifies the URL of the image file.

2 The loop attribute in the <audio> tag specifies that the audio will start over again every time it is completed.

3 The <nav> tag is used to create a set of links in HTML.

4 The width and height attributes of the <img> tag are required attributes.

E Answer the following questions.

1 Explain the purpose of the alt attribute in the <img> tag.

2 How can you specify multiple audio sources in an <audio> tag?

3 What is the function of the <nav> tag in HTML?

4 Describe how the controls attribute in the <audio> and <video> tags enhances the user experience.

F Apply your learning.

1 Create an HTML snippet to display an image of the scientist Srinivasa Ramanujan with a width of 300 pixels and a height of 400 pixels.

2 Create a hyperlink that directs the user to Wikipedia’s main page when clicked.

3 Write HTML code to embed an audio file named "example.mp3" with controls enabled.

4 Write HTML code to display an image and a hyperlink to download the image file when clicked.

Test

A. Fill in the blanks.

1 The rules that define the structure of a language are referred to as .

2 A single-line string can be enclosed in either quotes or quotes.

3 A can hold multiple values in a single variable.

4 A is used to access and view web pages.

B. Tick () the correct option.

1 What is the name of the operator // in Python?

a  Exponentiation b  Modulus

c  Floor division d  Multiplication

2 is used to lower the text below the baseline.

a  Superscript b  Subscript

c  Emphasise d  Bold

3 Which of the following HTML elements is used to create a container for form elements?

a  <input> b  <form>

c  <label> d  <select>

C. Write T for True and F for False.

1 Operators are predefined symbols that perform operations on one or more operands.

2 The eval() function evaluates a string expression and returns the result.

3 The margin sets the space around the content of the element.

4 The <source> tag is used with the <audio> tag to specify the path of the audio file.

D. Answer the following questions.

1 What are the different types of conditional statements?

2 How can you access elements of a list?

3 What are some attributes that can control the behaviour of a form?

E. Apply your learning.

1 Write a Python program that concatenates two strings, “Good” and “Morning”, and prints the result.

2 Write a code to create a tuple T with the given data: 7, ‘Alia’, 7, 4, ‘Jiya’

3 Write a program to calculate the area of an equilateral triangle with a side length of 10 cm.

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-8-7

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.