Tekie_G7_Coding_CBSE_AY24_Final

Page 1

About the Book This coding book is supplementary to the main “Mel n 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 graduation with real-life examples and practice problems.

Special Features • Illustrative approach: Concepts in coding and computer science are delivered through pictorial representations and learner-friendly approaches. • Learning through real-life examples: Age-appropriate examples that enable learners to relate to the concept and learn about the unknown from the known. • Extensive practice: Multiple practice scenarios to reinforce learnings. • Coding challenges: Includes projects through which learners can demonstrate their learning outcomes in coding and computer science.

About Uolo Uolo partners with K-12 schools to bring technology-based learning programs. We believe pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. Uolo is trusted by over 10,000 schools across India, South East Asia, and the Middle East.

Singapore

|

CS_CB_Coding_Grade7_Cover.indd All Pages

Gurugram

|

Bengaluru

|

hello@uolo.com �199

© 2024 Uolo EdTech Pvt. Ltd. All rights reserved.

NEP 2020 based

|

NCF compliant

|

Technology powered

04/12/23 1:30 PM



Computer Science Computer Science

Python II Web Development II

CODE_ORG CODING BOOKLET_LO_ED_FM_P1.indd 1

11/27/2023 4:18:58 PM


CODE_ORG CODING BOOKLET_LO_ED_FM_P1.indd 2

11/27/2023 4:18:58 PM


Contents Python 1

Introduction to Python

1

What is Programming?

Types of Programming Languages Introduction to Python Comments Data Types Variables

Simple Calculator Dynamic Typing Strings

Type Casting 2 Control Statements in Python

22

Conditional Statements and Comparison Operators Types of Conditional Statements Logical Operators Loops

Infinite Loop 3 Functions in Python

41

Functions

Arguments and Parameters Return Value

Recursive Functions

iii

CODE_ORG CODING BOOKLET_LO_ED_FM_P1.indd 3

12/6/2023 4:31:37 PM


Web Development 4 Introduction to Web Development

51

HTML

Basic Structure of an HTML Document Basic HTML Terminologies CSS

5 Images and Hyperlinks in HTML

64

Adding Images Styling Images Flexbox

Hyperlinks 6 Lists and Tables in HTML

81

Adding Lists Styling Lists Tables

iv

CODE_ORG CODING BOOKLET_LO_ED_FM_P1.indd 4

12/6/2023 4:31:37 PM


1

Introduction to Python

What Is Programming? Programming is the process of giving instructions to a computer about how to do a task. But instead of giving the instructions verbally, you write them down in a language that a computer can understand. This language is called a programming language. A task is a piece of work to be done. In a program, it may represent a section of the program. A programming language has its own vocabulary and syntax just as we have in English, Hindi and other languages.

Types of Programming Languages Programming languages are classified into two main categories:

• Low-level Languages • High-level Languages

Low-level Language Low-level languages (LLL) are machine-friendly languages that are closer to the machine and harder for humans to understand. They are used to control the hardware of the computer. Machine language and assembly language are examples of low-level languages. These languages communicate with the computer directly, so no language translation is required. The instructions in the machine language are written using 0s and 1s, which are known as binary digits. On the other hand, symbolic names, also known as mnemonics, are used in assembly language for writing programs.

High-level Language High-level languages (HLL) are user-friendly and easier to use than low-level languages. They are used for various tasks like making games, websites, and analysing data. Java, Python, and C are examples of HLLs. HLLs make programming simpler because they use words that are human readable like English language words, instead of the hardto-remember 0s and 1s of machine language. But, before a computer can run an HLL program, it needs to be translated into LLL.

1

CO24CB0701_P1.indd 1

11/29/2023 10:38:34 AM


Feature

HLL

LLL

Ease of use

Easier to understand and use

More difficult to understand and use

Purpose

Used for making games, websites, and analysing data

Used to control the computer hardware

Translation

Requires translation into LLL before execution

No translation required

Examples

Java, Python, C

Machine language, assembly language

In this book, we will learn Python, which is the most widely used programming language.

Introduction to Python Python is a high-level programming language that is easy to learn and simple to use. It is a “batteries included” language, which means that it comes with a lot of pre-installed features. This makes it simple to start programming without having to learn a lot of complicated material. It was created by Guido van Rossum and first released in 1991.

Python

Features of Python Here are some of the features of Python: 1

Easy to read: Python code is easy to read, just like English.

2 Quick to learn: Python has few keywords, a simple structure, and a clearly defined syntax. This makes it easier to learn and understand, even for beginners. 3 Easy to maintain: Python source code is easy to maintain and update. 4 Interactive execution mode: Python offers script and interactive modes for running programs. The code can be interactively tested and debugged in the interactive mode.

Did You Know? Python is named after a famous British comedy group called Monty Python.

A three-step loop process defines how Python is run in the interactive window: • The Python interpreter first reads the code entered at the prompt.

• Then it evaluates the code. • Finally, it prints the outcome and awaits new input.

5 Dynamic typing: Python defines data type dynamically for the objects according to the value assigned. It also supports dynamic data type checking. 6 Portable: Python is a portable language because it can be used on a variety of hardware platforms. 7 Large database support: Python provides interfaces to all major commercial databases. 8 GUI application creation: Python also supports the creation of Graphical User Interface (GUI) applications. 9 Scalable: Python provides better structure and support for larger programs than shell scripting. This makes it scalable.

2

CO24CB0701_P1.indd 2

11/29/2023 10:38:35 AM


Syntax Like any language, programming languages have their own sets of rules for writing programs. These rules, called syntax rules, tell us how to write programs in that language. Python is not different; it has its own rules that we must follow when writing code. One important rule in Python is that it’s case-sensitive. This means that ‘nUm,’ ‘Num,’ and ‘num’ are considered different things in Python.

Built-in Functions In Python, there are numerous built-in functions readily available. A function is a block of code used to perform a specific task. Built-in functions are functions predefined in the Python programming language. These functions can be used without the need to define them yourself. One of the built-in functions is the print() function. The print() Function The print() function displays a value or information in the output. Syntax: print(“value“) Code

Output

print(“Hello kitty!”)

Hello kitty!

Code

Output

print(25)

25

But how does a Python code get executed?

Execution of a Python Code The Python interpreter runs the code line by line and displays the results until an error occurs. It changes the HLL-written source code into bytecode, an intermediate language, which is then converted back into machine language and executed.

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 3

3

11/29/2023 10:38:35 AM


Comments We use comments to add documentation to a Python program. Python ignores these lines of comments in the program during execution as they are not part of the code.

Benefits of Using Comments Let us learn some benefits of Comments:

• They structure the code and make it easier for humans to read. • They explain the thought process and intentions behind the code. • They help find errors and debug the code. Debugging means to rectify errors.

After all, there is a popular saying, “Anyone can write code that a computer can understand. Good programmers write code that humans can understand.”

Types of Comments In Python, we have two types of comments:

• Single-line Comment • Multi-line Comment Single-line Comment

A single-line comment starts with a hash character ( # ) and is followed by related information. Code

Output

#using the print command

Learn Programming

print(“Learn Programming”) Multi-line Comment A multi-line comment begins and ends with three single or double-quote characters (‘ ‘ ‘ or “ “ “) with related information enclosed. Code

Output

“””

hello#world

Printing hello world with the sep command

hello world$

Printing hello world with an end command “”” print(“hello”, “world”, sep = “#”) print(“hello”, “world”, end = “$”) The sep command is used to add a separator between values given in the print() function. The end command prints the specified character with it at the end of the values given in the print() function.

4

CO24CB0701_P1.indd 4

11/29/2023 10:38:35 AM


Data Types In Python, every value has a data type. Data types define the type of data that a variable can store. There are two categories of data types in Python: Immutable and Mutable.

• Immutable data types are those whose values cannot be changed once declared. • Mutable data types are those whose values can be changed at any time. Python Data Types

Immutable

Mutable

Numbers

Strings ‘python@123’

Tuples (4,3.5, ‘b’)

Integer 4

Float 34.5

Complex 1+4j

Lists [4, ‘b’, 6.5]

Dictionaries {1: ‘a’, 2: ‘b’}

Sets {2, 5, 7}

Boolean (True, False)

Look at the table. It shows the different data types and their descriptions. Name

Type

Description

Integer

int

Whole numbers, like 15, 200, and 275.

Floating point

float

Numbers with a decimal point, like 4.3, 7.6, and 340.0.

String

str

Ordered sequences of characters, like “Python”, “hello”, “1495”, and “SV”.

List

list

Ordered sequences of objects, like [“hello123”, 40, 107.5].

Dictionary

dict

Unordered key-value pairs, like {“key”: “value”, “language”: “Python”}.

Tuple

tuple

Ordered immutable sequences of objects, like (50, “python”, 208.7).

Set

set

Unordered collections of unique objects, like {“apple”, “bird”}.

Boolean

bool

Logical value indicating True or False.

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 5

5

11/29/2023 10:38:36 AM


Variables A variable is a reference name given to a location in the computer’s memory. It allows you to store a value in that location and refer to it as needed. Variables can be used to store numbers, strings, lists, and other data types. They are just like a label that can be changed.

num 5

Imagine a memory location as a box and a variable name as a label for that box. You can store a number in the box and label it as “num”. Whenever you need to use the number, you can easily find it by the label on the box.

Variable Value

21

You can even remove the label and put it on another box, or you can replace the number in the box as needed.

num

Creating a Variable

Variable Name

In Python, variable declaration and initialisation happen with a single step of assigning a value to a variable. Syntax: variable_name = value Assignment Operator (=) is used to assign a value to a variable. Code

Output

word = “Hi”

Hi 5

number = 5 print(word, number) We can also initialise multiple variables in one line. Syntax: var1, var2 = value1, value2 Code

Output

word, number = “hi”, 5

hi 5

print(word, number) Syntax Error Syntax errors are the mistakes in following the rules to write the code, such as wrong function names, missing quotes, brackets, etc.

6

CO24CB0701_P1.indd 6

11/29/2023 10:38:36 AM


Below are some examples of common syntax errors: 1 Missed double quotes Code

Output

print(Learn Python)

SyntaxError: invalid syntax

2 Missed symbols, such as a colon, comma, or brackets Code

Output

print(Learn Python

SyntaxError: incomplete input

3 Wrong operation on wrong type of values Code

Output

num = 5

TypeError: can only concatenate str (not “int”) to str

message = “Number is: “ + num 4

No variable for receiving value Code

Output

num = 5

SyntaxError: invalid syntax

=num+4 print(n1)

Rules of Naming a Variable There are certain rules we need to follow while naming a variable.

Think and Tell

Some rules are:

Will a syntax error prevent the program from running?

1 Instead of using spaces, you should use the underscore (_) symbol when naming variables. 2

A variable name must start with a letter or the underscore character. Code

Output

greeting_message = “Good Evening!”

Good Evening!

_number_ = 205

205

print(greeting_message) print(_number_) Code

Output

greeting%message = “Good day!”

SyntaxError: cannot assign to expression here

print(greeting%message)

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 7

7

11/29/2023 10:38:36 AM


3

As Python is a case-sensitive language, variable names are also case-sensitive. Example: old, Old and OLD are three different variables. Code

Output

num = 25

25

Num = 30

30

NUM = 45

45

print(num) print(Num) print(NUM) 4

A variable name can have numbers within it but cannot begin with a number. Code

Output

num_1 = 430

430

_num2 = 250

250

print(num_1) print(_num2) Code

Output

1num = 100

SyntaxError: invalid syntax

print(1num)

Variable Naming Styles in Python As we have case styles for words in English, we have some case styles for naming variables. Below are the case styles you can follow to name variables in Python: Camel Case

• The first letter of the variable is lowercase. • Each subsequent word’s first letter is capitalised. • No spaces or underscores. • Often used for variable and function names.

Example: “Name of the company” can be written as “name Of The Company”. As this represents the camel’s hump we call it Camel-Case. Code

Output

camelCaseExample = “Hello Camel”

Hello Camel

print(camelCaseExample)

8

CO24CB0701_P1.indd 8

11/29/2023 10:38:37 AM


Snake Case

• All letters are lowercase. • Words are separated by underscores (_). • Often used for variable and function names.

underscore

Example: “name of the company” in snake-case is written as “name_of_ the_company”. Code

Output

snake_case_example = “Hello Python”

Hello Python

Snake_case lower_snake

print(snake_case_example) If we don’t follow the naming conventions or any syntax of a language, we may get Syntax Errors on executing our code.

Creating a Variable with User Input In Python, we can even create a variable with user input. To do so, we use a built-in function named input(). The input() Function The input() function in Python is used to allow input from the user. It is a built-in function. Syntax: name = input(“<message to be displayed>“) Code

Output

user_input = input(“Enter your favourite colour: “)

Enter your favourite colour: blue

Solved Examples Example 1.1 The side of a square is 80. Use camel case to name the variable area of a square. Calculate the area. Print the result. Answer: Code

Output

side = 80

The area is: 6400

areaOfSquare = side * side

print(“The area is: ”, areaOfSquare) Example 1.2 Below are the average temperatures of different places. Store them in different variables. The temperature has increased by 0.5 in the afternoon. Display the updated temperature of all the places. Average Temperatures of Places Place

Temperature

Met Town

25

Zo Hills

Bay Area

20 26

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 9

9

11/29/2023 10:38:37 AM


Answer: Code

Output

Zo_Hills=20

Place Updated Temperature Zo Hills 20.5

Met_Town=25

Met Town 25.5

Bay_Area=26

Bay Area 26.5

print(“Place”,”Updated Temperature”) print(“Zo Hills”, Zo_Hills+0.5) print(“Met Town”,Met_Town+0.5) print(“Bay Area”,Bay_Area+0.5)

Simple Calculator Let’s build a simple calculator project while learning the concepts in the chapter. We will be building this project by dividing this into tasks. Task 1: Take two numbers and an operator as input from the user. Let’s create three variables and use the input() function to allow input from the user. Code num1 = input(“Enter first number: “) operator = input(“Enter operator (+, -, *, /): “) num2 = input(“Enter second number: “) Now, before we execute the project, do you remember what Dynamic Typing is?

Dynamic Typing Dynamic typing is a feature of Python where the data type of a variable is not determined until runtime. This means that you can assign a variable to a value of any type, and the variable will automatically take on that type. The type() Function In Python, we use the type() function to check the dynamic data type assigned to a variable. It is a built-in function that returns the type of an object. The object can be a variable, a value, or an expression. Syntax: type(object_name)

10

CO24CB0701_P1.indd 10

11/29/2023 10:38:37 AM


Simple Calculator Task 2: Check the data type of user input. Code

Output

num1 = input(“Enter first number: “)

Enter first number: 4

operator = input(“Enter operator (+, -, *, /): “)

Enter operator (+, -, *, /): +

num2 = input(“Enter second number: “)

Enter second number: 6

print(type(num1))

<class ‘str’>

print(type(num2))

<class ‘str’>

print(type(operator))

<class ‘str’>

The input() function always returns a string value, even if it takes a number, operator, or any other value as input. And, since we have created variables with user input, all three variables are of string type.

Do It Yourself 1A 1 Identify the syntax error and correct the code:

a

score = 95 message = “Your score is: “ + score

Ans. b

number = 42

= type(number)

print(“The data type is: “ + str(data_type))

Ans. What will be the output of the given code? 2 Code

Output

a=7 print(type(a)) b = 3.0 print(type(b)) c=a+b print(c) print(type(c)) d=a*b print(d) print(type(d))

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 11

11

11/29/2023 10:38:37 AM


Strings A string is a data type that represents a sequence of characters. In Python, strings are put inside single quotes (‘ ’) or double quotes (“ ”). These values can be words, symbols, characters, numbers, or a combination of all these. There are two types of strings in Python:

• A single-line string • A multi-line string

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

Output

name1=“Mohit”

Mohit

name2=‘Mohit’

Mohit

print(name1) print(name2)

Multi-line String A multi-line string can be enclosed in either three single quotes (‘‘‘ ’’’) or three double quotes (“““ ”””). Code

Output

proverb_1= ‘’’Don’t judge

Don’t judge

a book

a book

by its cover. ‘’’

by its cover.

proverb_2= “””

Beauty is

Beauty is

in the eye of

in the eye of

the beholder.

the beholder. “”” print(proverb_1) print(proverb_2) The eval() Function The eval() function evaluates a string expression and returns the result. Syntax: result = eval(expression)

12

CO24CB0701_P1.indd 12

11/29/2023 10:38:37 AM


Code

Output

expression = “2 * 3 + 4 / 2”

8.0

result = eval(expression)

//Using variables within expressions:

8

x=5 y=3

expression = “x + y”

result = eval(expression) Simple Calculator Task 3: Pass the user input to the eval() function to evaluate it. Code

Output

num1 = input(“Enter first number: “)

Enter first number: 5

num2 = input(“Enter second number: “)

Enter second number: 8

operator = input(“Enter operator (+, -, *, /): “) print(“Result: “, eval(num1+operator+num2 ))

Enter operator (+, -, *, /): / Result: 0.625

Using the eval() function, our code can be completed very quickly. But it has the following limitations:

• It can be used to execute arbitrary code. This means that if an attacker can trick you into evaluating malicious code, they could take control of your computer system.

• It can be used to inject code into a running program. This means that an attacker could modify the behaviour of your program by injecting malicious code into it.

• It can be used to execute code that is entered by the user. This code could be malicious code that could steal the user’s data or take control of their browser.

• It can be slow. The eval() function has to parse the code that is being evaluated, which can take time. • It can be difficult to debug. If the code that is being evaluated contains errors, it can be difficult to track down the source of the errors.

For these reasons, it is important to use the eval() function with caution and to use it only when you are sure that the code that is being evaluated is safe. But there is another way to do this project. It is Type Casting.

Type Casting Type casting is conversion of the data type of a value into another data type. We can type cast a data type using type casting functions: 1

int()

2

float()

3

string()

4

bool()

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 13

13

11/29/2023 10:38:38 AM


The int() Function The int() function is used to typecast the value of a variable into an integer. It converts the following data type into an integer: 1

Float by removing the decimal point and everything after it.

2

String only if string represents a number.

3

Boolean by converting True to 1 and False to 0. Syntax: int(variable_name)

Code

Output

str_to_int = int(“8”)

8 <class ‘int’>

bool_to_int = int(True)

1 <class ‘int’>

print(str_to_int, type(str_to_int)) print(bool_to_int, type(bool_to_int)) Code

Output

number=int(“Hello”)

ValueError: invalid literal for int() with base 10: ‘Hello’

The float() Function The float() function is used to typecast the value of a variable into float. It converts the following data type into float: 1

Integer by adding a decimal followed by a zero.

2

String only if the string represents a float or an integer. Syntax: float(variable_name)

Code

Output

a=float(10)

10.0

b=float(“10.2”)

10.2

print(a) print(b) Code

Output

c=float(“Hello”)

ValueError: could not convert string to float: ‘Hello’

print(c)

14

CO24CB0701_P1.indd 14

11/29/2023 10:38:38 AM


The str() Function The str() function is used to typecast the value of a variable into a string. It converts all the data types including float, integer, and boolean into a string. Syntax: str(variable_name) Code

Output

num_1 = str(5)

5 <class ‘str’>

num_2 = str(7.2)

7.2 <class ‘str’>

print(num_1 , type(num_1)) print(num_2, type(num_2)) The bool() Function The bool() function is used to typecast the value of a variable into boolean. It converts the following data type into boolean: 1

Integer and prints False if the value of the variable is 0, otherwise prints True.

2

String and prints False if the string is empty, otherwise prints True. Syntax: bool(variable_name)

Code

Output

a=bool(0)

False True False True

b=bool(1) c=bool(“”) d=bool(“Python”) print(a,b,c,d) Simple Calculator Task 4: Typecast the numbers that the user inputs into floats. Code num1 = float(input(“Enter first number: “)) num2 = float(input(“Enter second number: “)) Next, we need to learn about operators we can use for various mathematical operations on numbers that the user inputs. Arithmetic Operators Arithmetic operators are the operators used with the integer or float values to perform mathematical operations on them.

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 15

15

11/29/2023 10:38:38 AM


There are 7 arithmetic operators in Python: Operator

Name

Description

Example

Result

+

Addition

Adds two values together

4+2

6

-

Subtraction

Subtracts one value from another

7-5

2

*

Multiplication

Multiplies two values

5*2

10

/

Division

Divides one value by another

7/2

3.5

%

Modulus

Returns the division remainder

5%2

1

**

Exponent

Returns the exponent of a number

3**2

9

//

Floor Division

Returns floor value of the division

7//2

3

Example 1.3 Write a program to get the right answers to the questions given below. a = 23 b = 13

Think and Tell Can we multiply a string by a float value in Python?

a) Addition of a and b. b) Multiplication of a and b. c) Division of a and b. d) Base a to the power b. e) Modulus of a%b Answer: Code

Output

a,b=23,13

Addition of a and b is: 36

print(“Addition of a and b is:”,a+b)

Multiplication of a and b is: 299

print(“Multiplication of a and b is:”,a*b)

a divided by b is: 1.7692307692307692

print(“a divided by b is:”,a/b)

Base a to the power b is: 504036361936467383

print(“Base a to the power b is:”,a**b)

Remainder, when a is divided by b, is: 10

print(“Remainder, when a is divided by b, is:”,a%b) PEMDAS rule Python follows the PEMDAS rule, which stands for: 1 Parentheses (P)

2 Exponents (E)

3 Multiplication (M)

4 Division (D)

5 Addition (A)

6 Subtraction (S)

This rule tells us the order in which operations are performed in an expression.

16

CO24CB0701_P1.indd 16

11/29/2023 10:38:38 AM


Operations within parentheses are performed first, followed by exponents, multiplication and division from left to right, and finally addition and subtraction from left to right. Example: 9 + 7 * (8 - 4) / 2 - 3**2

(First, the brackets are solved.)

= 9 + 7 * 4 / 2 - 3**2

(Then, the exponent is solved.)

=9+7*4/2-9

(Then, multiplication is solved.)

= 9 + 28 / 2 - 9

(Then, division is solved.)

= 9 + 14 - 9

(Then, addition is solved.)

= 23 - 9

(Finally, subtraction is solved.)

= 14 Simple Calculator Task 5: Apply all four basic arithmetic operations ( +, - , *, / ) to the numbers the user inputs. Code

Output

num1 = float(input(“Enter first number: “))

Enter first number: 6

num2 = float(input(“Enter second number: “))

Enter second number: 8 Addition: 14.0

add = num1+num2

Subtraction: -2.0

sub = num1-num2

Multiplication: 48.0

mul = num1*num2

Division: 0.75

div = num1/num2 print(“Addition: “, add) print(“Subtraction: “, sub) print(“Multiplication: “, mul) print(“Division: “, div)

Do It Yourself 1B 1 Write the output of the following expressions: Code

Output

54+12 45-17 3**4 10%100 175/5 Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 17

17

11/29/2023 10:38:38 AM


2 Write the output of the following code: value = True + False + True print(value)

Chapter Checkup A

Fill in the Blanks. Hints

eval()

1

A

allows you to store a value on that location and refer to it as needed.

2

A variable name must start with a

underscore

syntax errors

or the

letter

dynamic typing

character.

3

are mistakes in following rules to write the code.

4 that type.

means we can assign a variable to a value of any type, and the variable will automatically take on

5 B

variable

The

function evaluates a string expression and returns the result.

Tick () the Correct Option. 1

Which of the following is used to write comments in Python?

a // 2

c

#

d

--

Which of the following data types in Python is mutable?

a String 3

b /* */ b Integer

c List

d Tuple

What does the eval() function do?

a It evaluates a string expression and returns the result. b It can be used to execute arbitrary code. c It can be used to inject code into a running program. d All of the above.

4

What is the output of the following code?

x = 10

y = “Hello, world!” print(x + y)

a 10Hello, world! b TypeError: unsupported operand type c Hello, world!10 d 10

18

CO24CB0701_P1.indd 18

11/29/2023 10:38:38 AM


5

What is the output of the following code snippet?

x=5

y = “Hello”

result = str(x) + y

print(result) a 5Hello C

D

E

c Hello

d Error

Who Am I? 1

I am a type of data that can be changed after being created.

2

I am a variable naming style where words are separated by underscores.

3

I am the process of converting one data type into another.

4

I am an acronym that represents the order of operations in mathematical expressions in Python.

5

I am the function used for converting a value into a floating-point number.

Write T for True and F for False. 1

Comments in Python are executed as part of the program.

2

Single-line strings can be enclosed in either single quotes or double quotes.

3

Variable names in Python are case-sensitive.

4

Dynamic typing is a feature of Python where the data type of a variable is determined at compile time.

5

The type() function returns the data type of a variable.

Answer the Following. 1

What are the two main categories of data types in Python?

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 19

b Hello5

19

11/29/2023 10:38:39 AM


2

Write the output of the codes in the given space. a. x = 5.7 y = int(x) print(y)

b. x = 5 y = 10 result = eval(“x + y”) print(result)

Output 3

What is the difference between mutable and immutable data types in Python?

4

What will be the output of the code?

a = “Hello”

b = “World”

c=a+““+b

print(c * 3)

5

F

In Python, what does the input() function return after reading user input from the console?

Apply Your Learning. 1

Write a Python program that takes two numbers as input from the user and displays their average.

Write a program to keep track of a user’s expenses. Choose appropriate variable names to store the user’s name, 2 total expenses, and the category of expenses (e.g., “Food,” “Transportation”).

Display a message like “John spent $50 on Food.”

Write a Python program to calculate the area of a circle. Include a comment explaining the formula you used for 3 calculating the area.

20

CO24CB0701_P1.indd 20

11/29/2023 10:38:39 AM


4

Write a program to find the sum of all the stationery you purchased from a shop: Sr. No

Item Name

Item Price

1

Pen

25

2

Pencil

8

3

Notebook

45

4

Colours

88

Write a program to take a temperature in Fahrenheit as input from a user and convert it to Celsius, then print the 5 result.

Chapter 1 • Introduction to Python

CO24CB0701_P1.indd 21

21

11/29/2023 10:38:39 AM


Control Statements in Python

21

Control statements in Python are used to control the flow of execution of the program. They allow you to make decisions, repeat code, and skip code. There are three main types of control statements in Python:

• Conditional Statements • Loops • Jump Statements

Imagine that a theatre program is going to happen at your school. What role would you like to play? Just like that, in life, we often find ourselves in situations where we need to make choices. This skill we have is called decision-making ability. But computers cannot make decisions on their own. We have to give them step-by-step instructions in a language they understand, like Python. In Python, we have what are called conditional statements.

Conditional Statements and Comparison Operators Conditional statements allow us to instruct the computer to check for a specific situation and make it do something if that situation occurs. A condition is set to establish criteria that require some form of comparison to be performed. Therefore, to define a condition, one must also understand the comparison operators. Comparison operators are the symbols or expressions that allow us to compare two values or variables. They compare the value on the left-hand side with the value on the right-hand side and return either ‘True’ or ‘False’ as the result of the comparison. These operators are also known as Relational Operators. Below are the six comparison operators in Python. Operator Name

Purpose

Example

==

Equal to

Returns True if both operands are equal

x==y

!=

Not Equal to

Returns True if operands are not equal

x!=y

>

Greater than

Returns True if the left operand is greater than the right

x>y

<

Less than

Returns True if the left operand is less than the right

x<y

>=

Greater than or equal to Returns True if the left operand is greater than or equal to the right

x>=y

<=

Less than or equal to

x<=y

Returns True if the left operand is less than or equal to the right

22

CO24CB0702_P1.indd 22

11/29/2023 10:42:08 AM


Let us look at the examples to understand the usage of comparison operators. Solved Examples Example 2.1

Think and Tell

Johnny needs to determine whether the number of balls in box A is equal to, less than, or greater than the number of balls in box B. Box A contains 453 balls, and box B contains 454 balls. Using comparison operators, print whether the situations are ‘True’ or ‘False’.

What is the difference between the greater than operator (>) and the greater than or equal to operator (>=)?

Answer: Code

Output

box_A=453

Are balls in box A equal to box B? False

box_B=454

Are balls in box A less than box B? True

cond1=box_A==box_B print(“Are balls in box A equal to box B? “, cond1)

Are balls in box A more than box B? False

cond2=box_A<box_B print(“Are balls in box A less than box B? “, cond2) cond3=box_A>box_B print(“Are balls in box A more than box B?“, cond3) Example 2.2 Joe’s mother gives him ` 350 and asks him to buy some groceries from a nearby shop. He plans to purchase tomatoes for ` 50, onions for ` 60, and a jar of peanut butter for ` 100. 1 Using comparison operators, print ‘True’ or ‘False’ to help him determine whether the money his mother gave him will be enough to buy the planned items or not. 2 Joe intends to buy 2 more jars of peanut butter with the remaining money. Assist him in deciding if he has enough money to do so. Answer: Code

Output

price_tomato=50

The total money Joe has is: 350

price_onion=60

The total bill will be: 210

price_butter=100 total_money=350 print(“The total money Joe has is: “,total_money) total_bill=price_tomato+price_onion+price_butter

Is the money adequate to buy groceries? True The remaining amount Joe has left is: 140 Can Joe buy 2 more jars of peanut butter? False

print(“The total bill will be: “,total_bill) cond=total_money>total_bill print(“Is the money adequate to buy groceries? “,cond) remaining_money = total_money - total_bill Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 23

23

11/29/2023 10:42:08 AM


Code

Output

print(“The remaining amount Joe has left is:“, remaining_ money) cond2=remaining_money>(price_butter*2) print(“Can Joe buy 2 more jars of peanut butter?“, cond2)

Indentation and Code Blocks In Python programming, we use something called “indentation” to group together a set of statements into a specific block of code. Indentation helps Python understand which lines of code belong together and should be executed as a single unit. Indentation is a fixed number of spaces (or sometimes tabs) added at the beginning of each line of code. These spaces create a visual hierarchy in your program, just like paragraphs in a story or chapters in a book. Code

Interpreter view

Statement 1

Code block 1 begins

Statement 2

Code block 1 continues

Statement 4

What happens if you don’t indent your code properly?

Code block 3

Statement 5

Code block 2 continues

Statement 6

Code block 2 ends

Statement 7

Discuss

Code block 1 continues

Statement 3

Code block 1 ends

Algorithm and Flowchart Understanding algorithms and flowcharts is crucial as they form the foundation for comprehending how to plan and create computer programs. But what exactly are algorithms, and why are they important?

An ‘algorithm’ is a set of step-by-step instructions. It is a clear and precise plan that guides us to achieve a goal. We use algorithms not only in programming but also in our everyday lives. In programming, we write algorithms to instruct the computer how to perform specific tasks. It’s like giving the computer a set of directions to follow. Let us write an algorithm to find out if someone is eligible to vote or not. 1

Start

2 Input age 3 If age is greater than or equal to 18, then 4 Display “You are eligible to vote.” 5 Else

24

CO24CB0702_P1.indd 24

11/29/2023 10:42:08 AM


6

Display “You are not eligible to vote.”

7

End

We can represent this algorithm visually using a flowchart. A flowchart is a way to depict an algorithm visually. It uses shapes like circles, rectangles, and arrows, along with labels, to outline the steps in a process. Flowcharts serve as blueprints for a program, showing each step in the order it should happen. To create a flowchart, we use specific shapes, and each shape has a particular meaning. Elements of a Flowchart Symbol

l Symbol Symbol Symbol Symbol

Input orInput Input Input or or Input or or Name Start or End Arrows Input or Output Process Decision Name Name Name Name Process Process Process Process Process Arrows Arrows Arrows Arrows Arrows Decision Decision Decision Decision Decisio Start or Start End Start Start ororEnd End Start or End or End Output Output Output Output Output Purpose

Represents a start or end point

Represents Represents input Represents the Represents the the connection or output process or block decision or conditional ePurpose Purpose Purpose Purpose between twothe ofRepresents code (Output isthe Represents Represents Represents a Represents Represents a a a Represents a Represents Represents Represents Represents Represents Represents Represents Represents the Represents the the the Represents Represents Represents the Represents Represents the thestatement the Represents Represents the the Represents decision Represents the decision decision the decisi the shapes and usually True or False) start or end start startor start orend end or start end or end input or between input input input or or input or or or process connection connection connection between connection connection between between between process process process oror conditional orprocess orororconditional or conditional statement or conditional or conditional statement statement statem st the flow of the point point point point point output output output output output two shapes two two and shapes two shapes theshapes two and and shapes the and the the and the block of code block block block ofofcode code (Output block of code of is code (Output usually (Output (Output isisusually (Output usually is usually is us program flow of program flow flowof flow ofprogram program of flow program of program True or False) True Trueor True orFalse) False) or True False) or Fa Let us create a flowchart for the algorithm we created. Flowchart Start

Input age

If age>=18? Yes

No Display "You are not eligible to vote."

Display "You are eligible to vote."

End

Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 25

25

11/29/2023 10:42:09 AM


Do It Yourself 2A 1 Create a flowchart to check if a number is greater than 100 or not.

2 Create a flowchart to find and display the larger number between two numbers entered by the user.

Types of Conditional Statements In Python, we have three types of conditional statements that allow us to make decisions in our programs. These include:

• if Statement • if… else Statement • if… elif… else Ladder 26

CO24CB0702_P1.indd 26

11/29/2023 10:42:09 AM


The if Statement The ‘if’ statement is used to check a specific condition. If the condition following the ‘if’ keyword evaluates to True, the code block after the ‘if’ condition will be executed; otherwise, the code block will be skipped. Flowchart

true

if condition? false

Statement (s)

rest of code

Syntax:

if condition1:

# Statement to execute if condition1 is true

The colon (:) sign is used after the condition with the if statement. The statements inside the if statement should be properly indented. Code

Output

age = 21 if age >= 18: print(“Eligible to vote.”)

Eligible to vote.

The if… else Statement The ‘if… else’ statement checks a condition, allowing us to instruct the computer on what to do in both cases, whether the statement is true or false.

If the condition following the ‘if’ keyword evaluates to True, the code block after the if condition will be executed; otherwise, the code block after the ‘else’ keyword will be executed. Flowchart

if condition? False True Body of if

Body of else

Statement just below if

Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 27

27

11/29/2023 10:42:09 AM


Syntax:

if condition_1:

#Statements to execute if condition_1 becomes True

#Statements to execute if condition_1 becomes False

else:

Code

Output

age = 21

Eligible to vote.

if age >= 18:

print(“Eligible to vote.”)

else:

print(“Too young to vote!”)

The elif 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. Flowchart Start

False

If expr_1?

True

code block 1

elif expr_2? True False

elif expr_3?

code block 2 True

code block 3

False else code blok Stop

Syntax:

if condition_1:

Statement_1 elif condition_2:

Statement_2 .. ..

else:

Final_Statement

28

CO24CB0702_P1.indd 28

11/29/2023 10:42:09 AM


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 will be executed if none of the conditions are True. Let us update the project we created in the previous chapter using comparison operators and conditionals. Simple Calculator num1 = float(input(“Enter first number: “)) operator = input(“Enter operator (+, -, *, /): “) num2 = float(input(“Enter second number: “)) if operator == “+”: result = num1 + num2 elif operator == “-”: result = num1 - num2 elif operator == “*”: result = num1 * num2 elif operator == “/”: if num2 == 0: result = “Division by zero is not allowed.” else: result = num1 / num2 else: result = “Invalid operator.” print(“Result:”,result)

Do It Yourself 2B 1 Write a program to check if a number is greater than 100 or not.

2

Write a program to determine and print the larger number between two numbers entered by the user.

Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 29

29

11/29/2023 10:42:09 AM


Logical Operators Logical operators allow us to combine multiple conditions in one. There are three important logical operators in Python: ‘and’, ‘or’ and ‘not.’

The and Operator The ‘and’ operator allows us to combine two conditional statements and returns True only if BOTH statements are true. In all other cases, it returns False. If Statement 1 is True and Statement 2 is True, then the result is True. If either Statement 1 or Statement 2 (or both) is False, then the result is False. Syntax: Statement 1 and Statement 2 Following is the truth table for the AND operator: CONDITION 1

OPERATOR

CONDITION 2

RESULT

True

True

False

False

True

False

False

False

True True False

and

False Code

Output

print(3<7 and 8==8)

True

print(6>2 and 9==8)

False

The or Operator The ‘or’ operator allows us to combine two conditional statements and returns True if EITHER of the statements is true. It returns False only if BOTH statements are false. If Statement 1 is True or Statement 2 is True (or both), then the result is True. If both Statement 1 and Statement 2 are False, then the result is False. Syntax: Statement 1 or Statement 2 Following is the truth table for the OR operator: CONDITION 1

OPERATOR

True True

False

RESULT

CONDITION 2 True

or

False Code

Output

print(4+5>8 or 9!=7)

True

print(6>7 or 8==9.0)

False

True

False

True

False

False

True

True

Discuss What is the difference between the ‘and’ and the ‘or’ operator?

30

CO24CB0702_P1.indd 30

11/29/2023 10:42:09 AM


Multiple and/or Operators In Python, we have the flexibility to create complex conditional statements by using multiple ‘and’ and ‘or’ operators. When dealing with multiple conditional statements involving both ‘and’ and ‘or’, it’s important to know that ‘and’ takes precedence over ‘or’. This means that conditions with ‘and’ are evaluated first, followed by the conditions with ‘or’. Syntax: Statement 1 or Statement 2 and Statement 3 #First we solve the ‘and’ operator, and then the ‘or’ Code

Output

print(2>3 or 3==3 and 1>0)

True

Let us look at how we got the output for the given code: 2 > 3 or 3 == 3 and 1 > 0 False or True and True

#Solve and first

False or True #Solve or True Solved Example Write a program to help David pick students for his project. He has two rules: First, students must have at least 60% in their school grades. Second, they need a score of at least 7 in their analytical tests. Run the program to check if Ray and Joe meet David’s conditions. Ray has 65% in school and 8.5 in tests. Joe has 55% in school and 8 in tests. Answer: Code ray_academics=65 ray_analytical=8.5 print(“Ray’s scores:”) print(“Academics:”, ray_academics) print(“Analytical test:”, ray_analytical) ray_condition = ray_academics>=60 and ray_analytical>=7 print(“Does Ray meet David’s criteria?-”,ray_condition) joe_academics=55

Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 31

31

11/29/2023 10:42:09 AM


Code joe_analytical=8 print(“Joe’s scores:”) print(“Academics:”, joe_academics) print(“Analytical test:”, joe_analytical) joe_condition = joe_academics>=60 and joe_analytical>=7 print(“Does Ray meet David’s criteria?-”,joe_condition) Output Ray’s scores: Academics: 65% Analytical test: 8.5 Does Ray meet David’s criteria?- True Joe’s scores: Academics: 55% Analytical test: 8 Does Ray meet David’s criteria?- False

The not Operator The not operator reverses the result of the condition. True will be reversed to False, and vice versa. For example, not (True) will return False.

Loops When we write computer programs, there are times when we need to execute the same piece of code again and again. In that case, we have to write the same code again and again. This is not an efficient way of programming. But we can solve this using ‘loops’. Loops allow us to execute a set of instructions as long as a certain condition is True. Once that condition becomes False, the loop stops. This process is also known as iteration. Python provides mainly two types of loops, the while loop and the for loop.

The for Loop A ‘for’ loop is a way of telling a computer to do something over and over again. It can be used to repeat a block of code a certain number of times, or to go through a list of things one by one. A ‘for’ loop is also known as a counting loop. We use a variable to create the ‘for’ loop called the loop variable. Syntax:

for variable in sequence:

# Statements to be executed

32

CO24CB0702_P1.indd 32

11/29/2023 10:42:09 AM


Flowchart

item in sequence?

If no more item to iterate

Next item from sequence

Code to be executed

The two ways to create a ‘for’ loop: 1

Using the range() function.

2

Using the in operator.

Using range() Function The range() function in Python returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number. The range() function can be used in a ‘for’ loop to iterate over a sequence of numbers. Syntax:

for loop_variable in range(start, stop, step):

<statements>

where:

#the loop runs from start to stop-1

start is the starting number (optional, default is 0) stop is the ending number (not inclusive)

step is the increment (optional, default is 1) Code

Output

for num in range(0, 5):

0

print(num)

1 2 3 4

Here, the ‘for’ loop starts at 0 and counts up to 4, increasing by 1 each time. Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 33

33

11/29/2023 10:42:09 AM


Using the ‘in’ Operator The ‘in’ operator is a membership operator that checks if an item is a member of a sequence or not. It can be used in a ‘for’ loop to iterate over the items of a string, list, tuple, or dictionary. Syntax: for loop_variable in string_variable: <statements> Code

Output

word = ‘bumfuzzle’

b

for letter in word:

u

print(letter)

m f u z z l e

Here, the loop iterates over the letters of the string word, starting with the first letter ‘b’ and ending with the last letter ‘e’.

The while Loop The ‘while’ loop repeats a set of instructions as long as a condition is True. It is also known as a conditional loop. It verifies the condition before executing the loop. Flowchart

while

Condition

False

True

Code to be executed

34

CO24CB0702_P1.indd 34

11/29/2023 10:42:09 AM


Syntax:

while condition:

Statement 1 Statement 2 ... … Increment/decrement loop variable Code

Output

i=1

1

while i < 6:

2

print(i)

3

i += 1

4 5

Here, the ‘while’ loop starts with the value of i being 1. As long as i is less than 6, the loop will continue. In each iteration of the loop, the value of i is printed and then incremented by 1. The loop will stop when i is equal to 6.

The for versus while Loop The ‘for’ loop and the ‘while’ loop are both control flow statements in Python that are used to repeat a block of code. However, they have different usage scenarios. The ‘for’ loop is used to iterate over a sequence of items, such as a list, tuple, or string, when the number of times you want to iterate is known. The ‘while’ loop is used to repeat a block of code when the number of times you want to iterate is not known or when the number of iterations depends on the results of the loop.

Jump Statement Loops run the same set of code for a defined number of times or until the test condition becomes False, but sometimes we might wish to stop the loop even before the test condition becomes False or skip an iteration. This is where we need Jump statements.

Jump statements allow you to skip code or terminate a loop. We have two jump statements in Python:

• break statement • continue statement The break Statement

The ‘break’ statement is used to terminate the loop. Syntax:

while expression:

if condition:

break

#breaks out of the loop

#executes statement outside the loop

Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 35

35

11/29/2023 10:42:09 AM


Code

Output

word = input(‘Enter a word: ‘)

Enter a word: apple

for letter in word:

Vowel found!

if letter in ‘aeiou’:

print(‘Vowel found!’) break

Here, the loop checks for all the letters in the word entered by a user for vowels. If the letter is a vowel, the ‘break’ statement will run, and the loop will terminate. Otherwise, the loop will continue to run until it reaches the end of the word. The continue Statement

The ‘continue’ statement skips the current iteration of the loop and continues with the next iteration. Syntax:

while expression:

Statement_1 if condition:

continue

#skips next set of statements and starts with next loop iteration

Statement_2 Code

Output

for num in range(1,11):

1

if num == 4 or num== 6 or num==8: #when num = 5, it’s False continue print(num)

2 3 5 7 9

10 Here, the loop starts counting from 1 and increments the value of num by 1 in each iteration. When the value of num is equal to 4, 6, or 8, the ‘continue’ statement is executed, which skips the printing of the number and goes to the next iteration of the loop.

Infinite Loop In a program, if a loop is executed over and over again without stopping, it is called an ‘infinite’ loop.

This can happen if the condition that controls the loop is always true, or if the loop is never terminated by a ‘break’ statement. Code while True: print(“This is an infinite loop!”) Here, the loop will print the message “This is an infinite loop!” repeatedly, until the program is terminated by the user.

Did You Know? Infinite loops can be useful when you want to create a program that runs continuously, such as a server or a chatbot.

An ‘infinite’ loop can lead to the program becoming unresponsive.

36

CO24CB0702_P1.indd 36

11/29/2023 10:42:09 AM


How to Prevent an Infinite Loop? To prevent an ‘infinite’ loop, it is important to carefully consider the condition that controls the loop. Make sure that the condition is only true under the circumstances you want. You should also use ‘break’ statements to terminate loops when you no longer need them to run. Code

Output

counter = 0

Loop iteration: 0

while counter < 5: # This loop will run 5 times.

Loop iteration: 1

print(“Loop iteration:”, counter) counter += 1

Loop iteration: 2 Loop iteration: 3 Loop iteration: 4

Here, the loop will run five times because the counter variable starts at 0 and increments by 1 each time the loop runs. The loop will continue as long as the counter is less than or equal to 5. Once the counter reaches 5, the condition is no longer true, and the loop exits.

Do It Yourself 2C 1 Write a program to generate and display the first 10 numbers of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding numbers. If the sequence starts with 0 and 1, and the first 10 numbers will be: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

2 Write a program to calculate the sum of the digits of a given number. Take the number from the user as input. For example, if the input number is 4453, the sum of the digits will be 4 + 4 + 5 + 3 = 16

Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 37

37

11/29/2023 10:42:10 AM


Coding Challenge FizzBuzz Write a program that prints the numbers from 1 to 100. However, for multiples of 3, the

program should print “Fizz” instead of the number. For multiples of 5, the program should print “Buzz” instead of the number. For numbers that are multiples of both 3 and 5, the program should print “FizzBuzz” instead of the number.

Chapter Checkup A

Fill in the Blanks. instructions

Hints 1 In programming, conditions.

conditional

else

comparison

statements are used to execute different blocks of code based on specific

operators are used to compare two values or expressions and return a Boolean result.

2 3

equal to (==)

The

operator checks if two values are equal.

statement is used to specify a code block that executes when none of the preceding conditions 4 A in the ‘if’ and ‘elif’ statements are True. 5 B

An algorithm is a step-by-step set of

for solving a specific problem or performing a task.

Tick () the Correct Option.

1 What is the output of the given code? x=5

if x > 10: print(“x is greater than 10”) elif x == 10: print(“x is equal to 10”) else: print(“x is less than 10”) a

x is greater than 10

b

c

x is less than 10

d An error occurs

x is equal to 10

2 What is the output of the given code?

i=1

while i <= 5:

print(i) i += 1

a

5 4 3 2 1

b

1 2 3 4

c

1 2 3 4 5

d

None of the above

38

CO24CB0702_P1.indd 38

11/29/2023 10:42:10 AM


3 What is the output of the given code? for i in range(1, 6):

if i == 3:

continue

print(i)

a

1 2 3 4 5

b

1 2 4 5

c

124

d

None of the above

4 What is the output of the given code?

while True:

print(“Infinite Loop”)

break

a

Infinite Loop

b

No output

c

An error occurs

d

Loop runs infinitely

C

Who Am I? 1 I can help a program make decisions based on specified conditions. 2 I am a precise plan with a clear set of steps to solve a problem.

D

3

I am a visual way to depict the flow of a program.

4

I can combine two conditions together to test.

5

I repeat a block of code as long as a certain condition is true.

Write T for True and F for False. 1

A flowchart is a text-based representation of the logical flow of a program.

2

The ‘for’ loop is used to iterate over a sequence of elements.

3

The logical operator ‘and’ returns True if at least one of the conditions it combines is True.

4 The ‘continue’ statement in Python skips the current iteration of a loop and continues with the next iteration. E

Answer the Following. 1 What is the purpose of the ‘elif’ statement in Python’s conditional statements? Give an example.

2 Define the ‘and’ and ‘or’ logical operators and give an example of how they can be used in a conditional statement.

Chapter 2 • Control Statements in Python

CO24CB0702_P1.indd 39

39

11/29/2023 10:42:10 AM


F

3

How does a ‘for’ loop differ from a ‘while’ loop in Python? Provide an example of when you might use a ‘for’ loop.

4

Write the syntax of the while loop.

Apply Your Learning. 1 Write a program to display a multiplication table for a number the user inputs. Ask the user for the number of terms to display and print the result.

2

Write a program to print the largest number among three inputs.

3 Create a program that calculates the factorial of a positive integer entered by the user using a loop. A factorial of a number ‘n’ is the product of all positive integers from 1 to ‘n’.

4 Write a program to implement a word guessing game where players guess one letter at a time until they solve the word or run out of attempts.

5 Ben, the school’s football team captain, wants to find players who are tall and strong for the defenders, and short and nippy for the attackers. He needs defenders to be over 6 foot tall and weighing over 68 kilos. For attackers, he wants players under 5 foot tall and weighing less than 57 kilos. Write a program to help Ben find the right players.

40

CO24CB0702_P1.indd 40

11/29/2023 10:42:10 AM


3

Functions in Python

In our everyday lives, we use a lot of machines for different purposes, like washing machines, ovens, fans, tubelights, air conditioners, stoves, chimneys, and many more. All of these machines serve specific purposes. Let us take the example of a vending machine. A vending machine is an automated machine that you can use to buy things, like snacks, juices, and soft drinks. To buy something from a vending machine, you need to:

• Use the buttons or digital panel to select the item you want and pay for it. • Once the payment is processed, collect the item from the dispenser.

A vending machine does all of these things every time it is used. This is an example of a function. Every day, we do certain tasks over and over again. If we can automate these tasks, meaning we only create them once and then reuse them as needed, it makes things easier. In programming, we often need to repeat a specific set of code for a task. Instead of rewriting this code each time, wouldn’t it be better to write it once and then use it as many times as we want without having to copy and paste it? We can solve this problem with functions. We can create them once and then call them whenever we need them. Benefits of Functions 1 Organisation: Functions can help us organise a code by grouping related codes together to make the code easier to read and understand. 2 Reusability: We can reuse functions in different parts of a program to save time and effort, and it also helps to keep the code consistent.

Functions A function is a block of code that does a specific job. It can take in information, process it, and give out information. Functions can be used to make a code more reusable and efficient. We’ve already used some built-in functions in Python, like print(), input(), eval(), int(), and bool(). But Python also lets us create our own functions, called user-defined functions. A function is defined using the def keyword. The def keyword is followed by the name of the function, the inputs it takes (if any), and the body of the function. The body of the function is the code that will be run whenever the function is called for. Syntax: def function_name(parameters):

# Function body (code that performs the job)

41

CO24CB0703_P1.indd 41

11/28/2023 7:18:06 PM


# ...

return result # Optionally, you can return a value

def: Keyword used to define a function function_name: The name you give to your function parameters: The values the function takes (optional)

Discuss

Why is it important to give functions appropriate names?

return: The value the function returns (optional) To call a function, you simply use its name followed by parentheses. function_name(arguments) You can pass on the arguments and values in the function by enclosing it in the parentheses.

Arguments and Parameters Parameters are the variables that we pass while defining a user-defined function. Arguments are the variables that we pass while calling a function. Code

Output

Parameters

7

def sum (x,y): print (x+y) sum (3,4) Arguments Here, the parameters are x and y, and the arguments are 3 and 4 for the respective parameters, i.e., x = 3 and y = 4.

Types of Arguments Python functions can have two types of arguments: 1

Positional arguments

2

Keyword arguments

Positional Arguments When we pass arguments to a function in the order they are specified in the function definition, they are called positional arguments. Code

Output Parameters

Daisy Brown

def name (first_name, last_name): print (first_name + last_name) name (”Daisy”, “Brown”) Arguments

42

CO24CB0703_P1.indd 42

11/28/2023 7:18:06 PM


Here, Daisy and Brown will be taken by the parameters according to their position. first_name = Daisy last_name = Brown Keyword Arguments Keyword arguments are the arguments that are preceded by a keyword and an equal to sign (i.e., Key = Value). Here, the order of the arguments does not matter as the values are being assigned explicitly. Code

Output

def name (first_name , last_name ):

Daisy Brown

print (first_name + last_name) name (last_name = “Brown”, first_name = “Daisy “) Here, the arguments are passed with their respective keywords, such as last_name = “Brown” and first_name = “Daisy“. Now, we will be creating a project while learning about functions. Project: Temperature Converter Create a program to make a Temperature Converter that can change temperatures from Celsius to Fahrenheit and from Fahrenheit to Celsius. Task 1: Create a function to convert temperature from celsius to fahrenheit. Code

Output

def celsius_to_fahrenheit(celsius):

95.0

# Formula to convert Celsius to Fahrenheit fahrenheit = (celsius * 9/5) + 32 print(fahrenheit)

Discuss

What are the advantages of using keyword arguments over positional arguments?

celsius_to_fahrenheit(35) Here, celsius_to_fahrenheit is a function that takes one input (celsius) and displays the converted value in fahrenheit. When you call celsius_to_fahrenheit(35), it displays 95.0.

Return Value A function can return a value in Python using the return keyword. The return keyword is followed by the value that you want to return from the function. Let us update our project code with return value. Project: Temperature Converter Task 2: Update the celsius_to_fahrenheit() function to convert temperature from Celsius to Fahrenheit with a return value.

Chapter 3 • Functions in Python

CO24CB0703_P1.indd 43

43

11/28/2023 7:18:06 PM


Code

Output

def celsius_to_fahrenheit(celsius):

95.0

# Formula to convert Celsius to Fahrenheit fahrenheit = (celsius * 9/5) + 32 return fahrenheit result=celsius_to_fahrenheit(35) print(result) Here, the celsius_to_fahrenheit() function doesn’t print the calculated value but returns it. When we call the celsius_to_fahrenheit() function with the argument 35, it returns the value 95.0, which is then received in the result variable. The result variable is printed. We can also return multiple values from a function by returning them as a tuple. Code

Output

def sum_and_difference(a, b):

(15, 5)

sum = a + b difference = a - b return (sum, difference) result = sum_and_difference(10, 5) print(result) Now, let us complete our project “Temperature Converter”. Project: Temperature Converter Task 1: Function to convert temperature from Celsius to Fahrenheit with a return value. def celsius_to_fahrenheit(celsius): # Formula to convert Celsius to Fahrenheit fahrenheit = (celsius * 9/5) + 32 return fahrenheit Task 2: Create a function to convert temperature from Fahrenheit to Celsius and return the result. def fahrenheit_to_celsius(fahrenheit): # Formula to convert Fahrenheit to Celsius celsius = (fahrenheit - 32) * 5/9 return celsius Task 3: Create the menu for the operations using a while loop. while True: print(“1. Celsius to Fahrenheit”)

44

CO24CB0703_P1.indd 44

11/28/2023 7:18:06 PM


print(“2. Fahrenheit to Celsius”) print(“3. Quit”) choice = input(“Enter your choice (1/2/3): “) Task 4: If the user picks the first choice, call the function celsius_to_fahrenheit() and display the returned value. if choice == ‘1’: celsius = float(input(“Enter temperature in Celsius: “)) result = celsius_to_fahrenheit(celsius) print(celsius,”is equal to”, result, “°F\n”) Task 5: If the user picks the second choice, call the function fahrenheit_to_celsius() and display the returned value. elif choice == ‘2’: fahrenheit = float(input(“Enter temperature in Fahrenheit: “)) result = fahrenheit_to_celsius(fahrenheit) print(fahrenheit,”is equal to”, result, “,°C\n”) Task 6: Quit the program once the user chooses ‘3’ and display “Goodbye!” If none of the given choice options are entered, display “Invalid choice. Please enter 1, 2, or 3.”. elif choice == ‘3’: print(“Goodbye!”) break else: print(“Invalid choice. Please enter 1, 2, or 3.\n”)

Recursive Functions A recursive function is a function that calls itself directly or indirectly. Recursive functions can be used to solve problems that can be broken down into smaller and smaller sub-problems of the same type. One example of a recursive function is the function to calculate the factorial of a number. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 120 because 120 is the product of 1, 2, 3, 4, and 5. Let’s look at a program to find the factorial of a number without using a recursive function: Code

Output

n=int(input(“Enter the number to find out factorial for: “))

Enter the number to find out factorial for:

result = 1

5

for i in range(1, n+1):

120

result *= i print(result)

Chapter 3 • Functions in Python

CO24CB0703_P1.indd 45

45

11/28/2023 7:18:07 PM


Now, let’s create the same program using a recursive function: Code

Output

n=int(input(“Enter the number to find out factorial for: “))

Enter the number to find out factorial for:

def factorial(n):

5

if n == 0:

120

return 1 else: return n * factorial(n - 1) print(factorial(n)) This function works by recursively calling itself to calculate the factorial of the smaller and smaller numbers until it reaches the base case, which is when n == 0. In the base case, the function returns 1, because the factorial of 0 is 1. Recursive functions can be used to solve a variety of problems, such as finding the maximum value in a list, traversing a tree, and solving the Towers of Hanoi puzzle. Here are some tips for writing recursive functions: 1

The function should have a base case, which is a condition that terminates the recursion.

2

The function makes progress towards the base case with each recursive call.

3

Avoid using recursive functions to solve problems that can be solved with a loop.

Coding Challenge Palindrome Number Checker

Write a program to check whether the number the user inputs is a palindrome number or not using functions.

A palindrome number is a number that reads the same, backwards and forwards. For example, the numbers 121, 12321, and 5454 are palindromes. To check if a number is a palindrome, you can reverse the number and then compare it to the original number. If the two numbers are the same, then the number is a palindrome.

Chapter Checkup A

Fill in the Blanks. Hints

user-defined

return

argument

positional

built-in

1

An

is the value that is passed to a function when it is called.

2

A

argument is an argument that is passed to a function in a specific order.

46

CO24CB0703_P1.indd 46

11/28/2023 7:18:07 PM


3

B

A

value is the value that is returned by a function when it finishes executing.

4

functions are built into Python and can be accessed by the programmer.

5

functions are declared by the programmer and can be used in their own programs.

Tick () the Correct Option. 1 Observe the given code.

def add_numbers(a, b): return a + b

print(add_numbers(1, 2)) Output: 3

Which of the following statements is TRUE?

a The add_numbers() function is a built-in function. b The add_numbers() function is a user-defined function. c

The add_numbers() function has one argument.

d The add_numbers() function has two arguments. 2 Observe the given code.

def greet_person(name, age=None): if name is not None:

print(“Hello”, name)

if age is not None:

print(“You are”, age, “years old.”)

greet_person(name=”Bard”)

Output: Hello, Bard

Which of the following statements is TRUE?

a

The greet_person() function is a built-in function.

b

The greet_person() function is a user-defined function.

c

The greet_person() function has one positional argument.

d

The greet_person() function has one keyword argument.

3 What will be the output of the following code?

def add_numbers(x, y): result = x + y

return result sum_result = add_numbers(3, 5)

print(sum_result) a

8

b

add_numbers(3, 5)

c

result

d

None

Chapter 3 • Functions in Python

CO24CB0703_P1.indd 47

47

11/28/2023 7:18:07 PM


4

What will be the output of the following code?

def my_function(x, y=10):

result1 = my_function(5)

return x + y

result2 = my_function(5, 20)

print(result1, result2) a

5 20

b

15 25

c

10 25

d

Error

C

Who Am I? 1

When you give arguments to a function by naming them explicitly, you are using me.

2

I am the result that a function gives back after it finishes doing its work.

3

I am a type of function that comes with Python. Examples of me include print(), len(), and input().

4

I am a special type of function that can call itself from within its own code.

5

I help prevent infinite recursion in a recursive function by specifying when the function should stop calling itself.

D

E

Write T for True and F for False. 1

An argument is the value that is passed to a function when it is called.

2

A recursive function is a function that calls itself.

3

A keyword argument is an argument that is passed to a function in a specific order.

4

The input() is a user-defined function.

Answer the Following. 1

What is an argument and how is it different from a parameter?

2

How does a user-defined function differ from a built-in function?

48

CO24CB0703_P1.indd 48

11/28/2023 7:18:07 PM


3

What is the difference between a function with a return value and a function without a return value?

4

Observe the given code:

def power(x, n):

return 1

if n == 0:

else:

return x * power(x, n)

result = power(2, 3)

print(result) a

What is the issue with the above code?

b

How can you fix it to correctly calculate the power of a number?

5

Observe the given code:

def countdown(n):

if n == 0:

else:

return

print(n)

countdown(n)

countdown(5) a

What’s the issue with this code?

b

How can you fix it to make it countdown from 5 to 1?

F

Apply Your Learning. 1 Write a program to calculate the square of any number using a function that accepts parameters and returns the result.

2

Write a program to accept two numbers as input from the user and calculate their LCM.

Chapter 3 • Functions in Python

CO24CB0703_P1.indd 49

49

11/28/2023 7:18:07 PM


3

Write a program that takes a number and returns a list of the prime factors of the number.

4

Write a program to find the product of two numbers using a function with parameters.

5

Write a program to find if a number is prime or not by using a function that returns the result.

50

CO24CB0703_P1.indd 50

11/28/2023 7:18:07 PM


4

Introduction to Web Development

Web development is the process of designing, building, and maintaining web applications that work on the internet. Imagine you need to make a cardboard house for your school competition project. Before you begin making the project, you need to plan for it. You need to decide how many rooms your cardboard house will have and how they will be arranged. You also need to find out what materials you will need to build it. Once you have your plan ready, you can start building the house by putting together the various parts like walls, roof, and windows. Web development is similar to building a cardboard house; but instead of using cardboard and tapes, you would be using code. When you build a website, you use code to tell the computer how to display the various parts of the website, such as the text, images, and videos.

Did You Know? The first website, CERN, was created in 1989 and is still alive today.

Web development involves multiple tasks, such as:

• Designing the layout and appearance of the website • Writing the code that makes the website work • Adding content to the website, such as text, images, and videos

There are three main types of programming languages used in web development: HTML (HyperText Markup Language): HTML is the markup language used for creating websites. It is also used to structure the content of a website. For example, HTML tags can be used to tell the computer whether a piece of text is a heading, a paragraph, or a list. CSS (Cascading Style Sheets): CSS is used to style the content of a website. For example, CSS can be used to change the font size, colour, and alignment of text. JavaScript: JavaScript is a programming language that can be used to add interactivity to a website. For example, JavaScript can be used to create menus, animations, and games.

HTML HTML stands for ‘HyperText Markup Language’. It is used to develop web applications. It tells a web browser how to display content on a website. In HTML, ‘Hypertext’ means the text that is more than static text. It can be interactive and linked to other pages or resources.

51

CO24CB0704_P1.indd 51

11/28/2023 7:20:34 PM


Markup are the tags we use in HTML to structure and format the text on a web page. These tags are the instructions that tell the browser how and where to display the content on a page.

Did You Know? HTML is not a programming language because it does not include any logic or algorithms.

Features of HTML 1

Easy to learn: HTML is an easy language to learn, even for beginners. It is made up of tags that tell the browser what to do.

2

Platform independent: HTML is platform independent, which means that it can be used to create web pages that can be viewed on any device, regardless of the operating system or web browser.

3

Media support: HTML can be used to display images, videos, and audio on web pages.

4

Hypertext: HTML supports hypertext, which means that text on a web page can be linked to other web pages or resources.

5

Semantic structure: HTML5 introduced many new semantic elements, which can be used to improve the accessibility of web pages.

6

Case insensitive: HTML is a case-insensitive language.

Basic Structure of an HTML Document An HTML document is structured into two main parts: the head and the body. The head contains information about the document, such as the title. The body contains the content of the web page, such as text, images, and videos. The body is displayed in the browser window. HTML Document Basic Structure The basic structure of an HTML document looks like this: <html> 1

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

<head>

2

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

</head>

3

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

<body>

4

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

</body>

<title> Document Title</title>

<!-- Content goes here --> </html>

Web Browser A web browser is a software application that allows you to access and view web pages. There are many web browsers available, such as Google Chrome, Mozilla Firefox, Microsoft Edge, and Apple Safari. All web browsers work in a similar way, but they may have different features and user interfaces.

Google Chrome

Mozilla Firefox

Apple Safari

opera

Microsoft Edge

52

CO24CB0704_P1.indd 52

11/28/2023 7:20:34 PM


They allow us to browse websites, watch videos, listen to music, and play games. Some of the basic components of a web browser are as follows:

• Address bar: The address bar is where you type the URL of the website you want to visit. • Navigation buttons: The navigation buttons allow you to move forward, back, and refresh the current web page.

• Tabs: Tabs allow you to have multiple web pages open at the same time. • Bookmarks: Bookmarks allow you to save the URLs of your favourite websites so that you can easily access them later.

• History: The history feature allows you to view a list of the websites you have recently visited. Basic HTML Terminologies Tags A tag tells the browser how to display the content that follows it. Tags are enclosed in angle brackets (< and >). For example, <h1> is the opening tag for heading and </h1> is the closing tag for heading. To create an HTML document, we have the following tags: Tag

Purpose

Syntax

<!---->

Used to insert comments in the HTML code. <!--comment–->

<p>

It is used as the paragraph tag that is used <p>content</p> to add a paragraph.

Heading tags

HTML heading tags are used to add <h1>Most important heading</h1> headings and sub-headings to the content <h2>content</h2> you want to display on a web page. HTML has six levels of heading from <h1> to <h6>. <h3>content</h3> <h4>content</h4> <h5>content</h5> <h6>Least important heading</h6>

<div>

This tag is used in HTML to make divisions of content in the web page such as text, images, and header.

<div>content</div>

<br>

Inserts a single line break

Should be added where the line break is needed.

<b>

Converts the text into bold

<b>text</b>

<i>

Converts the text into italics

<i>text</i>

<img>

Displays an image

<img src=”https://example.com/image.png” alt=”This is an image of a cat.” />

<a>

Creates a link. Links can be used to link <a href=”https://example.com”>This is a link to to other web pages, images, or other the example website.</a> resources.

Chapter 4 • Introduction to Web Development

CO24CB0704_P1.indd 53

53

11/28/2023 7:20:34 PM


Elements An element is a combination of a tag and its content.

Opening Tag

For example, the <h1> element is a heading element. There are mainly two types of HTML elements: 1

Container elements: Container elements are HTML elements that can contain other elements or text within them. They have both an opening tag and a closing tag to enclose their content.

Content

Closing Tag

<h1> This is my first HTML document. </h1>

Element

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

Empty elements: Empty elements, also known as void elements or self-closing elements, do not contain any content between opening and closing tags. They are self-contained and do not require a closing tag. Examples: <br>, <hr>, <img>.

Attribute It is used to define the characteristic of an HTML element. An attribute is always placed in the opening tag of an element and generally provides additional styling (an attribute) to the element.

<h1> <font color= ''red''> This is my first HTML document. </font> </h1>

Attribute

Project: Space Exploration Let us build a simple Space Exploration web page project while learning the concepts in the chapter. We will be building this project by dividing it into tasks. Task 1: Create a web page and name it Space Exploration. Add the heading ‘Space Exploration’ and then add an introduction for it. Code <html>

<head> </head> <body>

<title>Space Exploration</title>

<h1>Space Exploration</h1> <div> <p><b>Space exploration</b> is the study of space and everything beyond Earth’s atmosphere. We use robots and spacecrafts to explore space and learn new things about it. <br><br> Space exploration has led to many <i><b>amazing discoveries</b></i>, such as exoplanets (planets that orbit other stars), water on Mars, and black holes. <br><br> Space exploration is also important for inspiring people and showing us what is possible. </p> </div> </body> </html>

54

CO24CB0704_P1.indd 54

11/28/2023 7:20:34 PM


Output

Space Exploration Space exploration is the study of space and everything beyond Earth's atmosphere. We use robots and spacecrafts to explore space and learn new things about it. Space exploration has led to many amazing discoveries, such as exoplanets (planets that orbit other stars), water on Mars, and black holes. Space exploration is also important for inspiring people and showing us what is possible.

Do It Yourself 4A Match the following terms with their descriptions.

1

Column A

Column B

<h1>

Is a language for structuring web content.

<!-- -->

Converts the text into bold.

<div>

Is used for inserting comments in HTML code.

HTML

Is used to create a division within a web page.

<b>

Defines the main heading of a web page.

Identify the error in the following element examples:

2

a

<titl>My Web Page</title>

b

<h1>Welcome to My Page<h1>

c

<p>This is a paragraph</h>

d

<a href=”https://www.example.com” Example Website</a>

CSS CSS stands for Cascading Style Sheets. It is a language used to style HTML elements. CSS can be used to change the appearance of HTML elements, such as their font, colour, and size.

Features of CSS Some key features of CSS include: 1

Selectivity: CSS can be used to select specific HTML elements to style such as changing colours, styling fonts, spacing elements, and resizing them.

2

Consistency: You can use the same styles for many pages on a website to make them look similar.

Chapter 4 • Introduction to Web Development

CO24CB0704_P1.indd 55

55

11/28/2023 7:20:35 PM


3

Cascading: CSS styles are applied in cascading order. This means that the most specific style will be applied to an element, even if there are other styles that are more general.

4

Responsive design: CSS can be used to create responsive web pages that work on all devices, from desktop computers to smartphones.

5

Animations and transitions: CSS can be used to add animations and transitions to web pages, which can make them more visually appealing and engaging.

Adding Style to an HTML Document There are three ways to add style to an HTML document: 1

Inline CSS: Inline CSS is used to style a single HTML element. To add inline CSS, you use the style attribute. For example, the following code will make the <h1> element red and 20 pixels in size: <h1 style=”color: red; font-size: 20px;”>This is a heading</h1>

2

Internal CSS: Internal CSS is used to style all the elements on a single HTML page. To add internal CSS, you use the <style> tag. The <style> tag should be placed in the <head> section of your HTML document. For example, the following code will make all <h1> elements on the page red and 20 pixels in size: Code <html> <head>

<style>

h1 { }

color: red; font-size: 20px;

</style> </head> <body> <h1>This is a heading</h1> <h1>This is another heading</h1> </body> </html> 3

External CSS: External CSS is used to style all the elements on all of the pages of a website. To add external CSS, you use the <link> tag. The <link> tag should be placed in the <head> section of your HTML document. For example, the following code will link to an external CSS file called style.css: Code <html> <head> <link rel=”stylesheet” href=”style.css”> </head> <body> <h1>This is a heading</h1> </body> </html>

56

CO24CB0704_P1.indd 56

11/28/2023 7:20:35 PM


The style.css file would contain the following CSS:

Think and Tell

Code

What CSS will you use to style a web page?

h1 { color: red; font-size: 20px; } If you only need to style a single element, then use inline CSS.

If you need to style all the elements on a single page, then use internal CSS. If you need to style all the elements on all the pages in a website, then use external CSS.

CSS Classes CSS classes are a way to group similar HTML elements together so that you can style them all at once. This can save you a lot of time and effort, especially if you have a lot of similar elements on your page. To create a CSS class, you add the class attribute to an HTML element and assign it a unique name. For example, the following code would create a CSS class called my-class: <p class=”my-class”>This is a paragraph</p> Once you have created a CSS class, you can style it using the . (dot) character and the class name. For example, the following CSS code will make all paragraphs with the my-class class red and 20 pixels in size: .my-class {

color: red;

font-size: 20px;

}

Selectors and Properties Selectors are used to select the HTML elements that you want to style, and properties are used to define the styles that you want to apply to those elements. Some of the most common selectors in HTML include: 1

Element selectors: Select elements by their tag name, such as h1, p, or img.

2

Class selectors: Select elements by their CSS class.

3

ID selectors: Select elements by their ID.

4

Combination selectors: Combine multiple selectors to target specific elements.

There are many CSS properties, including: CSS Property

Purpose

Syntax

color

Sets the colour of the text.

color:blue

font-family

Sets the font family of the text.

Font-family:cambria

Chapter 4 • Introduction to Web Development

CO24CB0704_P1.indd 57

57

11/28/2023 7:20:35 PM


CSS Property

Purpose

Syntax

font-size

Sets the size of the text.

Font-size:x-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

text-decoration

Formats the text.

Text-decoration: underline Note: line-through, overline can be used.

Text-align

Aligns the text.

Text-align: left Note: right, center, justify can be used.

Background-color

Sets the background colour of the element.

background-image

Sets background images for an element, Background-image:url(”https://example. you can set one or more images. com/image.png”)

border

To set the border around the element.

Border: solid

border-color

Sets the colour of the border of an element.

border-color:blue

border-radius

Round the corners of the outer border edges of an element.

border-radius:30px

padding

To set the space around the content of the element.

padding:40px

To set the space around the element itself.

margin:20px

margin

Background-color:red

Note: Any number can be added according to the use. Note: Any number can be added according to the use.

You can also use a shortcut called the background property to set multiple background-related properties in one declaration. For example, you can use the background property to set the background colour, image, size, and position of a div element all at once.

Think and Tell How are Selectors and Properties different?

Here is an example: div { }

background: blue url(‘image.jpg’) no-repeat center/cover;

In this example:

Discuss

What are the benefits of having classes in an HTML document?

• blue sets the background colour to blue. • url(‘image.jpg’) sets the background image to the image named image.jpg. • no-repeat prevents the image from repeating. • center/cover positions and sizes the image so that it covers the entire div element. 58

CO24CB0704_P1.indd 58

11/28/2023 7:20:35 PM


You can apply the background property to any HTML element, not just to div elements. For example, you can apply it to the <body> element to set the background of your entire web page. Project: Space Exploration Task 2: Use internal CSS to make the project colourful and attractive. 1

Inside the head element, create a style element and: a

Add a style for body element.

b

Create a content class for styling internal content.

Code <html> <head> <title>Space Exploration</title> <style> body { background-color: powderblue; color: black; text-align: center; }

</head> 2

.content{ color: darkred; text-align: left; } </style>

Update the body element by applying the content style in content div. Code <body>

<h1>Space Exploration</h1>

<div class=content> <p><b>Space exploration</b> is the study of space and everything beyond Earth’s atmosphere. We use robots and spacecrafts to explore space and learn new things about it. <br><br> Space exploration has led to many <i><b>amazing discoveries</b></i>, such as exoplanets (planets that orbit other stars), water on Mars, and black holes. <br><br> Space exploration is also important for inspiring people and showing us what is possible. </p> </div> </body> </html>

Chapter 4 • Introduction to Web Development

CO24CB0704_P1.indd 59

59

11/28/2023 7:20:35 PM


Output

Do It Yourself 4B 1

Fill in the blanks. Hints

background-color

background

internal

a

If you want to style all elements on a single HTML page, you can use

b

CSS classes are used to group

similar

<link> CSS.

HTML elements together.

c The shorthand for setting multiple background-related properties in one declaration is the property.

2

d

To set the background colour of an element, you can use the

property.

e

External stylesheets are linked to HTML documents using the

element.

Write T for true and F for false. a

Internal CSS is added to the <body> section of an HTML document.

b

You can create a CSS class by adding the class attribute to an HTML element.

c

The no-repeat property of CSS prevents the image from repeating.

d

External stylesheets are included directly within an HTML document, using the <style> element.

e

CSS can be used to change the colour and size of HTML elements.

Coding Challenge 1.

Create a web page with the following content: a. A title: My Dream Vacation

b. A paragraph describing my dream vacation c. Set the font and background colour.

60

CO24CB0704_P1.indd 60

11/28/2023 7:20:35 PM


2.

Create a web page with the following content: a. A title: My Favourite Game

b. A CSS class called ‘my-favourite-game’ that sets the background colour of the page to cyan. c. A paragraph describing my favourite game and why I like it.

Chapter Checkup A

Fill in the Blanks. Hints

B

head

web applications

angle

body

1

Web development involves designing, building, and maintaining

2

The basic structure of an HTML document consists of the

3

HTML tags are enclosed in

4

You can apply CSS using three main methods: inline styles, internal stylesheets, and

external

. and the

.

brackets. stylesheets.

Tick () the Correct Option. 1 Which type of CSS would you suggest to style a single HTML element?

a Internal CSS

b External CSS

c

d Outline CSS

Inline CSS

2 Which HTML tag is used to create a single line break? a <newline>

b <line-break>

c

d <br>

<b>

3 Which of the following is an example of a CSS class? a .my-class

b my-class

c

d my.class

<class=”my-class”>

4 Which of the following HTML elements is used to create a link? a <p> c

<h1>

b <img> d <a>

5 Which of the following CSS properties is used to set the colour of the border of an element? a border-color

b color

c

d border

bordercolor

Chapter 4 • Introduction to Web Development

CO24CB0704_P1.indd 61

61

11/28/2023 7:20:36 PM


C

Who Am I? 1

I define the characteristics of an HTML element and am placed in the opening tag.

2

I make divisions of content on a web page, like sections of text, images, headers, and more.

3

I am a CSS property to set the space around the element itself.

4

I convert text into an italic format in HTML.

5 I display images on a web page. You can specify the image source and alternative text using attributes with me.

D

E

Write T for True or F for False. 1

A web browser is a software application that allows you to access and view web pages.

2

CSS-created web pages don’t work on all devices.

3

You can use the . (dot) character and the class name to style a CSS class.

4

Element selectors select elements by their tag name, such as h1, p, or img.

5

Class Selectors select elements using their ID.

Answer the Following. 1

What is web development, and what are its two main categories?

2

What is the basic structure of an HTML document?

3

What does the HTML tag <img> do, and how can you specify the source of an image?

4

What is CSS, and what are some of its features?

5

What are selectors and properties in CSS, and provide examples of each?

62

CO24CB0704_P1.indd 62

11/28/2023 7:20:36 PM


F

Apply Your Learning. 1

In CSS, how would you make all paragraphs with the class “my-class” blue in colour and 30 pixels in size?

2

When you use the HTML tag <div>, what purpose does it serve?

3

You have a paragraph of text that you want to make bold. How would you do this using HTML tags?

4 Create a CSS class named “highlight” that changes the text colour to yellow and applies the ‘back.png’ images as background of the web page.

Chapter 4 • Introduction to Web Development

CO24CB0704_P1.indd 63

63

11/28/2023 7:20:36 PM


51

Images and Hyperlinks in HTML

Just like pictures make a book more interesting, images make websites more exciting and interesting. Images are used for many purposes, such as providing visual support to written content, conveying feelings, telling stories, providing clarity of purpose, and making the content easy to remember.

Let us learn to add and style images.

Adding Images In an HTML document, you can add images using the following methods: 1

Using the <img> element: The most common way to add images is by using the <img> element. You need to specify the source (URL) of the image, using the src attribute. Here is an example: <img src=”image.jpg” alt=”A beautiful landscape”> In this example, ‘image.jpg’ is the source file for the image, and “A beautiful landscape” is the alternative text (alt text) that appears if the image cannot be displayed.

2

Using background images: You can set background images for HTML elements (like <div> or the entire <body>), using CSS.

Note the following points while adding images in a web page: 1

You can acquire the image to be inserted into the web page from any resource. It can be a file downloaded and saved on your computer, or you can provide a direct link to an online resource.

64

CO24CB0705_P1.indd 64

11/28/2023 7:24:52 PM


2

If the image is on your computer, both the image and your web page should be saved in the same folder or location. In this case, you can reference the image file like this: <img src=”image.jpg”>

3

If the image and the HTML file are in different folders, then you should give the full path or relative path to the image in the code. The corrected example should look like this: <img src=”C:\images\image.jpg”> or using a relative path like: <img src=”../images/image.jpg”>.

4

You can provide the URL of the image directly if it’s hosted on the internet: <img src=”https://www.example.com/image.jpg”>.

5

In case you are using the Tekie platform for developing your project, then you will get the required resources for the respective projects on the platform. Here is an example of setting a background image for a <div> element: <style> .my-div { background-image: url(‘background.jpg’); background-size: cover; /* Adjust the size as needed */ } </style> <div class=”my-div”> <!-- Content of the div goes here --> </div>

In this example, ‘background.jpg’ is the source file for the background image and ‘background-size: cover;’ ensures that the image covers the entire div. In the last chapter, we created a project called Space Exploration. In this chapter, we will add an astronaut image to the project. Project: Space Exploration Task 3: Adding an astronaut image Code <body> <h1>Space Exploration</h1> <img src=”rocket.jpg” alt=”rocket” width=”100” height=”100”> <div class=content>

Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 65

65

11/28/2023 7:24:55 PM


Output

Task 4: Adding a background image and changing the text colour Code <html> <head> <title>Space Exploration</title> <style> body { background-image: url(“space_background.jpg”); color: white; text-align: center; } .content{ text-align: left; } </style> </head> Output

66

CO24CB0705_P1.indd 66

11/28/2023 7:24:56 PM


Styling Images We can style an image in two ways: 1

Using a style attribute: To use a style attribute, specify the CSS properties you want to apply to the image, separated by semicolons. For example, the following code makes the image 100% wide and auto height: <img src=”https://example.com/image.jpg” style=”width: 100%; height: auto;”>

2

Using a class: To use CSS to style an image, you can either create a CSS class or ID and apply it to the image using the class or id attribute, or you can use an inline CSS block. Here is an example of how to use a CSS class to style an image: <img src=”https://example.com/image.jpg” class=”image-style”> .image-style { width: 100%; height: auto; margin: 10px; }

You can use CSS to style images in many ways. Here are some of the most common CSS properties used to style images:

• width: Specifies the width of the image. • height: Specifies the height of the image. • margin: Specifies the amount of space around the image. • padding: Specifies the amount of space between the border of the image and its contents. • border: Specifies the border around the image. • border-radius: Specifies the radius of the corners of the image border. • box-shadow: Specifies a shadow around the image. • opacity: Specifies the transparency of the image. • filter: Specifies a filter to apply to the image. Project: Space Exploration Task 5: Adding an image and styling it using a class Code <html> <head> <title>Space Exploration</title> <style> body { background-image: url(“space_background.jpg”); color: white; text-align: center; } Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 67

67

11/28/2023 7:24:56 PM


Code .img-style{ border: 5px solid orangered; border-radius: 15px; width: 120px; height: 80px; margin: 10px; } .content{ text-align: left; margin: 10px; } </style> </head> <body> <img src=”planet.jpg” align=left class=”img-style”> <h1>Space Exploration</h1> <!-- The remaining code will be same--> Output

Do It Yourself 5A 1

Match the columns. Column A

Column B

Is an attribute for specifying the source of an image

Used to provide alternative text for images

Is an HTML element for adding images

Using a class

Is a purpose of the alt attribute

margin

Is a way to apply CSS styles directly to an HTML element

src

Specifies the amount of space around the image

<img>

68

CO24CB0705_P1.indd 68

11/28/2023 7:24:56 PM


2

Fill in the blanks. class

Hints

height

border-radius

<img>

background-image

a

In an HTML document, you can add images using the

b

The

attribute of an <img> tag is used to style an image using a class.

c

The

property specifies the height of the image.

d

To set background images for HTML elements, you use the

e

The

element.

property.

property can make the corners of an image round.

Flexbox Imagine that a container element is like a box and the flex items are like the objects inside the box. A flexbox is a CSS layout module that allows you to easily create flexible and responsive layouts by arranging the objects inside the box in a flexible and responsive way. You can line up the objects in a row or a column, and you can control how much space each object takes up. You can also control how the objects are aligned inside the box, such as horizontally centred or vertically centred. A flexbox works by dividing a container element into flex items. These items can be any type of an HTML element, such as divs, spans, and images. Flex items can be resized and rearranged to fit the available space in the container. Here is a simple example of how to use a flexbox: <div class=”container”> <div class=”item”>Item 1</div> <div class=”item”>Item 2</div> <div class=”item”>Item 3</div> </div> .container { display: flex; } .item { flex: 1; } This code creates a container element with three flex items. The flex items are arranged horizontally and take up equal amounts of space. You can also use a flexbox to control the alignment of flex items.

For example, the following code vertically aligns the flex items in the centre of the container: .container {

display: flex;

}

align-items: center;

You can also use a flexbox to control the direction of flex items.

Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 69

Discuss

Share some of the applications or websites where you notice the use of flexboxes.

69

11/28/2023 7:24:57 PM


For example, the following code arranges the flex items vertically instead of horizontally: .container {

display: flex;

}

flex-direction: column;

Properties of a Parent (Flex Container) Property

Purpose

display: flex

Makes the parent container flexible.

flex-direction: row | column

Allows flex items of the container to be displayed row-wise or column-wise.

flex-wrap: wrap | nowrap

Allows flex items to wrap onto more than one line.

justify-content: centre | flex-start | flex-end Allows items to align along the main axis.

align-items: centre | flex-start | flex-end

Allows multiple lines of items to align along the cross axis.

70

CO24CB0705_P1.indd 70

11/28/2023 7:24:57 PM


Property align-content: centre | flex-start | flex-end

Purpose Allows items to align along the cross axis in a single line.

Properties of a Child (Flex Item) Property

Purpose

order

allows the change in order of items without altering the source order.

flex-grow

allows an item to fill up the available free space.

flex-shrink

allows an item to shrink if there is not enough free space available.

flex-basis

defines the size of an item before space is distributed.

flex

shorthand for flex-grow + flex-shrink + flex-basis.

flex-self

can align a single item within the flex container.

Project: Space Exploration Task 6: Use a flexbox to place items within a web page. 1

Replace the body element with the header class and update as shown to add a flex container for the header part of your web page.

2

Update the content class by adding a flex container. Code

<html> <head> <title>Space Exploration</title> <style> .header{ display: flex; background-image: url”(space_background.jpg”); justify-content: center; color: white; border-radius: 5px; width: 100%; } .img-style{ border: 5px solid orangered; border-radius: 15px; width: 120px; height: 80px; margin: 10px; } Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 71

71

11/28/2023 7:24:58 PM


Code .content{ display:flex; text-align: left; margin: 10px; } 3

Add the new classes for cards. a

.card-holder – a flex container for flex items

b

.cards – flex items

c

.cards-img – for images in flex items

d

.cards:hover – to add a hover feature Code .card-holder { display: flex; justify-content: space-around; flex-wrap: wrap; } .cards { width: 16%; color: white; background-color: #2c3350; padding: 10px; border-radius: 5px; margin: 0.35%; font-size: 14px; text-align: center; } .cards-img { position: relative; width: 90px; height: 65px; border-radius: 5px; } .cards:hover { background-color: #646f9a; box-shadow: 5px 5px 5px 5px #d3d3d3; } </style> </head>

4

Add the header division. Code <body> <div class=header> <img src=”planet.jpg” align=”left” class=”img-style”>

72

CO24CB0705_P1.indd 72

11/28/2023 7:24:58 PM


Code <h1>Space Exploration</h1> <img src=”rocket.jpg” alt=”rocket” width=”100” height=”100”> </div> 5

Add a sub-heading for the article cards. Code <div class=content> <p><b>Space exploration</b> is the study of space and everything beyond Earth’s atmosphere. We use robots and spacecrafts to explore space and learn new things about it. <br><br> Space exploration has led to many <i><b>amazing discoveries</b></i>, such as exoplanets (planets that orbit other stars), water on Mars, and black holes. <br><br> Space exploration is also important for inspiring people and showing us what is possible. </p> </div> <h3> Links of interesting articles about Space:</h3>

6

Add the card-holder and cards div tags.

7

Add the image and text for the first article card. Code <div class=card-holder> <div class=cards> <img src=”exoplanet.jpg” class=cards-img> <p>What is an exoplanet?</p> </div>

8

Duplicate the cards div of the first card.

9

Change the details of the second card. Code <div class=cards> <img src=”another_Earth.jpg” class=cards-img> <p>Another earth?</p> </div>

10

Repeat the process to create remaining cards. Code <div class=cards> <img src=”neutron_star.jpg” class=cards-img> <p>Neutron Star</p> </div> <div class=cards> <img src=”far_away_galaxies.jpg” class=cards-img> <p>Far-away Galaxies</p> </div>

Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 73

73

11/28/2023 7:24:58 PM


Code </div> </body> </html> When done, run your code to test it. Output

Hyperlinks Hyperlinks, also known as links, allow users to navigate from one web page to another by clicking a text or an image link. To create a hyperlink in HTML, use the <a> tag. The <a> tag has the required href attribute, which specifies the URL of the linked page. The text or the image that you want to be the link should be between the opening and closing <a> tags. For example, the following HTML code creates a hyperlink to the Uolo home page: Code <a href=“https://www.uolo.com”>Uolo</a>

74

CO24CB0705_P1.indd 74

11/28/2023 7:24:58 PM


Output Uolo When a user clicks the word “Uolo”, the web browser opens the Uolo home page.

You can also use the <a> tag to create links to other resources, such as images, PDFs, and other types of files. Let us hyperlink the article cards for the Space Exploration project. Project: Space Exploration Task 7: Hyperlink the card images. Use an anchor tag to add a link to the card image. Don’t forget to close the tag. Code <div class=cards> <a href=”https://en.wikipedia.org/wiki/Exoplanet”> <img src=”exoplanet.jpg” class=cards-img> </a> Code <div class=cards> <a href=”https://www.space.com/30172-six-most-earth-like-alien-planets.html”> <img src=”another_Earth.jpg” class=cards-img> </a>

Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 75

75

11/28/2023 7:24:58 PM


Repeat the process for the remaining cards. Code <div class=cards> <a href=”https://en.wikipedia.org/wiki/Neutron_star”> <img src=”neutron_star.jpg” class=cards-img> </a> <p>Neutron Star</p> </div> <div class=cards> <a href=”https://en.wikipedia.org/wiki/List_of_galaxies”> <img src=”far_away_galaxies.jpg” class=cards-img> </a> <p>Far-away Galaxies</p> </div> </div> </body> </html> Output

76

CO24CB0705_P1.indd 76

11/28/2023 7:24:59 PM


Click a card to check if the link is opening or not.

Coding Challenge Consider any four famous persons from the past in whom who you are interested. Make a web page about them using flexboxes. Include a picture of them, a short story about their lives, and a link to another web page with more information about them.

Chapter Checkup A

Fill in the Blanks. Hints

anchor

align-items

child

alt

flex-wrap

attribute is used to display the alternative text describing the image, if the image does not 1 The load on the web page. 2

The

property allows flex items to wrap onto more than one line.

3

The

tag is used to create a hyperlink.

4

The

property allows multiple lines of items to align along the cross axis.

5

The flex container can change the width, height, and order of the

Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 77

elements.

77

11/28/2023 7:24:59 PM


B

Tick () the Correct Option. 1

How do you create a hyperlink to an external website, using the <a> tag in HTML?

a

<a href=”#external-website”>External Website</a>

b

<a href=”http://www.example.com”>Visit Website</a>

c

<a src=”http://www.example.com”>Open Link</a>

d

<a link=”http://www.example.com”>Go There</a>

2

Which CSS property is used to create rounded images?

a

b image-shape border-radius

c

round-image d

3

Image-border

What is the main purpose of flexboxes in web development?

a

To add images to a web page

b

To create flexible layouts and arrange elements flexibly

d To add animations to web pages c To change the font style on a web page 4

How can you set a background image for an HTML <div> element, using CSS?

a

b Using the background-image property Using the <background> element

c

Using the src attribute

5

d

Which CSS property is used to make a parent container flexible in flexbox?

a

display: flex

c

flex-direction d

C

Using the alt attribute

b

flex-grow align-items

Who Am I? 1

I have attributes like ‘src’ and ‘alt’ to specify the image source and the alternative text.

2

I ensure that a background image covers the entire HTML element.

3

I create a shadow around an image, using CSS.

4

I am a CSS property to specify a filter to apply to the image.

5

I control the alignment of items in a flex container.

78

CO24CB0705_P1.indd 78

11/28/2023 7:25:00 PM


D

E

Write T for True and F for False. 1

In CSS, the ‘border-radius’ property is used to make images transparent.

2

You can style images using CSS in two ways—using the style attribute and using classes.

3

Hyperlinks can be created using text only, and images cannot be linked to other web pages.

4

The ‘margin’ property in CSS determines the space around an image.

5

The ‘flex-direction’ property determines whether flex items are arranged horizontally or vertically.

Answer the Following. 1 Identify and correct the error in the following HTML code for inserting an image: </img src=”image.jpg” alt=”A beautiful landscape”>

2

Which CSS property is used to specify the amount of space between the border of the image and its contents?

3 Correct the CSS code that sets the background image for a <div> with class “my-div” and ensures that it covers the entire div: .my-div {

background: url(‘background.jpg’);

background-size: cover;

} 4

Find the error in the following CSS code that arranges the flex items vertically in a flexbox:

.container {

display: flex;

flex-direction: row;

} 5

Explain the purpose of the ‘flex-grow’ property in a CSS flexbox.

Chapter 5 • Images and Hyperlinks in HTML

CO24CB0705_P1.indd 79

79

11/28/2023 7:25:00 PM


F

Apply Your Learning.

1

Given the following HTML and CSS code, what will be the background colour of the div when you hover over it?

<div class=”hover-button”>Hover Me</div>

.hover-button:hover {

}

background-color: yellow;

2 If you have a web page with three images styled using the class ‘image-style’ and the following CSS code, what will be the output? <img src=”image1.jpg” class=”image-style”>

<img src=”image2.jpg” class=”image-style”>

<img src=”image3.jpg” class=”image-style”>

.image-style {

width: 80%;

}

3

margin: 10px;

What is the output of the following HTML code?

<img src=”https://example.com/image.png” alt=”Image of my cat”>

What error will you get if you try to display an image that is not found?

What error will you get if you forget to add the alt attribute to an image tag?

4

Consider the following HTML code:

<div class=”flex-container”>

<img src=”https://example.com/image.png” alt=”Image of my cat”>

<a href=”https://example.com/cat-breeds”>Read more about cat breeds</a>

</div>

What output will you get if you try to display the above HTML code without using a flexbox?

80

CO24CB0705_P1.indd 80

11/28/2023 7:25:00 PM


6

Lists and Tables in HTML

In this chapter, we will learn about lists and tables in HTML. Lists in HTML are similar to a shopping list or a to-do list. They help us organise items in a neat and easy-to-read way on a webpage.

Adding Lists In HTML, we can create three types of lists:

• Ordered (numbered) • Unordered (bulleted) • Description Ordered Lists

Ordered lists, also known as numbered lists, are used to list items in a specific order. They are defined using the <ol> tag. Each list item in an ordered list is defined using the <li> tag. Here is an example of an ordered list: Code

Output

<ol>

1. Item 1

<li>Item 1</li>

2. Item 2

<li>Item 2</li> <li>Item 3</li>

3. Item 3

</ol> You can use the type attribute to specify the type of numbering for your ordered list. The default numbering type is numbers, but you can also use uppercase letters, lowercase letters, or Roman numerals. Code

Output

<ol type=”I”>

I. Item 1

<li>Item 1</li>

II. Item 2

<li>Item 2</li> <li>Item 3</li>

III. Item 3

</ol>

81

CO24CB0706_P1.indd 81

11/28/2023 7:30:19 PM


Here are some examples of different numbering schemes: Types of Numbering

Description

type=” 1”

The list items will be numbered with numbers (default).

type=” A”

The list items will be numbered with uppercase letters.

type=” a”

The list items will be numbered with lowercase letters.

type=” I”

The list items will be numbered with uppercase Roman numbers.

type=” i”

The list items will be numbered with lowercase Roman numbers.

Unordered Lists Unordered lists, also known as bulleted lists, are used to list items in no particular order. They are defined using the <ul> tag. Each list item on an unordered list is defined using the <li> tag. Here is an example of an unordered list: Code

Output

<ul>

 Item 1

<li>Item 1</li>

 Item 2

<li>Item 2</li>

 Item 3

<li>Item 3</li> </ul> You can use the style attribute to specify the bullet style for your unordered list. The default bullet style is a disc, but you can also use squares, circles, or other symbols. Code

Output

<ul style=”list-style-type: square;”>

 Item 1

<li>Item 1</li>

 Item 2

<li>Item 2</li>

 Item 3

<li>Item 3</li> </ul> Here are some examples of different bullet point styles: Bullet Style

Description

disc

Change the list item marker to a bullet.

circle

Change the list item marker to a circle.

square

Change the list item marker to a square.

none

No list item marker will be displayed

82

CO24CB0706_P1.indd 82

11/28/2023 7:30:19 PM


Description Lists Description lists are used to display a list of terms and their definitions. They are defined using the <dl> tag. Each term in a description list is defined using the <dt> tag, and each definition is defined using the <dd> tag. Here is an example of a description list: Code

Output

<dl>

Term 1 Definition 1

<dt>Term 1</dt> <dd>Definition 1</dd>

Term 2 Definition 2

<dt>Term 2</dt> <dd>Definition 2</dd>

Term 3

<dt>Term 3</dt>

Definition 3

<dd>Definition 3</dd> </dl>

Styling Lists Styling lists means improving the appearance of the list items, such as the bullet style, numbering, padding, and margin. There are two main ways to style HTML lists: 1

Using the style attribute

2

Using CSS classes

Using the Style Attribute The style attribute can be used to specify the appearance of individual list items or entire lists. To use the style attribute, simply add it to the opening tag of the list or list item and specify the desired CSS properties. Styling a List Item: We can style a list item in a list using the style attribute. For example, the following HTML code styles a list item to have grey background colour: Code

Output

<ul>

 Item 1

<li style=”background-color: #ccc;”>Item 1</li>

 Item 2

<li>Item 2</li>

 Item 3

<li>Item 3</li> </ul> Styling a List: We can also use the style attribute to style entire lists.

Chapter 6 • Lists and Tables in HTML

CO24CB0706_P1.indd 83

83

11/28/2023 7:30:19 PM


For example, the following HTML code defines an unordered list with square bullet points and 10px padding and margin: Code

Output

<ul style=”list-style-type: square; padding:10px; margin:10px;”>

 Item 1

<li>Item 1</li>

 Item 2

<li>Item 2</li>

 Item 3

<li>Item 3</li> </ul> Here are some of the most common CSS properties that can be used to style lists:

• List-style-type: Specifies the style of the bullet points or numbers in a list. • List-style-position: Specifies whether the bullet points or numbers are placed inside or outside of the list items. • List-style-image: Specifies an image to use as the bullet points in a list. • Padding: Specifies the amount of padding around the list items. • Margin: Specifies the amount of margin around the list items. • Font-size: Specifies the font size of the text in the list items. • Font-colour: Specifies the font colour of the text in the list items. • Border: Specifies a border around the list items. Using CSS Classes CSS classes can be used to style lists in a more reusable way. To use a CSS class to style a list, simply add the class name to the opening tag of the list or list item. For example, the following HTML code adds the CSS class list-style-square to an unordered list: <ul class="list-style-square"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> Then, you can use CSS to style the list items with the list-style-square class. For example, the following CSS will give all list items with the list-style-square class square bullet points and 10px padding and margin: .list-style-square {

list-style-type: square; padding: 10px; margin: 10px;

}

Discuss

How are the list style and type different?

If you need to style only a few individual list items or lists, then using the style attribute is fine.

84

CO24CB0706_P1.indd 84

11/28/2023 7:30:19 PM


However, if you need to style a lot of lists or you need to reuse the same list style throughout your webpage, then it is better to use CSS classes. Project: Space Exploration Task 8: Create and style an unordered list of fun facts about space. To do so, we first need to identify where the list will appear and what flex container do we need. We need four flex containers to place our content on the webpage as shown.

1

Create an unordered list of fun facts about space in sub-holder2 after the cards’ code. Code

<div class=sub-holder2> <div> <h3> Fun Facts About Space </h3> <ul> <li>Space is so quiet because there is no air for sound waves to travel through.</li> <li>There is an uncountable number of stars in the known universe.</li> <li>One day on Venus is longer than one year on Earth.</li> </ul> </div> </div> 2

Update and add div for containers for header, holder and sub-holder1. Code

<body> <div class=header> <img src="planet.jpg" align=left class=img-style> <h1>Space Exploration</h1> <img src="rocket.jpg" alt="rocket" width="100" height="100"> </div>

Chapter 6 • Lists and Tables in HTML

CO24CB0706_P1.indd 85

85

11/28/2023 7:30:20 PM


Code <div class=holder> <div class=sub-holder1> <div> <p><b>Space exploration</b> is the study of space and everything beyond Earth's atmosphere. We use robots and spacecraft to explore space and learn new things about it. <br><br> Space exploration has led to many <i><b>amazing discoveries</b></i>, such as exoplanets (planets that orbit other stars), water on Mars, and black holes. <br><br> Space exploration is also important for inspiring people and showing us what is possible. </p> </div> 3

Create style classes for containers and the list inside the style tag. Code .holder { display: flex; justify-content: space-around; } .sub-holder1 { width: 65%; box-shadow: 0 0 20px rgba(0, 0, 0, 0.15); padding: 5px; } .sub-holder2 { width: 25%; } ul{ box-shadow: 0 0 20px rgba(0, 0, 0, 0.15); } </style> Output

86

CO24CB0706_P1.indd 86

11/28/2023 7:30:20 PM


Bookmark Just like the bookmarks we use in our books to quickly jump to a specific page, HTML bookmarks help us jump to a specific part of a webpage on the internet. Adding a Bookmark To add a bookmark in an HTML document, follow these steps: 1

Choose the element you want to bookmark. This could be a heading, a paragraph, an image, or any other HTML element.

2

Add an id attribute to the element. The id attribute must be unique on the page.

<h2 id=”mybookmark”>This is my bookmark</h2> 3

Create a link to the bookmark. To do this, use the a element and the href attribute. The href attribute should point to the id of the element you want to bookmark.

<a href=”#mybookmark”>Click here to go to my bookmark</a> Project: Space Exploration Task 9: Add bookmarks 1

Add information about Documentaries on Space Exploration after the cards’ details. Code

<p>Far-away Galaxies</p> </div> <h3>Documentaries on Space Explorations</h3> <p><b>Cosmos: Possible Worlds (2020):</b> This 13-part documentary series hosted by Neil deGrasse Tyson explores the universe and humanity's place in it. It covers a wide range of topics, including the origins of the universe, the search for life beyond Earth, and the future of space exploration.<br><br> <b>Voyage of Time (2016):</b> This Terrence Malick-directed documentary is a visually stunning meditation on the cosmic journey of the universe, from the Big Bang to the present day. It features a voiceover by Brad Pitt.<br><br> <b>One Strange Rock (2018):</b> This 10-part documentary series hosted by Will Smith explores the wonders of Earth and humanity's place in the universe. Each episode focuses on a different aspect of Earth, such as its atmosphere, oceans, and life forms.<br><br> <b> The Last Man on the Moon (2019):</b> This documentary tells the story of Eugene Cernan, the last astronaut to walk on the moon. It features interviews with Cernan and his fellow Apollo 17 crew members, as well as archival footage from the mission.<br><br> <b>Apollo 11 (2019):</b> This documentary tells the story of the Apollo 11 mission, which landed the first humans on the moon. It features restored footage from the mission, as well as interviews with the astronauts and other people involved in the mission.<br><br><br></p>

Chapter 6 • Lists and Tables in HTML

CO24CB0706_P1.indd 87

87

11/28/2023 7:30:20 PM


2

Add an id attribute to the elements you want to bookmark: a

The h3 element for the articles section.

<h3 id=b1> Links of interesting articles about Space:</h3> b The h3 element for the documentaries section. <h3 id=b2>Documentaries on Space Explorations</h3> c The h3 element for Fun facts. <h3 id=b3> Fun Facts About Space </h3> 3 Create link to the bookmarks Code <div class=holder> <div class=sub-holder1> <div> <p><a href="#b1">Interesting Articles</a></p> <p><a href="#b2">Documentaries on Space Explorations</a></p> <p><a href="#b3">Fun Facts about Space</a></p> <p><b>Space exploration</b> is the study of space and everything beyond Earth's atmosphere. We use robots and spacecrafts to explore space and learn new things about it. <br><br> Space exploration has led to many <i><b>amazing discoveries</b></i>, such as exoplanets (planets that orbit other stars), water on Mars, and black holes. <br><br> Space exploration is also important for inspiring people and showing us what is possible. </p> Output

88

CO24CB0706_P1.indd 88

11/28/2023 7:30:21 PM


Do It Yourself 6A d

1 Read the statements and solve the puzzle.

b U

Across a CSS property can be used to add space around list items.

L e

c

b The HTML tag used to create an unordered list.

L

c This HTML tag is used to create an ordered list.

a P

Down

A

D

N G

E

d A type of HTML list that doesn’t have any specific order. e The HTML tag is used for individual list items.

D

2 Match the Following. Column A

Column B

HTML tag used for ordered lists

disc

The default bullet style for an unordered list

ol

CSS property used to specify the style of bullet points or numbers in a list

style an individual list item using HTML attributes

Using the style attribute

list-style-type

Tables Imagine you have a list of your favourite video games. You want to write down the name of each game, the genre, and the release date. You could write this information in a list, but it would be difficult to read and understand. A better way to organise this information is to use a table. A table is a grid of rows and columns. Each row represents one item on your list, and each column represents a different piece of information about that item.

Did You Know? Web designers choose colours for websites based on colour psychology. Like blue is often used for trustworthiness, while red can create a sense of urgency.

Creating Tables To create a table in HTML, we use the following tags: Tag

Purpose

<table></table>

This tag is used to create a table.

<th></th>

This tag is used to add table headers. The headings are bold and centred by default.

<tr></tr>

This tag is used to create table rows.

Chapter 6 • Lists and Tables in HTML

CO24CB0706_P1.indd 89

89

12/6/2023 5:52:42 PM


Tag

Purpose

<td></td>

This tag is used to create a data cell and add data to the cell. The data in a cell is left-aligned by default.

<caption></caption>

This tag is used to add captions to a table. It must be added right after the <table> tag. A table caption will be centred above a table by default.

<thead></thead>

This stands for ‘table header’ and is used to group the header content in your table.

<tbody></tbody>

This stands for ‘table body’ and contains the main content of your table, such as data rows with <td> (table data) elements.

<tfoot></tfoot>

This stands for ‘table footer’ and is used for any footer content in your table.

Here is an example of a simple HTML table: Code <table>

<tbody>

<caption>Favourite Video Games</caption>

<tfoot>

<tr>

<tr>

<td>Minecraft</td>

<thead>

<td>

<td>Sandbox</td>

<tr>

Total Games: 2

<td>2011</td>

<th>Video Game</th> <th>Genre</th> <th>Release Date</th> </tr>

</td>

</tr>

</tr>

<tr>

</tfoot>

<td>Fortnite</td>

</table>

<td>Battle Royale</td>

</thead>

<td>2017</td> </tr> </tbody> Output Favourite Video Games

Video Game

Genre

Release Date

Minecraft

Sandbox

2011

Fortnite

Battle Royale

2017

Total Games: 2

90

CO24CB0706_P1.indd 90

11/28/2023 7:30:21 PM


Styling Table To style tables in HTML, you can use CSS. CSS is a language that allows you to control the appearance of HTML elements. Here are some basic CSS properties that you can use to style tables:

• Border: This property controls the border of the table. You can specify the border thickness, style, and colour. • Border-collapse: This property controls the collapse of table borders. By default, the borders of adjacent table cells will touch each other. You can use the border-collapse property to collapse the borders of adjacent table cells into a single border.

• Margin: This property controls the margin around the table. The margin is the space between the table and the other elements on the webpage.

• Padding: This property controls the padding inside the table. The padding is the space between the border of the table and the content of the table cells.

• Width: This property controls the width of the table. • Height: This property controls the height of the table.

You can also use CSS to style the individual elements of a table, such as the table header cells, table data cells, and table caption. Here is an example of how to use CSS to style a table: Code <html>

<body>

<head>

<table>

<td>Fortnite</td>

<style>

<tr>

<td>Battle Royale</td>

table {

<th>Video Game</th>

<td>2017</td>

border: 1px solid black;

<th>Genre</th>

</tr>

border-collapse: collapse;

<th>Release Date</th>

<tr>

margin: 0 auto;

</tr>

<td>Among Us</td>

padding: 10px;

<tr>

<td>Social Deduction</td>

width: 400px;

<td>Minecraft</td>

<td>2018</td>

}

<td>Sandbox</td>

</tr>

th {

<td>2011</td>

</table>

background-color: #ab2f;

</tr>

</body>

text-align: center; } td {

<tr>

</html> Output

text-align: center; } </style> </head>

Chapter 6 • Lists and Tables in HTML

CO24CB0706_P1.indd 91

91

11/28/2023 7:30:22 PM


Project: Space Exploration Task 10: Add a table and style it. 1

Add the table on Stars with Exoplanets in sub-holder2 before Fun facts. Code <div class=sub-holder2> <div> <h3 id=b3>Stars with Exoplanets</h3> <table> <tr> <th>Name of the Star</th> <th>Number of Exoplanets</th> </tr> <tr> <td>Epsilon Eridani</td> <td>3</td> </tr> <tr> <td>Lacaille 9352</td> <td>2</td> </tr> <tr> <td>Ross 128</td> <td>1</td> </tr> <tr> <td>Epsilon Indi</td> <td>6</td> </tr> </table> </div> <div> <h3 id=b4> Fun Facts About Space </h3>

2

Style the table by adding shadow. Code

table {

box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);

} </style>

92

CO24CB0706_P1.indd 92

11/28/2023 7:30:22 PM


Output

You can add a bookmark for the newly added table as well.

Coding Challenge 1.

Think and Tell

Create a webpage for your travel bucket list.

Does CSS allow us to change the appearance of multiple webpages by modifying just one stylesheet?

2. Create a webpage about your favourite book. Add bookmarks to different sections of the book, such as chapters or characters, and create links to jump to those bookmarks.

Chapter Checkup A

Fill in the Blanks. Hints

list-style-type

type

numbered

tbody

1

Ordered lists are also known as

2

You can change the style of unordered list items using the

3

To style an individual list item using HTML attributes, we can use the

4

You can change the type of numbering in ordered lists using the

style

lists and are used to list items in a specific order. property. attribute. attribute.

5 The HTML tag used to contain the main content of your table, such as data rows with <td> (table data) elements is tag.

Chapter 6 • Lists and Tables in HTML

CO24CB0706_P1.indd 93

93

11/28/2023 7:30:22 PM


B

Tick () the Correct Option. 1

Which CSS property specifies an image to use as the bullet points in a list?

a

List-style-image b

Padding

c

List-style-type d

None of these

2

Which tag is used to define a term in a description list?

a

<dd> b

<dt>

c

<dl> d

<li>

3

What property is used to add a border to a table in CSS?

a

Border-style

b

Border

c

Border-collapse

d

Table-border-style

4

The data in a table's cell is:

a

Left-aligned by default.

b

Right-aligned by default.

c

Centre-aligned by default.

d

Top Left-aligned by default.

C

Who Am I? 1

I am an attribute to specify the type of numbering for your ordered list.

2

I am an HTML tag used to create a table header. I am commonly found inside the <thead> element.

3 I am a CSS property that helps you set the background colour for table cells. I can make your tables visually distinct.

D

4

I am centred above the table by default.

5

I am used to mark a specific spot on a webpage to quickly jump back to it when needed.

Write T for True and F for False.

1

There must be at least one ‘tr’ tag inside the ‘thead’ element.

2

<style>

table,th,td{

margin:2px;

}

border-collapse: collapse;

</style>

94

CO24CB0706_P1.indd 94

11/28/2023 7:30:22 PM


E

In the code snippet other than ‘solid’, you can use any other style. 3

<th> tag does not have a closing tag.

4

<td> tag is used to create a row in a table.

5

<a href=”#bookmark”> is a valid way to create a link to a bookmark within the same HTML document.

Answer the Following. 1

What happens when you click on a link with the following HTML code? <a href=”#myBookmark”>Jump to Important Information</a>

2

Write the code to change the bullet style of the list to squares.

3

How would you change the text colour of all the list items to blue?

4

What is the purpose of using the id attribute when creating bookmarks?

5

Identify the error in this CSS code and provide the corrected version:

body {

background-color: #f0f0f0;

font-color: #333;

font:size: 14px;

margin 15px;

}

F

padding: 10px;

Apply Your Learning. 1

Make an ordered list of your hobbies and number the list with lowercase letters.

2

Identify the error in the following HTML code snippets: a

<ol>

b

<table>

<li>Item 1</li>

<caption>Table of Products</capiton>

<li>Item 2</ol>

<tr>

<li>Item 3</li>

<th>Product</th>

</ol>

<th>Price</th> <tr> </table>

Chapter 6 • Lists and Tables in HTML

CO24CB0706_P1.indd 95

95

11/28/2023 7:30:23 PM


3

What’s the mistake in this code for creating a bookmark link? <a href=”section2”>Jump to Section 2</a>

4 Write a program that creates a table of the planets in the solar system, including their names, distances from the sun, and number of moons.

5 Write a program that creates a table of the scores for a soccer game, including the team names, goals scored, and yellow and red cards received.

6 Create an HTML list of your favourite foods. Add CSS to change the colour of the list items when you hover over them.

96

CO24CB0706_P1.indd 96

11/28/2023 7:30:23 PM



About the Book This coding book is supplementary to the main “Mel n 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 graduation with real-life examples and practice problems.

Special Features • Illustrative approach: Concepts in coding and computer science are delivered through pictorial representations and learner-friendly approaches. • Learning through real-life examples: Age-appropriate examples that enable learners to relate to the concept and learn about the unknown from the known. • Extensive practice: Multiple practice scenarios to reinforce learnings. • Coding challenges: Includes projects through which learners can demonstrate their learning outcomes in coding and computer science.

About Uolo Uolo partners with K-12 schools to bring technology-based learning programs. We believe pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. Uolo is trusted by over 10,000 schools across India, South East Asia, and the Middle East.

Singapore

|

CS_CB_Coding_Grade7_Cover.indd All Pages

Gurugram

|

Bengaluru

|

hello@uolo.com �199

© 2024 Uolo EdTech Pvt. Ltd. All rights reserved.

NEP 2020 based

|

NCF compliant

|

Technology powered

04/12/23 1:30 PM


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.