0% found this document useful (0 votes)
17 views69 pages

Study Guide

The document serves as a study guide for Grade 8 Computer Studies at The Shri Ram School, Moulsari, covering topics such as Computational Thinking, Algorithms, Flowcharts, and Python Coding. It outlines key concepts, definitions, and learning objectives, along with practical examples and exercises to enhance understanding of computational problem-solving and programming. The guide emphasizes the importance of skills like decomposition, pattern recognition, and algorithm design in developing effective solutions.

Uploaded by

shivchadda13
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views69 pages

Study Guide

The document serves as a study guide for Grade 8 Computer Studies at The Shri Ram School, Moulsari, covering topics such as Computational Thinking, Algorithms, Flowcharts, and Python Coding. It outlines key concepts, definitions, and learning objectives, along with practical examples and exercises to enhance understanding of computational problem-solving and programming. The guide emphasizes the importance of skills like decomposition, pattern recognition, and algorithm design in developing effective solutions.

Uploaded by

shivchadda13
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

The Shri Ram School, Moulsari

Study Guide- Grade 8


Computer Studies

Name: ………………………………………………………………

Class: ………………………………………………………………

1
2
Table of Contents

Computational Thinking ……………………. 05

Algorithms and Flowcharts ……………………. 13

Python Coding: Introduction ……………………. 29

Python Coding: Conditional Constructs ……………………. 43

Python Coding: Lists ……………………. 49

Python Coding: Iteration Constructs ……………………. 57

Application Development ....................... 61

3
4
Computational
Thinking

5
Learning Objectives
• Introduction
• Definition
• Essential Dimensions
• The Four Cornerstones of Computational Thinking
o Decomposition
o Pattern Recognition
o Abstraction
o Algorithm Design
• Computational Thinking: What it is, and isn’t?

Introduction
• Computers can be used to help us solve problems. However, before a
problem can be tackled, the problem itself and the ways in which it could
be solved need to be understood. Computational Thinking (CT) allows us
to do this.
• Computational Thinking allows us to take a complex problem, understand
what the problem is and develop possible solutions. We can then present
these solutions in a way that a computer, a human, or both, can
understand.

Definition
Computational thinking (CT) is a problem-solving process that includes (but is
not limited to) the following skills:
• Formulating problems in a way that enables us to use a computer and
other tools to help solve them
• Logically organizing and analyzing data
• Representing data through abstractions such as models and simulations
• Automating solutions through algorithmic thinking (a series of ordered
steps)
• Identifying, analyzing, and implementing possible solutions with the goal
of achieving the most efficient and effective combination of steps and
resources
• Generalizing and transferring this problem-solving process to a wide
variety of problems

6
Essential Dimensions
The skills (outlined in the definition of CT) are supported and enhanced by
several dispositions or attitudes that are essential dimensions of CT. These
dispositions or attitudes include:
• Confidence in dealing with complexity
• Persistence in working with difficult problems
• Tolerance for ambiguity
• The ability to deal with open ended problems
• The ability to communicate and work with others to achieve a common
goal or solution

The Four Cornerstones of Computational Thinking

Source: [Link]

7
Decomposition
• Decomposition is a process where you break down a complex problem or
system into smaller more manageable parts. These smaller parts can then
be analyzed, solved, or addressed separately to solve the larger problem
or to better understand the system.
• Decomposition is often applied in fields like software engineering, web
development, artificial intelligence, and database management.
• Example- Consider a machine learning algorithm used for image
recognition. The whole process can be decomposed into several steps-
preprocessing the images, extracting features from the images, training
the model with these features, and finally testing the model to evaluate
its performance. Decomposition makes it easier to understand the
working of such complex models.

Pattern Recognition
• Pattern recognition is the ability to analyze and identify the shared
characteristics between parts of a decomposed problem.
• Pattern Recognition forms the backbone for abstraction in computational
thinking. By identifying and understanding patterns, abstractions or
general rules can be formulated. These patterns, in turn, guide the
problem-solving approach, editing how algorithms are designed and
implemented.
• Example- In a chess game, an AI system uses pattern recognition to
predict the opponent’s next move and plan its strategy accordingly.
Similarly, ML algorithms leverage pattern recognition to interpret MRI
scans for detecting anomalies.
• Example- A spam filter, which recognises the pattern of words in an email
to categorise it as spam or not-spam.
• A ubiquitous example is that of recommended systems in our favourite
online platforms like Amazon or Netflix. These platforms register your
past browsing and purchasing history, identifying patterns in the choices
you make. This implies that they have a database filled with patterns of
choices made by all their users. A Machine Learning algorithm is then used
to compare your patterns with that in the database. Based on similarities
identified, the system recommends you new items, predicting your
specific preferences.

8
Abstraction
• Abstraction involves filtering out – essentially, ignoring - the
characteristics that we don't need to concentrate on those that we do.
• Abstraction allows us to create a general idea of what the problem is and
how to solve it. The process instructs us to remove all specific detail, and
any patterns that will not help us solve our problem. This helps us form
our idea of the problem. This idea is known as a ‘model’.

Algorithm Design
• An algorithm is a plan, a set of step-by-step instructions to solve a
problem. If you can tie shoelaces, make a cup of tea, get dressed or
prepare a meal then you already know how to follow an algorithm.
• In an algorithm, each instruction is identified and the order in which they
should be carried out is planned. Algorithms are often used as a starting
point for creating a computer program, and they are sometimes written
as a flowchart or in pseudocode.
• If we want to tell a computer to do something, we must write a computer
program that will tell the computer, step-by-step, exactly what we want
it to do and how we want it to do it. This step-by-step program will need
planning, and to do this we use an algorithm.
• Algorithms are used for many different things including calculations, data
processing, searching, and automation.
• It is important to plan out the solution to a problem to make sure that it
will be correct. Using computational thinking and decomposition we can
break down the problem into smaller parts and then we can plan out how
they fit back together in a suitable order to solve the problem.
• This order can be represented as an algorithm. An algorithm must be
clear. It must have a starting point, a finishing point, and a set of clear
instructions in between.

Picture Courtesy: [Link]

9
Computational Thinking: What it is, and isn’t?
• Conceptualizing, not programming. CT is neither computer
programming, nor it is thinking like a computer. Computers do not and
cannot “think” at the first place. It requires thinking at multiple levels of
abstraction.
• Fundamental, not rote skill. A fundamental skill is something every
human being must know to function in modern society. Rote means a
mechanical routine.
• A way that humans, not computers, think. CT is a way humans solve
problems; it is not trying to get humans to think like computers.
Computers are dull and boring; humans are clever and imaginative. We
humans make computers exciting.
• Ideas, not artifacts. It’s not just the software and hardware artifacts we
produce that will be physically present everywhere and touch our lives all
the time, it will be the computational concepts we use to approach and
solve problems, manage our daily lives, and communicate and interact
with other people.
• Complements and combines mathematical and engineering thinking. CT
inherently draws on mathematical thinking, given that, like all sciences,
its formal foundations rest on mathematics. Computer science inherently
draws on engineering thinking, given that we build systems that interact
with the real world. The constraints of the underlying computing device
force computer scientists to think computationally, not just
mathematically. Being free to build virtual worlds enables us to engineer
systems beyond the physical world.
• For everyone, everywhere. Computational Thinking (CT) will be a reality
when it is so integral to human endeavours it disappears as an explicit
philosophy.

10
Glossary

abstraction one of the four steps in computational thinking to gather the


general characteristics and to filter out of the details we do not
need to solve our problem

algorithm a plan, a set of step-by-step instructions to resolve a problem.


In an algorithm, each instruction is identified and the order in
which they should be carried out is planned.

computational thinking a problem-solving method using computer science


techniques, where possible solutions are developed and
presented in a way that can be understood by humans and
computers

decomposition the process of breaking down a problem into smaller, more


manageable parts that can be addressed more easily. It's the
first step in computational thinking.

flowchart a diagram that shows a process, made up of boxes/ shapes


representing steps, process (es), decision (s), inputs, and
outputs

instruction a single action that can be performed by a computer processor

pattern recognition one of the four steps in computational thinking that involves
finding similarities and patterns in data to simplify problems
and improve comprehension.

program a set of instructions written in a programming language that


tells a computer to perform a specific task. The instructions
are translated (assembled, interpreted, or compiled) into
machine-readable form and then executed by the computer.

pseudocode also written as pseudo-code; a method of writing up a set of


instructions for a computer program using plain English

11
12
Algorithms
and
Flowcharts

13
Learning Objectives
• What is an Algorithm?
• What is a Flowchart?
• Advantages of using Algorithms and Flowcharts
• Difference between an Algorithm and a Flowchart
• Tips for writing Algorithms
• Characteristics of an Algorithm
• Steps for creating a Flowchart
• Symbols used in Flowcharts
• Variables and Constants
• A few examples for practice

What is an Algorithm?
An algorithm is a set of instructions that a computer follows to perform a specific
task. It is a step-by-step procedure that outlines the actions to be taken to solve
a particular problem.

What is a Flowchart?
A flowchart is a graphical representation of an algorithm that uses symbols and
arrows to show the flow of instructions. It is a visual tool used to illustrate the
steps involved in a process.

Advantages of using Algorithms and Flowcharts


• Provide a clear and concise way to understand a process
• Help in identifying errors and inefficiencies in a process
• Enable easy modification and improvement of a process
• Facilitate communication between different stakeholders involved in a
process

In addition to being used by technology, a lot of things we do daily are like


algorithms.

Let's say you want to make some spaghetti. To do this successfully, there's a
certain set of steps you need to follow in a particular order. First, you'll need
to boil a pot of water. Once it's boiling, you then add the spaghetti and cook
it for a set amount of time, stirring occasionally. Once it's finished, you drain the
water, then it's ready to be served with a sauce of your choice.

14
This entire process is an algorithm. Because you followed these steps in a
particular order, you reached your desired outcome: a delicious pasta dish.

Difference between an Algorithm and a Flowchart

Tips for writing Algorithms


• Use clear and concise language.
• Break down the problem into smaller steps.
• Use meaningful names for variables and functions.
• Consider efficiency and resource usage when designing an algorithm.
• Test the algorithm with different inputs to ensure it produces the
expected output.

15
Characteristics of an Algorithm

Steps for Creating a Flowchart


• Define the problem to be solved.
• Break down the problem into smaller steps or processes.
• Identify the decision points and input/output required.
• Arrange the steps in a logical sequence.
• Draw the flowchart using the appropriate symbols and arrows.
• Test the flowchart to ensure it correctly solves the problem.

16
Symbols used in Flowcharts
Flowcharts use a particular shape to denote each action so just by looking at the
shapes used, you know whether it is user input, some conditional statement, or
some calculations being done in a particular step. The meanings of some of the
more common shapes are as follows:

17
Few Important points before we start:

Assignment Operator
Values are assigned to an item/variable using the ← operator. The variable on
the left of the ← is assigned the value of the expression on the right.

Input and Output Statements


INPUT and OUTPUT are used for the entry of data and display of information

INPUT is used for data entry. It is usually followed by a variable where the data
input is stored, for example:
INPUT Name
INPUT StudentMark

OUPUT/PRINT is used to display information either on a screen or printed on


paper.
PRINT Name
PRINT “Your name is”, Name

18
Variables and Constants
Algorithms use variables or constants which is like a container used to store a
value or a piece of information in a computer program. It is a named memory
location that can hold different values during the execution of a program.

For example, let's say you are writing a program to calculate the area of a
rectangle. You would need to store the length and width of the rectangle as
variables. You could name the variables "length" and "width", and assign them
values such as 10 and 5, respectively. Once the variables are defined and
assigned values, you can perform calculations using them.

To calculate the area of the rectangle, you would multiply the length and width
variables together:

area = length * width

Here, area is a variable.

Variables can be of different data types, such as integers, decimals, or


characters. The data type of a variable determines the kind of value it can hold
and the nature of operations that can be performed on it.

19
20
Example 1: Accept two numbers from the user and display the greater number

Algorithm:
Step 1: Start
Step 2: Read two numbers X and Y
Step 3: Check if X > Y
Step 4: If the condition is true, Print X
Step 5: If the condition is false, Print Y
Step 6: Stop

Flowchart:

21
Example 2: Print numbers from 1 to 20

Algorithm:
Step 1: Start
Step 2: Initialize X as 0
Step 3: Increment X by 1
Step 4: Print X
Step 5: If X is less than 20 then go back to step 3
Step 6: Stop

Flowchart:

22
Example 3: Convert temperature from Fahrenheit (℉) to Celsius (℃)

Algorithm:
Step 1: Start
Step 2: Read temperature in Fahrenheit
Step 3: Calculate temperature with formula C = 5 / 9 * (F - 32)
Step 4: Print C
Step 5: Stop

Flowchart:

23
Example 4: Determine whether a student passed the exam or not

Algorithm:
Step 1: Start
Step 2: Input marks of 4 courses M1, M2, M3 and M4,
Step 3: Calculate the average marks as Grade = (M1+M2+M3+M4) / 4
Step 4: If Grade is less than 60, print "FAIL", else print "PASS"
Step 5: Stop

Flowchart:

24
Example 5: Input two numbers and display their sum

Algorithm:
Step 1: Start
Step 2: Input two numbers, say A and B
Step 3: Calculate the sum as sum = A + B
Step 4: Print sum
Step 5: Stop

Flowchart:

25
Example 6: Determine if the given number is even or odd

Algorithm:
Step 1: Start
Step 2: Input a number, say Number
Step 3: Divide the Number by 2 and check the remainder
Step 4: If the remainder is equal to 0 then print “even” else print “odd”
Step 5: Stop

Note: In coding, the modulus operator (represented as %) returns the remainder


when the first operand is divided by the second operand.

Flowchart:

26
Example 7: Determine if the given number is positive, negative or zero

Algorithm:
Step 1: Start
Step 2: Input a number, say N
Step 3: If N > 0 then print “positive” else if N < 0 then print “negative” else print
“zero”
Step 4: Stop

Flowchart:

27
28
Python Coding:
Introduction

29
Learning Objectives
• Introduction
• Features of Python
• Python IDLE
• Python Statements
• Python Comments
• Python Tokens
• Variables
• Data Types
• Typecasting
• Displaying output in Python
• Getting user’s input in Python

Introduction
Python is a high-level programming language belonging to the
fourth generation of programming languages. Python was
developed by Guido van Rossum in the late 1980s. Python is a
powerful language that you can use to create games, write GUIs,
and develop web applications.

Features of Python
• Easy to code
• Less learning time
• Readability: Python programs use clear, simple, and concise instructions
that are easy to read even by those who have no substantial programming
background. Programs written in Python are, therefore, easier to
maintain, debug, or enhance.
• Higher productivity: Codes used in Python are considerably shorter,
simpler, and less verbose than other high-level programming languages
such as Java and C++. In addition, it has well-designed built-in features
and standard library.
• Interpreted: When a programming language is interpreted, it means that
the source code is executed line by line, and not all at once. Python is
processed at runtime by the interpreter.

30
• Open source: Python is an open-source language, which means it is free
and available for everybody to use for any purpose. It doesn't cost
anything to download Python or to include it in your application. It can
also be freely modified and re-distributed.
• Object-oriented: In Python, each entity, such as, a variable, a function, a
list, etc. is handled as an object belonging to a particular class.
• Cross platform: Python works on Windows, Linux/UNIX, Mac OS X, other
operating systems, and small-form devices. It also runs on
microcontrollers used in appliances, toys, remote controls, embedded
devices, and other similar devices.

Python IDLE
IDLE (Integrated Development and Learning Environment) is an integrated
development environment (IDE) for Python. An integrated development
environment (IDE) is a software suite that consolidates basic tools required to
write and test software. Developers use numerous tools throughout software
code creation, building and testing.

Note: Python provides a Python Shell, which is used to execute a single Python command and
display the result. That is why it is called the interactive mode.

To start an IDLE interactive shell, search


for the IDLE icon in the start menu and
double click on it.

31
This will open IDLE, where you can write and execute the Python scripts, as
shown below.

You can execute Python statements in Python Shell as shown below.

32
To execute a Python script, create a new file by going to File → New File.

1. Enter multiple statements and save the file.


2. To save the file, go to File → Save.
3. To run the script, go to Run → Run Module or press the F5 function key in
the editor window. The IDLE shell will show the output.
Note: Python program file (source code) is saved with .py extension.

Python Statements
Statements are instructions that a Python interpreter can execute. When you
assign a value to a variable, say my_variable = “dog”, you’re making an
assignment statement. An assignment statement may also be as short as c = 3.
There are other kinds of statements in Python, like if statements, while
statements, for statements, etc.

Python Comments
When writing a program, you’ll find it helpful to put some notes within your
code to describe what it does. A comment is very handy when you must review
or revisit your program. It will also help another programmer who might need
to go over the source code. You can write comments within your program by
starting the line with a hash (#) symbol. A hash symbol tells the Python
interpreter to ignore the comment when running your code.

33
Tokens
A token is the smallest individual unit within a program. There are five types of
tokens:
• Identifier
• Keyword
• Literal
• Operator
• Delimiters

Keywords
• A programming language comprises of a set of predefined words which
are called keywords.
• Since they have a predefined meaning attached, they cannot be used for
any other purpose.
• The list of Python keywords can be obtained by typing the following help
command in Python shell.

• Typing the above command in Python Shell will produce the following
output:

Note: Python 3.x has 33 keywords. Except for the first three (False, None and True), the other
keywords are entirely in lowercase.

34
Literals
A literal is the raw data given in a variable or constant. In Python, there are
various types of literals. They are as follows:

String literals
A String literal is a sequence of characters surrounded by either single quotation
marks or double quotation marks.
'hello' is same as "hello".

Numeric literals
Numeric literals can belong to 3 different numerical types: Integer, Float and
Complex.

Boolean literals
A Boolean literal can have any of the two values: True or False.

Collection literals
Python provides four types of collection literals: List, Tuple, Dictionary, and set.

35
Identifiers
• A Python Identifier is a name given to a function, class, variable, module,
or other types of entities that you’ll be using in your Python program.
• Any entity you’ll be using in Python should be appropriately named or
identified as they will form part of your program.

Here are Python naming conventions that you should be aware of:
• Special characters such as %, @, and $ are not allowed within identifiers.
• An identifier should not begin with a number. Hence, 2variable is not
valid, but variable2 is acceptable.
• Python is a case-sensitive language, and this behavior extends to
identifiers. Thus, Count and count are two distinct identifiers in Python.
• You cannot use Python keywords as identifiers.
• You can use underscores to separate multiple words in your identifier.

Operators
Operators are special symbols that perform some operation on operands and
returns the result. For example, 5 + 6 is an expression where + is an operator
that performs arithmetic add operation on numeric left-side operand 5 and the
right-side operand 6 and returns the sum of two operands as a result.

Python includes the following categories of operators:


• Arithmetic Operators
• Assignment Operators
• Relational or Comparison Operators
• Logical Operators

36
Arithmetic Operators
Arithmetic operators perform the common mathematical operation on the
numeric operands. The arithmetic operators return the type of result depends
on the type of operands, as below:
• If either operand is a complex number, the result is converted to complex.
• If either operand is a floating-point number, the result is converted to
floating point.
• If both operands are integers, then the result is an integer, and no
conversion is needed.
The following table lists all the arithmetic operators in Python:

Assignment Operators
The following table lists all the assignment operators in Python:

37
Relational or Comparison Operators
The following table lists all the relational or comparison operators in Python:

Logical Operators
The following table lists all the logical operators in Python:

Delimiters
• Python uses symbols and combinations of symbols as delimiters in
expressions, literals, tuples, lists, dictionaries, strings, and various parts of
a statement.
• For example, comma (,) character that we used to delimit alphanumeric
and numeric data within the print () function.

38
Variables
• Variables are containers for storing data values.

• Python has no specific command for declaring a variable.


• A variable is created the moment you first assign a value to it.
For example,
x=5
y = "John"
print (x)
print (y)
• Variables do not need to be declared with any type. Their type is
determined by the type of value stored in it.
For example,
x=4 # x is of type int
x = "Sally" # x is now of type str
print (x)

Data Types
• Variables can store data of different types, and different types can do
different things.
• Python has the following data types built-in by default, in these
categories:

39
• You can get the data type of any object by using the type () function:
For example,
To print the data type of the variable x:
x=5
print (type (x))
The output of the above program will be: <class 'int'>

Typecasting
There may be times when you want to specify a type on to a variable. This can
be done with typecasting.

#Example
#Integers
x = int (1) # x will be 1
y = int (2.8) # y will be 2
z = int ("3") # z will be 3

#Example
#Floats
w = float (1) # w will be 1.0
x = float (2.8) # x will be 2.8
y = float ("3") # y will be 3.0
z = float ("4.2") # z will be 4.2

#Example
#Strings
x = str ("s1") # x will be 's1'
y = str (2) # y will be '2'
z = str (3.0) # z will be '3.0'

40
Displaying output in Python
The print () function in Python displays an output to a console or to the text
stream file. You can pass any type of data to the print () function to be displayed
on the console.

For example,
print (“Hello”)
The output of the above statement will be: Hello

• To combine both, a piece of text and a variable, Python uses the +


character.
For example,
x = "awesome"
print ("Python is " + x)
The output of the above program will be: Python is awesome
• You can also use the + character to add a variable to another variable.
For example,
x = "Python is "
y = "awesome"
z=x+y
print (z)
The output of the above program will be: Python is awesome

Note: For numbers, the + character works as a mathematical operator.

For example,
x=5
y = 10
print (x + y)
The output of the above program will be: 15

41
• If you try to combine a string and a number, Python will give you an error.
For example,
x=5
y = "John"
print (x + y)

Note: To combine a string and a numeric literal or variable, use, (comma) instead of + (plus).

Getting user’s input in Python


The input () function is used to get the user's input. It reads the keystrokes as a
string object which can be referred to by a variable having a suitable name.

Note: The blinking cursor waits for the user's input. The user enters his input and then hits
Enter. This will be captured as a string.

The input () function has an optional string parameter that acts as a prompt for
the user as shown below.

42
Python Coding:
Conditional Constructs

43
Learning Objectives
• Conditional/ Selection Constructs
• Various forms of the if Statement
o Python if Statement
o Python if...else Statement
o Python if...elif...else Statement

Conditional/ Selection Constructs


• In computer programming, we use the conditional statements to run a
block of code only when a certain condition is met at the time of making
a decision.
• Decision making is required when we want to execute a code only if a
certain condition is satisfied.
• For example, assigning grades (A, B, C) based on marks obtained by a
student.
if the percentage is above 90, assign grade A
if the percentage is above 75, assign grade B
if the percentage is above 65, assign grade C

Various forms of the if statement


In Python, there are three forms of the if statement:
• The if statement
• The if...else statement
• The if...elif...else statement

Python if Statement
The syntax of if statement in Python is:
if condition:
# body of if statement

The if statement evaluates the given condition.


If condition is evaluated to True, the code inside the body of if is executed.
If condition is evaluated to False, the code inside the body of if is skipped.
In Python, the body of the if statement is indicated by the indentation. Body
starts with an indentation and the first unindented line marks the end.

44
Example 1: Python if Statement
number = 10
# check if number is greater than 0
if number > 0:
print ('Number is positive.')
print ('Code following the if block’)

Output of Example 1:
Number is positive.
Code following the if block

In the above example, we have created a variable named number. Notice the
test condition, number > 0

Here, since number is greater than 0, the condition evaluates True, the body of
if block is executed.

If we change the value of the variable number to a negative integer.


Let's say -5.
number = -5

Now, when we run the program, the output will be:


Code following the if block

This is because the value of number is less than 0. Hence, the condition evaluates
to False. And, the body of if block is skipped.

45
Python if...else Statement
An if statement can have an optional else clause.
The syntax of if...else statement is:
if condition:
# block of code if condition is True
else:
# block of code if condition is False

The if...else statement evaluates the given condition:


If the condition evaluates to True,
• the code inside if is executed
• the code inside else is skipped
If the condition evaluates to False,
• the code inside else is executed
• the code inside if is skipped

Example 2. Python if...else Statement


number = 10
if number > 0:
print ('Positive number')
else:
print ('Negative number')
print ('This statement is always executed')

46
Output of Example 2
Positive number
This statement is always executed

In the above example, we have created a variable named number. Notice the
test condition, number > 0. Since the value of number is 10, the test condition
evaluates to True. Hence, code inside the body of if is executed.

If we change the value of variable to a negative integer. Let's say -5.


number = -5

Now if we run the program, the output will be:


Number is negative.
This statement is always executed.

Here, the test condition evaluates to False. Hence, code inside the body of else
is executed.

Python if...elif...else Statement


The if...else statement is used to execute a block of code among two
alternatives. However, if we need to make a choice between more than two
alternatives, then we use the if...elif...else statement.
The syntax of the if...elif...else statement is:
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3

Here,
If condition1 evaluates to True, code block 1 is executed.
If condition1 evaluates to False, then condition2 is evaluated.
If condition2 is True, code block 2 is executed.
If condition2 is False, code block 3 is executed.

47
Example 3: Python if...elif...else Statement
number = 0
if number > 0:
print ("Positive number")
elif number < 0:
print ('Negative number')
else:
print ('Zero')
print ('This statement is always executed')

Output of Example 3
Zero
This statement is always executed

In the above example, we have created a variable named number with the value
0. Here, we have two condition (test) expressions. Here, both the conditions
evaluate to False. Hence, the statement inside the body of else is executed.

48
Python Coding:
Lists

49
Learning Objectives
• What are lists?
• What are the characteristics of lists?
• How to create and display a list?
• How to access an individual item from a list?
o Negative Indexing
• List Methods

What are Lists?


• A list is a sequence datatype which is used to store data items of similar
type or different types.
• Suppose we need to record the ages of 5 students. Instead of creating 5
separate variables, we can simply create a list with five elements.

• Lists are one of the four built-in data types in Python used to store data
items, the other 3 are Tuple, Set, and Dictionary, all with different
characteristics and usage.

What are the characteristics of Lists?


• List items are indexed, the first item has index [0], the second item has
index [1] etc.
• Lists allow duplicates, since lists are indexed, lists can have items with the
same value.
• Lists are changeable, meaning that we can change, add, and remove items
in a list after it has been created.
• List items are ordered, meaning that the items have a defined order, and
that order will not change. If you add new items to a list, the new items
will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order
of the items will not change.

50
How to create a list?
We create a list by placing elements inside [ ], separated by commas. For
example,
#Python code to demonstrate the creation of a list
ages = [19, 26, 23]
print (ages)
# Output: [19, 26, 23]

A list can:
store elements of different types (integer, float, string, etc.)
store duplicate elements

# list with elements of different data types


list1 = [1, "Hello", 3.4]

# list with duplicate elements


list2 = [1, "Hello", 3.4, "Hello", 1]

# empty list
list3 = []

How to access an individual item from a list?


In Python, lists are ordered and each item in a list is associated with a number.
The number is known as list index. The index of the first element is 0, of the
second element is 1 and so on. For example,

languages = ["Python", "Swift", "C++"]

# access item at index 0


print (languages [0]) # will print Python

# access item at index 1


print (languages [1]) # will print Swift

# access item at index 2


print (languages [2]) # will print C++

51
In the above example, we have created a list named languages.

Here, we can see each list item is associated with the index number. And we
have used the index number to access the items.

Remember: The list index always starts with 0. Hence, the first element of a list is present at
index 0, not 1.

Negative Indexing in Python


Python allows negative indexing for its sequences. The index of -1 refers to the
last item, -2 to the second last item and so on. Let's see an example,

languages = ["Python", "Swift", "C++"]

# access item at last position


print (languages [-1]) # will print C++

# access item at second last position


print (languages [-2]) # will print Swift

Note: If the specified index does not exist in a list, Python throws the IndexError exception
(runtime error).

52
List Methods
Python has many useful list methods that makes it easy to work with lists.

Method Description

append () add an item to the end of the list

insert () inserts an item at the specified index

len () returns the number of items/ elements in the list

clear () removes all items from the list

sort () sort the list in ascending/descending order

The append () method


The append () method adds an item to the end of the list.
For example,

53
The insert () method
The insert () method inserts an element to the list at the specified index. It allows
you to modify the existing list by adding a new element at a specified position,
rather than creating a new list with the added element. For example,

The len () method


The len () method returns the number of items (length) in an object.
For example,

54
The clear () method
The clear () method removes all the items/elements from a list.
Syntax: [Link] ()
For example,

The sort () method


The sort () method sorts the list in the ascending order, by default.
Syntax: [Link] ()
For example,

55
The sort () method takes an optional parameter 'reverse', which sorts the list
into descending order when it is set to True.
[Link] (reverse = True)
For example,

56
Python Coding:
Iteration Constructs

57
Learning Objectives
• What are Iteration Constructs (Loops)?
• What are the components/ elements of an Iteration Construct (Loop)?
• How many types of Iteration Constructs (Loops) are there in Java?
o The for loop
o The while loop
• How does the for loop work?
• The for loop and the range () function

What are Iteration Constructs (Loops)?


• Iteration constructs are meant for repetition of one or more statements
depending upon a condition.
• Till the time a condition is True a set of statements are executed again and
again.
• As soon as the condition becomes False the repetition stops.
• The given flowchart below shows the basic for loop Flowchart.

58
What are the components/ elements of an Iteration Construct (Loop)?
• Initialization – To set the starting value of the counter/ control variable.
• Condition – To check for how long the loop will continue.
• Updation – To update (increase/ decrease) the value of the counter/
counter variable.
• Loop Body – The statements that get executed repeatedly till the test
condition is True.
Note: The counter/ control variable is the variable whose value determines how many times
the loop will get executed.

How many types of Iteration Constructs (Loops) are there?


Python offers two types of iterations constructs (loops), which are:
• the for loop and
• the while loop.

How does the for loop work?


• A Python for loop can be used to iterate over a list of items and perform
a set of actions on each item.
• The syntax of a for loop consists of assigning a temporary value to a
variable on each successive iteration.
• When writing a for loop, remember to properly indent each action,
otherwise an IndentationError will result.
Example 1:
dog_breeds = ["boxer", "bulldog", "shibainu"]
# Print each breed:
for breed in dog_breeds:
print (breed)

The for loop and the range () function


• The range () function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.
Example 2: To print numbers from 0 to 2
for i in range (3):
print (i)

59
Note: The counter variable in the above example starts at 0 and terminates before it
reaches the value given with the range () function.

Example 3: To print numbers from 3 to 5

for n in range (3, 6):


print (n)
Note: In the above example, the first parameter, i.e., 3 is included but the second
parameter, i.e., 6 is excluded.

Example 4: To print first ten even numbers

for x in range (2, 21, 2):


print (x)

60
Application
Development

61
Introduction
• Thunkable is a free platform to build iOS, Android, and web apps without
code.
• Before developing Thunkable, the founders developed App Inventor as
part of the MIT Media Lab. Then improved it to create Thunkable. If the
MIT Media Lab sounds familiar, they are the same folks who developed
Scratch.

How does Thunkable work?


• When using Thunkable, creators can design their user interface and how
their apps look by moving design features called components around a
simulated phone screen. Examples of components include buttons, text
boxes, images, and graphics. The possibilities are endless!
• Instead of typing computer instructions, Thunkable creators drag blocks
to program to instruct what the app should do when the user interacts
with the app. For example, a creator could move Thunkable blocks to
change some text on the screen when the user presses a button.
• Executing code once an action is performed is called event-driven
programming, a key concept in mobile app development.

How much does it cost to use Thunkable?


• Thunkable is free to use to create public projects. Public projects are
included in the Thunkable Public Gallery for anyone to preview and remix.
• You can create a maximum of 3 projects for free.
• Thunkable's free public accounts have a storage limit of 100MB. This
space is used to store project assets, such as images, audio files, and other
resources used within your apps.
• If you need more storage for your account, you can upgrade to Builder
plan to get 1 GB of space for your projects or to Advanced to get unlimited
space.
• Private projects are the projects, only you can access, but you will have to
upgrade your account by purchasing a membership.

What's a Component?
• Components are the building blocks of your Thunkable app. They can help
your app look a certain way or have a certain functionality.
• Components are organized into 10 different categories.
• UI Components (User Interface Components) are components which you
can see on the screen. Examples include buttons, loading icons, and
images.

62
• Each UI component has unique properties that you can use to customize
it. You can find this at the top of the Properties panel.
The commonly used components along with their properties and events are
listed below:

Button
A button is just something you can click on to perform an action. This action can
be anything from navigating to a different screen, saving information to a
database, or playing a sound. When you tap on the play icon to hear your
favourite music, you are using a button.

Properties of the Button Component

Property Value Description


Text Text Text displayed on the button
Text Color Color Color of the text displayed on the
button
Font Select from Font Font of the text displayed on the
menu button
Font Bold True/False True = button's text is bold
False = button's text is not bold
Font Italic True/False True = button's text is italic.
False = button's text is not italic.
Font Size Number Font size of the text on the button
Disabled True/False True = button is disabled for the user
by default
False = button is enabled for the user
by default
X Coordinate value Position of the upper left corner of the
button on the X-axis, where the left
side of the screen is X = 0
Y Coordinate value Position of the upper left corner of the
button on the Y-axis, where the top of
the screen is Y = 0
Height Number in pixels Button’s height
Width Number in pixels Button’s width

63
Property Value Description
Resize Mode Stretch Stretches the button to fit the
dimensions of the device's screen
Resize Mode Float in Place Renders the button in the same aspect
ratio as the design, regardless of the
device size
Visible Visible Users can see the button
Visible Invisible Users cannot see the button
Background Color Color The background color of the button
Border: Style Solid The button's border is a solid line.
Border: Style Dashed The button's border is a dashed line.
Border: Style Dotted The button's border is a dotted line.
Border: Color Color The button's border is the color
selected
Border: Width Number in pixels The width of the button's border is
defined by a custom number of pixels.
Border: Radius Number in pixels The radius of the button border’s
corners is defined by a custom
number of pixels.

Events of the Button Component

This event fires when a user taps (or


clicks) the button.

This event fires when a user presses


and holds the button for an extended
period.
This event fires when a user initially
touches the button.

This event fires when a user lifts their


finger (or stylus) off the screen or
releases the press on the button.

64
Label
The label component is used to display read-only text and can be made clickable
using blocks. Labels work alongside other user interface components like
buttons, images, and text inputs to create a cohesive and intuitive user
experience.

Properties of the Label Component

Property Value Description


Text Text Text that appears on the label
Font Select from Font Font of the text displayed on the label
menu
Color Color Color of the text that appears on the
label
Font Weight True/False Make the label's text bold
Font Style True/False Make the label's text italicized
Underline True/False Underline the label's text
Strikethrough True/False Apply strikethrough formatting to the
label's text. You can further select the
strikethrough's color and style.
Text Align Select from menu Set alignment of the text relative to
the label's outline
Font Size Number Font size of the text on the label
Number of Lines Number Maximum number of lines of text that
your label will display

X Coordinate value Position of the upper left corner of the


label on the X-axis, where the left side
of the screen is X = 0
Y Coordinate value Position of the upper left corner of the
label on the Y-axis, where the top of
the screen is Y = 0
Height Number in pixels Label’s height
Width Number in pixels Label’s width
Resize Mode Stretch Stretches the label to fit the
dimensions of the device's screen

65
Property Value Description
Resize Mode Float in Place Renders the label in the same aspect
ratio as the design, regardless of the
device size
Visible Visible Users can see the label
Visible Invisible Users cannot see the label
Background Color Color The background color of the label
Border: Style solid The label's border is a solid line.
Border: Style Dashed The label's border is a dashed line.
Border: Style Dotted The label's border is a dotted line.
Border: Color Color The label's border is the color
selected.
Border: Width Number in pixels The width of the label's border is
defined by a custom number of pixels.
Border: Radius Number in pixels The radius of the label border’s
corners is defined by a custom
number of pixels.

Events of the Label Component

This event will fire when the user clicks on the


label.

Text Input
The text input component is a field where app users can enter text, such as a
name or email address.

Properties of the Text Input Component

Property Value Description


Hint Text The prompt text the
user sees when the text
input is empty (e.g. Type
Email).

66
Property Value Description
Text Text Populated text of the
text input
Secure Text Entry True/False Toggle whether the
input text is obscured as
a user types (suitable for
entering passwords and
other sensitive
information)
Editable True/False Toggle whether the user
can edit the text
Multiline True/False Toggle whether the user
can enter multiple lines
of text
Auto Focus True/False Toggle whether the text
input field is
automatically in focus
when the screen opens
(i.e. the user doesn't
need to tap into the field
to focus)
Max Length (Android Number Set the maximum
and iOS only) number of lines of text
your user can enter
Input Color Color The color of the text
input's text
Background Color Color The background color of
the text input field
X Coordinate value Position of the upper left
corner of the text input
on the X-axis, where the
left side of the screen is
X=0
Y Coordinate value Position of the upper left
corner of the text input
on the Y-axis, where the
top of the screen is Y = 0

67
Property Value Description
Height Number in pixels Text input’s height
Width Number in pixels Text input’s width
Resize Mode Stretch Stretches the text input
to fit the dimensions of
the device's screen
Resize Mode Float in Place Renders the text input in
the same aspect ratio as
the design, regardless of
the device size.
Visible True/False Toggle whether users
can see the text input
Border Style select from list [solid, Style of text input's
dotted, dashed] border
Border Color Color Color of text input's
border
Border Width Number in pixels The width of the text
input's border is defined
by a custom number of
pixels.
Border Radius Number in pixels The radius of the text
input's border’s corners
is defined by a custom
number of pixels.

68
Events of the Text Input Component

This event fires when the user clicks on the


text input component.

This event fires whenever a character is


added to or removed from the text input
(i.e. whenever there is a change to the
content of the text input).
This event fires when the component loses
focus, i.e. the user clicks on another
component.
This event fires when the submit button is
clicked or enter key is pressed on the
device keyboard.

Credits:
[Link]
[Link]
[Link]
[Link]
[Link]

69

You might also like