Unit 2: Coding
Learning Objectives
Learners will learn to:
develop text-based programs that use input and output
use variables in text-based programs
identify and describe data types in text-based programs
identify and describe data types in text-based programs, including Integer,
Real (floating point) and String.
develop text-based programs using data types, including Integer, Real
(Floating point), and String
develop text-based programs that use different arithmetic operators,
including +, −, *, /
understand how errors can be introduced into programs
systematically identify and debug errors in text-based programs
Vocabulary
source code
python shell
variable
data type
Let Us Start
Hey! I am aware that Python Not at all! Python is known for its
programming can be used to simplicity and readability. It has a
develop a wide range of simple syntax, which makes it easy to
applications. Is it difficult to get understand and write code. It's a high‐
started with Python level programming language, meaning
programming? you don't have to worry about low‐
level details like memory management.
This makes it great for beginners and
experienced programmers alike.
1
Let Us Explore
We know that a computer programmer creates code to develop specialised and
customised software using high-level programming languages. This software is used
in restaurants, movie theatres, and hospitals. They use customised software to
manage patient details, prepare bills, assign seats, etc.
Make a list of some programming languages that you have used earlier or that you
are aware of.
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
Get, Set, Go
2.1 What is Python?
Python is a popular high-level programming language. It was created by Guido van
Rossum and released in 1991. It was mainly developed to emphasise code readability
and its syntax allows programmers to express concepts in fewer lines of code. It is
used for:
web development (server-side)
software development
mathematics
system scripting
Features of Python programming language
Python works on different platforms such as Windows, Mac, Linux, Raspberry
Pi, etc.
Python has a simple syntax similar to the English language.
2
Python has a syntax that allows developers to write programs with fewer lines
than some other programming languages.
Python is freely downloaded from the internet. It is an open-source language,
which means that its source code is freely available for modification by
anybody.
Python runs on an interpreter system, meaning that code can be executed as
soon as it is written.
IDLE for Python
To create a program in Python, you need to type Python commands in a text editor,
such as Notepad or Notepad++. However, with a text editor, you will need to use
other tools to run or execute the program. To avoid this, you can use an Integrated
Development Environment (IDE).
An IDE enables you to create, test and execute programs within the same
environment. There are many different types of IDEs. One example of an IDE for
Python is the Integrated Development and Learning Environment known as IDLE. It
comes with many useful features, such as syntax highlighting and autocomplete,
making writing and reading Python code easier. Python IDLE also includes a
debugger, which allows you to execute your code line by line to find and fix errors.
Tech Tickler
PyCharm, Vim, and Emacs are examples of a few other IDEs, that you can use
for creating, editing, and executing Python programs.
Downloading and installing Python IDLE
Integrated Development and Learning Environment (IDLE) is used to execute
individual instructions of Python. You can also use it to create, edit and execute
programs containing multiple instructions.
3
Steps to download and install Python IDLE
1. To download the setup file, open the web page.
https://www.Python.org/downloads/ in your browser.
2. Click the ‘Download Python’ option.
3. Scroll down and select the version to be downloaded based on your
computer’s operating system. Here Windows installer (64-bit) is selected. This
will download the setup file to the local drive of your computer.
4. Click on the downloaded file. The Python Setup window is displayed.
5. Check both checkboxes at the bottom of the dialogue box. Then, click the
Install Now option. The process of installing IDLE will start in the system.
6. Once the installation is successful, a 'Setup was successful' message is
displayed. Click the Close button. IDLE is now ready to use.
4
Using the Python
To open Python IDLE, click the icon from the Start menu. When you first start
IDLE, the Python shell is displayed as shown.
In the Python programming language, there are two ways in which we can run our
code:
Interactive mode
Script mode
Interactive mode
In the screenshot, the blinking line is the cursor. This is where you type Python
commands and get the command output immediately in the next line. This is called
the interactive mode of the shell.
An example of a command and its output is shown in the given image.
The interactive mode is useful for typing a few lines of instructions or commands.
However, it cannot create a program with multiple commands.
Script mode
In the script mode, a Python program can be written in a file. This file can then be
saved and executed using the command prompt. We can view the code at any time
5
by opening the file and editing becomes quite easy as we can open and view the
entire code as many times as we want.
Script mode is very suitable for writing long pieces of code. It is much preferred over
the interactive mode by experts in the program. The file made in the script mode is,
by default, saved in the Python installation folder and the extension to save a Python
file is “.py”.
Creating and executing a program
You can type a new program in IDLE by selecting the New File option from the File
menu. Type the program and save the file with an extension “.py”. IDLE uses different
colour codes to show different types of text: the print command is in purple, the
string in green and the output in blue.
Steps to create a Python program
Step 1: Open the Python shell
Step 2: Click the New File option from the File menu of the shell.
Step 3: A new window opens up on the screen. You can type the commands of a
program here.
6
The given program contains instructions to print text.
Steps to save a Python program
Step 1: Click the File menu and select the Save or Save As option.
Step 2: Select the folder where you want to save the file.
Step 3: Type a file name. Make sure the file type is selected as Python files. The file
gets saved with a .py extension.
Step 4: Click the Save button.
7
Steps to execute a Python program
Step 1: Once you have saved a program, select the Run Module option from the Run
menu to execute the program.
Step 2: The script is executed and the output of the script is displayed in the Python
Shell.
Typing commands in Python
The print() command
The print() command is used to display a value on the screen. It can be used to
display text or numbers. The value to be displayed is given inside the round brackets.
Text in Python is also called string and refers to a sequence of letters or characters. It
is generally enclosed in single or double quotes. If a number is enclosed in quotes, it
is considered as a string. So, a number should not be enclosed in quotes if it has to
be used for calculations.
Example 1: Display a string
command
output
Example 2: Display a number
command
output
8
Comments
A Python command can include comments to help someone else understand your
code. The Python interpreter ignores them. Comments start with a ‘#’. Comments can
be used to
to explain a part of the Python code
to make the code more readable
to prevent the execution of some code while testing
Activity 1
Perform the following tasks.
Task 1: Open Python IDLE on your computer.
Task 2: Write a command to display the following text in the interactive mode.
Text= “Learning to use Python programming language!”
Task 3: Use the script mode to create and save a program for Task 2.
Task 3: Remove the quotes from the text to be printed and run the program once
again. Observe the output.
2.2 Variables
A variable is a named storage area in the computer memory used to store a value.
You can change the value of data stored in this area, but the variable's name will
remain the same. Every variable must be named. The name given should be
meaningful so that you can remember what the variable is used for in the program.
For example, a variable called score can be used to store the score in a game and a
variable called answer can be used to store the answer selected by the user.
9
Rules for creating Python variables
A variable name can contain an alphabet, numeric digit and underscores (A-Z,
0-9 or _).
A variable name should start with either a letter or an underscore. It cannot
start with a numeric digit.
Variable names are case-sensitive. A variable in lowercase is different from the
same variable in uppercase. For example, score, Score and SCORE are three
different variables.
2.3 Data types
Every variable in Python has a data type. The data type determines the type of data
that the variable can store and what kind of operations can be performed on that
particular data. Python decides a variable’s data type by the value assigned to it. The
basic data types available in Python are as follows.
Data type Description and examples Examples
Integers It contains whole numbers or integers. -15, 26, 0, -35, 763
‘int’ They can be positive, negative or zero.
Floating Point It contains a number with a decimal point. 56.8, -45.0, 23.6671,
‘float’ It can be positive, negative or zero. 0.314
Character It contains a single character or symbol. If A, z, $, 6
‘char’ it holds a digit, it cannot be used in
calculations.
String It contains a string. A string is a collection “Yes”, “123”, ‘A’, ‘I
‘str’ of one or more characters enclosed in like Python
single quotes or double quotes. programming’.
Boolean It contains logical values. It can only have ‘True’, ‘False’
‘bool’ True or False values.
10
Assigning values to variables
To define a variable, you must give it a value using the ‘=’ sign. This is called
assigning a value to a variable. Python allows assigning value to a single variable or
to multiple variables at the same time.
For example,
score=0 will store the number 0 in the score variable
answer=’R’ will store the character ‘R’ in the answer variable
percentage = 78.56 will store 78.56 in the percentage variable
a, b, c= “Rose”, “Marigold”, “Lotus” will store ‘Rose’ in the ‘a’ variable, ‘Marigold’
in the ‘b’ variable, and ‘Lotus’ in the ‘c’ variable.
Accepting values from a user
A program also needs to take some input from a user. This can be done using the
input() command. The following command assigns the input typed by the user into
the variable x.
x= input()
You can also add a message informing the user what they should type in. This
message is called the prompt.
Program
11
Output
Activity 2
Write a line of code that asks the user to input their age. Store this value in a variable
and display the age along with a message.
2.4 Operators
Often, you will need to perform calculations in a program. Python offers a wide range
of operators that allow you to perform complex calculations.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations on numbers.
Python provides the following arithmetic operators.
Operator Name of Description Example
Symbol operator Assuming x=20 and
y=10
+ addition Adds two values and gives the x+y results in 30
sum
- subtraction Subtracts the second value from x-y results in 10
the first value and gives the y-x results in -10
difference
* multiplication Multiplies two values and gives x*y results in 200
the product
/ division Divides the first value by the x/y results in 2
second value and give the
quotient
% modulus Divides the first value by the x%y results in 0
second and give the remainder
12
Example 1: A program that uses arithmetic operators on two variables and displays
the results.
Program
Output
Example 2: A program that takes input from the user and multiplies the numbers
and then displays the result.
Program
13
Output
Activity 3
Create an Addition program in Python that takes two numbers entered by the user. It
then adds them together and outputs the result
2.5 Errors
A Python command will not execute if there is an error in its syntax; instead, it will
display an error message with a description of the error, as shown in the following
screen. An error occurs when you do not follow the rules for typing Python
commands.
For example, a command defined in a small case cannot be typed in the upper case.
‘P’ in
uppercase
Error
In the example shown, the ‘print’ command is typed with the letter ‘P’ in uppercase,
which results in an error. Other errors could also be a missing bracket or a spelling
mistake. When there is an error, you need to correct the same and execute the script
once again.
Steps for checking and correcting errors
Click the Run menu and select the Check Module option.
In the following program, the check module shows the line with the error. The
ending quote is not given here, so the program shows an error.
14
After using the Check Module command, you can open the file using the Open
option from the File menu and make changes to the file. Save the changes using the
Save option, and execute the script again.
Tech Tickler
You can also use shortcut keys for the various actions as given below.
• Create a new program: Ctrl+N
• Open a saved program: Ctrl+O
• Save a program: Ctrl+S
• Save a program with another name: Ctrl+Shift+S
• Run a program: F5
Unit Review
1. Python is a popular high-level programming language. It was created by
Guido van Rossum and released in 1991.
2. To create a program in Python, you need to type Python commands
Integrated Development Environment (IDE).
3. An IDE enables you to create, test and execute programs within the same
environment.
4. The mode where you type Python commands and get the command output
immediately in the following line is called the interactive mode of the shell.
15
5. In the script mode, a Python program can be written in a file. This file can then
be saved and executed using the command prompt.
6. To save the program in Python, use the file with an extension “.py”.
7. Select the Run Module option from the Run menu to execute the program.
8. The print() command is used to display a value on the screen.
9. A Python command can include comments to help someone else understand
your code. The Python interpreter ignores them. Comments start with a ‘#’.
10. A variable is a named storage area in the computer memory used to store a
value.
11. The data type determines the type of data that the variable can store and
what kind of operations can be performed on that particular data.
12. Data types used in Python are integers, float, character, string and boolean.
13. To define a variable, you must give it a value using the ‘=’ sign. This is called
assigning a value to a variable.
14. The input() command takes some input from a user.
15. Arithmetic operators such as +, -, * and / are used to perform mathematical
operations on numbers.
16. An error occurs in Python when you do not follow the rules for typing Python
commands.
17. To check for the errors, click the Run menu and select the Check Module
option.
Check for Understanding
1. Select the correct answer.
a. Which of the following statements are true regarding creating a variable in
Python?
i. A variable name cannot contain an alphabet and numeric digit.
ii. A variable name should start with a numeric digit.
iii. Variable names are not case-sensitive.
16
b. What will an Integrated Development Environment (IDE) enable you to do?
i. Create a program
ii. Execute a program
iii. Both a. and b.
c. Which of the following is used to assign value to a variable?
i. +
ii. /
iii. =
d. Which of the following is used to add a comment in a Python program?
i. #
ii. $
iii. %
2. Answer the following questions.
a. Write down any three features of the Python programming language.
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
b. Differentiate between interactive mode and Script mode in Python
Programming.
____________________________________________________________________________________
____________________________________________________________________________________
___________________________________________________________________________________
17
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
___________________________________________________________________________________
c. Explain variables. Write the Python code to create a variable called z.
Assign x + y to it and display the result.
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
d. Identify the errors in the following program. Rewrite the program correctly.
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
_______________________________________________________________________________
______________________________________________________________________________
18
Lab Activity
Q1. Create a Python program using the following instructions.
a. Accept the student’s name, exam name and the percentage marks obtained,
b. assign the user input to respective variables,
c. and display the user input along with proper messages.
Q2. Create a Python program using the following instructions.
a. Accept the name, subject and marks of a student in 3 subjects out of 50
b. Calculate and display the total marks and percentage scored by the
student
Resources
https://www.javatpoint.com/python-tutorial
Reference Material
https://www.programiz.com/python-programming/first-program
19