Variable in Real Life
The process of creating a variable and assigning a value to variable is called
Initialization
Variables in Programming
Variables must be initialized with a value before they are used
A variable that is not initialized has an undefined value and cannot be used
until it is assigned a value
In Python, a variable is created the moment you first assign a value to it
Python Variable Naming Rules
Variable names must start with a letter (a-z, A-Z) or an underscore (_)
The rest of the name can contain letters, digits (0-9), or underscores
Variable names are case-sensitive
Reserved words (keywords) cannot be used as variable names
Data Types in Programming
Programming languages offer a wide variety of data types to suit the
programmers’ needs
In Python, some basic data types are: Integer, Floating-Point Number, String,
and Boolean
Integer
Integer is a data type used to define integer variables
Integers can be 7-8 digits and can be any positive or negative whole number
Floating-Point Number
A floating-point number in Python is used to define decimal numbers and is
accurate up to 15 decimals places
String
A string in Python is a sequence of Unicode characters
It is used to define any form of strings ex. Text, Alphanumeric etc.
In Python, we can use single quotes, double quotes or triple quotes to define
strings. Multi-line strings in Python can be represented using triple quotes
Boolean
Boolean data in Python is used to define Boolean variables
Boolean variables can hold only two values in it, either “true” or “false”
Validating User Input
Validating user input is important to make sure the program works fine
Whenever a specific data type is expected, validation should be done to make
sure the user enters the right type of value
A common way of validating user input is by flagging out the wrong input
Mathematical Operations in Programming
There are five mathematical operations that can be performed on variables in
programming: addition, subtraction, multiplication, division, and modulus
Addition operation is performed using the "+" symbol and can be carried out
on Integer, Float, Double, and String datatypes. It is used to perform
mathematical addition of two variables or to concatenate two strings
Subtraction operation is performed using the "-" symbol and can be carried
out on Integer, Float, and Double datatypes. It is used to perform
mathematical subtraction of two variables
Multiplication operation is performed using the "\*" symbol and can be carried
out on Integer, Float, and Double datatypes. It is used to perform
mathematical multiplication of two variables
Division operation is performed using the "/" symbol and can be carried out on
Integer, Float, and Double datatypes. It is used to perform mathematical
division of two variables
Modulus operation is performed using the "%" symbol and can be carried out
on Integer, Float, and Double datatypes. It is used to find the remainder of the
division of two variables
Important Note:
In some programming languages like Python, there is no command to declare
variables. A variable is created the moment you first assign a value to it.
Integer and Float datatypes in Python
An integer is a whole number, positive or negative, without decimals, of
unlimited length.
A float is a number with a decimal point.
Modulus Operator %
It is used to perform mathematical remainder of two variables.
It divides the variable on the left by the variable on the right and returns the
remainder.
It can be used with both integer and float datatypes.
Sequencing with Block
Coding
Repetition in programming
In programming, repetition of a line or a block of code is also known as
iteration
A loop is an algorithm which executes a block of code multiple times till the
time a specified condition is met
Break and continue statements
The break statement modifies the normal flow of execution while it terminates
the existing loop and continues execution of the statement following that loop
Whenever a program encounters a continue statement, the control skips the
execution of remaining statements inside the loop for the current iteration
and jumps to the beginning of the loop for the next iteration
Nested loops
When there is a loop inside another loop, it is called a nested loop
Sequencing in algorithms
An algorithm is a detailed step-by-step process that needs to be followed in
order to complete a task or to solve a problem
There are three basic building blocks that can be used when designing
algorithms: sequencing, selection, and iteration
Sequencing refers to the specific order in which we need to perform the
activities in order to get the desired output
Sequence
A sequence is a list of activities that are done one after another
In programming, tasks also need to be done in the correct sequence to get
the desired output.
Skipping or altering the sequence of steps in a program can lead to errors or
incorrect output.
An algorithm to swap two numbers must be followed step by step in sequence
to achieve the desired output.
Skipping or altering the sequence of steps in the algorithm can lead to errors
or incorrect output.
Selection
An algorithm can use selection to choose a specific flow based on a condition.
For example, an algorithm can check if a number is above or below a certain
value and choose a specific flow based on that condition.
Iteration
An algorithm can use iteration to repeat a specific flow based on a condition.
For example, an algorithm can print all the natural numbers from 1 to 100 by
repeating the flow for each number.
Bug
A bug is a term used to describe any unexpected problem in a program
It is any deviation in the expected and actual output of the program
Consequences of a bug
A bug can cause unexpected behavior in a program
It can lead to errors, crashes, or security vulnerabilities
Importance of bug detection and removal
Finding and fixing bugs is a crucial part of the software development process
It ensures that the program functions as intended and meets the needs of the
users
Loops
While Loop: A While Loop can execute a set of commands till the condition
is true. It is also called a conditional loop. Once the condition is met, the loop
is finished.
For Loop: A For Loop is needed for iterating over a sequence. It executes
for a specific number of times.
Nested Loops: A loop inside another loop is called a nested loop. There is
no restriction on how many loops can be nested inside a loop. This is helpful
while working with requirements where the user wants to work with multiple
conditions simultaneously.
Applying Loops and Conditionals with Sequencing
Selection: The algorithm needs to make a choice between two or more
alternatives. It is like asking questions like “Is it raining?”. If the answer to the
question is true, the algorithm follows one path. If the answer is false, the
algorithm follows a different path.
Iteration: The process of doing the same task over and repeatedly, until a
certain task is complete, or a certain condition is met. The iteration can also
be set to run for a specific number of times. For example, think of a race in
which a car must go around a track five times. The car will keep going around
the track repeatedly until it completes five laps. Once that is done, it will exit
the track.
Combining all the three building blocks of algorithms: Sequencing, selection, and
iteration. Loops and conditionals can be used to reduce the number of steps of the
sequence by using a loop along with certain conditions to check when the loop should
stop
Fun with Functions
Function
A function is a block of code made up of a set of steps that results in a single
specific action
It is given a simple name for easy reference and reuse in a program
Benefits
Increases reusability of code
Improves code readability and organization
Defining and calling a function
To define a function, a programmer specifies its name, input parameters (if
any), and the code to be executed
To call a function, the programmer simply uses its name and provides any
necessary input arguments
Function parameters
Input parameters allow a function to accept and use different data in each call
They are defined when the function is created and specified when it is called
Types of values returned by a function
A function can return a single value, multiple values, or no value at all
The type of value returned depends on the function's purpose and
implementation
Understanding Python Functions
A function is a named code block that performs a job or returns a value
Functions are used to divide a large program into smaller and more
manageable parts
They are used to perform a task multiple times in a program without having to
copy the same code all over the place
The `print()` function is an example of a built-in function in Python
Defining a Python Function
A function has two main parts: a function definition and body
Function definition starts with the `def` keyword and the name of the function
Function body: all the indented lines that follow the function definition
The text string surrounded by triple quotes is called a docstring. It describes
what the function does
Calling a Function
A function call instructs Python to execute the code inside the function
To call a function, you write the function’s name, followed by the information
that the function needs in parentheses
The value that you pass into a function is called an argument
Passing Information to Python Functions
When you add a parameter to the function definition, you can use it as a
variable inside the function body
The name is called a function parameter or simply a parameter
The value that you pass into a function is called an argument
Parameters and arguments are not the same thing. Parameters are
placeholders for the values that you pass into a function, while arguments are
the actual values that you pass in
Understanding Functions in Python
A function is a reusable named block of code that performs a task or returns a
value
Use the def keyword to define a new function
A function consists of function definition and body
A function can have zero or more parameters
If a function has one or more parameters, you need to pass the same number
of arguments into it
A function can perform a job or return a value. Use the return statement to
return a value from a function
Parameters and Arguments
A parameter is a piece of information that a function needs
An argument is a piece of data that you pass into the function
For example, the greet() function has a parameter called name and the
argument is the text string 'John' or the variable jane
Returning a value
A function can return a value. The value that a function returns is called a
return value
Use the return statement inside the function body to return a value from a
function
Example of a function with multiple parameters
The following example defines a function called sum() that calculates the sum
of two numbers
When a function has multiple parameters, you need to use a comma to
separate them
When you call the function, you need to pass all the arguments
Reducing redundancy using Functions
A function in code is used to keep the code DRY (Don't Repeat Yourself)
It helps to minimize errors, keep code short, and save programming time
Advantages of using Functions
Increases readability and makes code organized and easy to understand
Reduces code length by removing redundant code and replacing it with
functions
Increases code reusability
Function Parameters
Variables accepted by a function to perform the set of tasks defined in its
body are called function parameters
For example, in calculating the area of a circle, the radius is the function
parameter and in calculating the area of a rectangle, the length and breadth
are the function parameters
Event
An event is something that happens
In the context of coding, events are a generalization of all the things that the
program can respond to
Event Handlers
An event handler is a piece of code associated with an event in the code
An event handler gets executed when that event occurs
Example: In Make Code platform, "on player walk" block is an event handler.
Agent mode forward is the action that occurs with this event.
Understanding Arrays
and Collections
Python Arrays
Python arrays are a fundamental data structure that can store more than one
item at the same time
They are an ordered collection of elements with every value being of the
same data type
They are a thin wrapper over C arrays and are useful when working with
homogeneous data
They are more compact and take up less memory and space compared to lists
Comparison between Python Lists and Python Arrays
Both lists and arrays are an ordered sequence of elements
Lists can store items of various data types, while arrays can only store items
of the same single data type
Lists are built into the Python programming language, whereas arrays aren't
and need to be imported via the array module
When to use Python Arrays
Use arrays when you want to work with homogeneous data
Use arrays when you want to perform mathematical calculations with the
NumPy package
Use lists when you want more flexibility as they can store items of various
data types
How to use Arrays in Python
Import the array module to create Python arrays
Create an array using the array() constructor
Define an array using the general syntax: variable\_name = array(typecode,
[elements])
Typecode table
The typecode specifies what kind of elements will be stored in the array
For example, 'i' is for integers, 'f' is for floats, and 'd' is for doubles
Defining Python arrays
Python arrays are defined using the array module
The array module is imported as Arr()
An array is created using [Link]([])
The first argument in the array([Data]) constructor is the typecode, which
specifies the type of data the array can hold
The second argument is a list of values to be stored in the array
Length of an array can be found using the built-in len() method
print(len(numbers)) will print the length of the array
Accessing individual items in an array
Individual items in an array are accessed using their index number
Indexing starts at 0
print(numbers[0]) will print the first element in the array
Negative indexing can also be used, with the last element having an index of -
1
How to Search Through an Array in Python
You can find out an element's index number by using the index() method.
The index() method returns the index number of the first instance of the value
being searched.
Methods For Performing Operations on Arrays in
Python
Arrays are mutable, which means they are changeable.
How to Add a New Value to an Array
To add one single value at the end of an array, use the append() method.
Note:
Be aware that the new item you add needs to be the same data type as the
rest of the items in the array.
Error Handling:
If you try to add a float to an array of integers, it will raise an error.
Adding multiple values to an array in Python
To add multiple values to the end of an array, use the extend() method
The extend() method takes an iterable (such as a list of items) as an
argument
Make sure that the new items are all the same data type
Adding a value to a specific position in an array
Use the insert() method to add an item at a specific position
The insert() function takes two arguments: the index number of the position
the new element will be inserted, and the value of the new element
Removing a value from an array
To remove an element from an array, use the remove() method and include
the value as an argument to the method
With remove(), only the first instance of the value you pass as an argument
will be removed
Use the pop() method to remove an element from a specific position
The pop() method takes the index number of the element to be removed as
an argument
Iterating over Collections
Collections consist of lists, sets, or maps
Iterators are used to access collections in a sequential manner
Modifying a collection's elements while iterating through that collection is not
allowed
To add elements while iterating a list, set, or map, keep the new elements in a
temporary list, set, or map and add them to the original after finishing
iterating the collection
To remove elements from a list, create a new list and insert the elements you
wish to keep or add the elements you wish to remove to a different list and
remove them after finishing iterating the collection
Modifying Collections
Not every collection can be modified
"Unmodifiable" collections do not support modification operations such as
add, remove and clear
"Immutable" collections guarantee that no change in the Collection object will
be visible
"Fixed size" lists assure that their size remains constant even though the
elements can change
It is not possible to iterate or modify a Collection that is null
Adding and Removing Elements During Iteration
To add elements while iterating a list, set, or map, keep the new elements in a
temporary list, set, or map and add them to the original after finishing
iterating the collection
To remove elements from a list, create a new list and insert the elements you
wish to keep or add the elements you wish to remove to a different list and
remove them after finishing iterating the collection
Collections
A collection is a container that groups multiple items into a single object
Used to store data
Data can be retrieved and manipulated from Collections
Advantages of using Collections
Allows programmers to group multiple items into a common set
Grouping of items makes it easier to identify and perform different operations
on them like retrieving and modifying data
Increases the performance of the program
Increases productivity and reduces operational time
Extra
The second way is to use the Power Operator. Represented or used as **
in Python.