0% found this document useful (0 votes)
2 views47 pages

Unit 3 Programming

This document outlines a programming unit focused on Python, covering the basics of programming, types of programming languages, and the significance of Python as a powerful learning tool. It includes lessons on programming fundamentals, execution methods (compilers and interpreters), debugging processes, and popular programming languages. The document also provides practical guidance on installing Python and writing simple programs using IDLE.

Uploaded by

zackjamac63
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)
2 views47 pages

Unit 3 Programming

This document outlines a programming unit focused on Python, covering the basics of programming, types of programming languages, and the significance of Python as a powerful learning tool. It includes lessons on programming fundamentals, execution methods (compilers and interpreters), debugging processes, and popular programming languages. The document also provides practical guidance on installing Python and writing simple programs using IDLE.

Uploaded by

zackjamac63
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

UNIT3:PROGRAMMING

Unit objectives:
At the end of this unit, the learner should
be able to:
1. Discuss the basics of programming.
2. Identify the different types of programming
languages.
3. Explain why a python is a power programming
language for learning.
4. Learn core python scripting elements
5. Demonstrate the ability to solve problem
using python
Lesson
1 BASICS OF PROGRAMMING
Learning Objectives
At the end of the lesson, the learner should be able to:
1. Define programming
2. Identify the types of programming languages.(High-level languages and low-level languages)
3. Demonstrate how programs are executed using compilers and interprets.
4. Explain the work of IDE(Integrated Development Environment) and its tools.
5. Define what is a debugging.
6. List and identify the different kinds of errors occur in programming.
7. List and identify the most popular programming languages.
8. Explain why a python is a power programming language for learning.
Lesson
1.1 What is a programming?
❖ As you have already learned, the Software rules the hardware(physical machine) and it
determines what any computer can do. Without software, computers would just be expensive
paperweights.
❖ The process of creating software is called Programming.
❖ A program is a step-by-step set of instructions telling a computer exactly what to do.

Programming Languages
❖ Computer scientists developed notations for expressing computations in an exact and
unambiguous way. These special notations are called programming languages.
❖ Every structure in a programming language has a precise form(its Syntax) and specific
meaning(its semantics).
❖ A programming language is a code for writing down to tell the computer the instructions it
will follow.
❖ In fact, programmers often define their programs as to a computer code, and the process of
writing an algorithm in a programming language is referred to as Coding.
Lesson
1 Continue..
➢ There are many different types of programming [Link] the all have the ability to:
• Input data from external input device such as a keyboard.
• Output data to external output device such as a screen.
• Process decisions according to certain conditions being met.
• Process calculations like arithmetic operations such addition and subtraction.
• Process repetition for a certain number of times while a condition is met, or until a condition
is met.
➢ Languages are defined as human-readable(high-level languages) or machine-readable(low-
level languages).
➢ In high-level languages, the instructions are encoded in a language that humans can use and
understand, While
➢ In low-level languages, the instructions are in a language that computers understand, and are
in binary code.
Lesson
1 Continue..
❖ Computers only have the ability to run programs written in low-level languages. Thus,
programs written in a high-level language have to be processed before they are executed.
❖ high-level languages are portable, meaning that they can be run on different types of
operating systems with few or no modifications. Low-level programs can only run on one
kind of machine and it requires to be rewritten to execute on another machine.
❖ Two types of programs are used to process high-level languages into Low-level languages:
[Link] Interpreter; This translates the code into machine code, instruction by instruction,
the machine executes each instruction before the interpreter moves on to the next instruction.
Interpreted code will display an error as soon as it hits a problem, so it easier to debug errors
than compiled code. However, it is slower to execute.
2.A Compiler-this translates the entire program into machine code before the program is
[Link] can be difficult to test single lines of compiled code,as all bugs are reported after
the entire program has been compiled. The compilation process is slow, but the machine code
can be executed quickly.
Lesson
1 Continue..
❖ The difference between interpreting and compiling is that compiling is one-time translation.
Once program is compiled, it may be run over and over without further need for the
compiler or the source code.
❖ Interpreter case, the interpreter and the source code are needed every time the program
runs.
❖ Compiled programs are faster than interpreted programs, since the translation is done once
for all the source code, but interpreted programs have a more flexible programming
environment as a programs can be developed and executed interactively.
How compiler works

Source code Compiler Machine code Output


Lesson
1Continue..
How interpreter works

Source code Interpreter Output

❖ In order to execute programs,they may have to be compiled or interpreted. An


IDE(Integrated development environment) is used to write code,test for errors and
compile or interpret a program.
❖ IDE(Integrated development environment) is an application used to create [Link]
IDE can often support different languages.
❖ IDE have a number of different tools and functions that assist a developer in the creation
of program, the common tools of IDE are:
1. Code editor: the code editor is a text edit area that allows developers to write,edit and
save a document of code. It has features that assist with the writing and editing of code
such as auto-completion and syntax checking.
Lesson
1 Continue..
[Link]:This translates the high-level language into the machine language by compiling
or interpreting.
[Link]:this is a program with in the IDE that is used to detect errors. If the program has
errors, the debugger may suggest what the type of error is and what line it is on.
Lesson
1.2 What is debugging?
1

❖ Programming is a complex process; it often leads to errors. The programming errors are
called bugs and the process of tracking them down and correcting them is called
debugging.
❖ Three types of errors can occur in a program:
1) Syntax errors
2) Runtime errors
3) Semantic errors
❖ It is useful to differentiate between them in order to track them down more easily.

Syntax errors
❖ The programs can only be executed if the program is syntactically correct, otherwise, the
process fails and returns an error message.
❖ Syntax is the structure of a specific program and the rules about that structure.
Lesson
1 Continue..
❖ For most programmers, a few syntax errors are a problem because program is not so
forgiving. If there is a single syntax error anywhere in your program, you will get an error
message, and you will not be able to run your program.
❖ During the first weeks of your programming journey, you will probably spend a lot of time
tracking down syntax errors.
❖ As you gain experience, though, you will make rarer errors and find them more quickly.

Runtime errors
❖ The second kind of error is a runtime error, so called because the error does not appear
until you execute the program. These errors are also referred as exceptions because they
usually specify that something exceptional (and bad)has happened.
❖ Runtime errors are rare in the simple programs, so it might be a while before you
encounter one.
Lesson
1 Semantic errors
❖ The third type of error is the semantic error or logical error.
❖ If there is logical error in your code, it will execute successfully and the computer will not
generate any error messages, but it will not do the right [Link] will do something else.
Specifically, it will do what exactly you instruct it to do but it will not do what you expect it to
do; because the program you wrote is not the program you expect to write.
❖ The Semantics of the program(its meaning) is wrong. Identifying logical errors can be
complicated and tricky because it requires you to work backward by checking the output of
the program and trying to figure out what it has gone wrong.
Lesson
1 Debugging
❖ Debugging is the process of working through the program in a systematic way to eliminate
any errors or bugs. Mostly, a debugger program is included within the IDE.

Stepping
❖ Stepping is a process of debugging which executes one line of code at a time to check for
errors.
❖ A debugger can use breakpoints, points in the code where the program can be stopped to
realize what is happening and check for errors.
Lesson
1Most popular programming languages
❖ Today, there are dozens of programming language use in the industry.
❖ The 5 most popular programming languages are:
1. Python
Python, the language you will learn, is a general-purpose language created in the early
[Link] few years it has become popular by using the business and academic applications.
[Link]
It was created by Sun microsystems in the early [Link] can be used to develop programs
that run on both, a single computer or over the internet from a web server.
3.C and C++
C and C++(pronounced ”C plus plus”)These powerful languages are general-
purpose languages developed at Bell Laboratories. The C language was created
in 1972 while C++ language was created in 1983 as more advanced C language.
Lesson
1 4:C#
❖ C#(pronounced sharp”) this language was by Microsoft around the year 2000 for developing
applications based on the Microsoft platform.
4:Javascript
JavaScript, created in the 1990,it’s a popular script in developing web pages.
Despite, the name JavaScript is not related to java.

➢ The programming language you will be learning is a python. Python is an example of a high-
level language and considered as an interpreted language because Python programs are
executed by an interpreter
Lesson
1 1.3 Why python?
❖ Python language is fun and extremely an easy-to-use programming language that has gradually gained
its popularity over the last few years. But it’s development back to over 10 years ago by Guido van
Rossum. Python's easy and simple syntax and its overall feel are mainly derived from ABC, a teaching
programming language that was developed in the [Link],python was also created to solve real
problems and it derives a wide variety of features from powerful programming languages such as
C,C++ and Java. For this reason, one of the python’s most amazing features is its broadly appeal to
professional software developers,scientists,researchers,artists, and educators.
❖ For beginning programmers, python has the advantage that it enforces writing readable code.
❖ Here is an example of the difference between using python, and using some other popular
programming languages.
❖ Mostly, the first program that anyone writes in any language, is Hello World. This is a simple program
that displays the “Hello, world!” on the screen using some popular programming languages.

C++, Hello World is coded as follows


#include <iostream>
Int main() {
Std: :cout << “Hello, world!”;}
Lesson
1 C#, Hello World is coded as follows
Using system;
Namespace HelloWorld {
Class Hello {
Static void main() {
Console. WriteLine(“Hello, world!”);
[Link]();}}}

Java
Class Hello {
Public static void main( strings[] args ) {
[Link]( “Hello, World!”);}}

➢ Now, compare this to writing Hello World in python:


▪ Print(“Hello, world!”)
Lesson
2 INTRODUCTION PROGRAMMING USING PYTHON

Learning Objectives
At the end of the lesson, the learner should be able to:
1. Describe the important tools used to getting to start the python programming.
2. Execute a python script using at the shell prompt and interactive window
using IDLE.
3. Explain the values, data types, variables and expressions in python.
4. Demonstrate the skills to use Conditional statements in python.
5. Demonstrate the skills to use repetitions statements in python
Lesson
2.1:Getting python
1

❖Installing python on Windows


Follow these steps to install python3 and open python interpreter on Windows.
Step1:Download the python 3 Installer
• Open a browser window and navigate to the download page for windows at
[Link]
• Under the heading of the top: Python Releases for windows.
• Click on the link Latest python 3 Release-Python 3.8.3 the latest version
• Then scroll to the bottom of the page, under the files heading selecting
Windows x86-64 executable installer.
Step2:Run the Installer
• Install Now.
• You should see the following window:
Lesson
1
Lesson
1 Continue..

Most Python installations install an environment to create programs in, which is called IDLE (Integrated
Development and Learning Environment). In Python, IDLE is a suitable environment to do your
programming in.
Open IDLE
You can open IDLE in two steps:
[Link] on the start menu and locate the Python 3.8 folder.
[Link] the folder and select IDLE (Python 3.8).
IDLE opens a Python shell in a new window. The Python shell is an interactive environment that allows you
to type in some Python code and execute it immediately. It is a great way to get started with Python
programming. The Python shell window looks like this:
Lesson
Continue..
1
Lesson
❖ At1the top of the window, you can see the version of Python that is running and some
information about the operating system.
The >>> symbol that you see is called a Python prompt. Wherever you see this, it means that
Python is waiting for you to give it some instructions.
Now that you have Python installed, let’s get straight into writing your first Python program.

Your First Python Program


❖ Now that you have the latest version of Python installed on your computer,
it’s time to start coding. If you don’t have IDLE open already, go ahead and open it.
There are two main windows that you will work with in IDLE:
The interactive window, which is the one that opens when you start IDLE.
The script window.
You can type code into both the interactive and script windows. The difference between
the two is how the code is executed. You will write your first Python program and learn
how to run it in both windows.
Lesson
2.2:The Interactive Window
1

❖ The interactive window contains a python shell, which is a textual user interface used to
interact with the python language hence the name Interactive window.
❖ In the Interactive window, the first line tells you what version of python is running.
❖ In this case, IDLE is running Python 3.11.9. The second and third lines give some information
about the operating system and some commands you can use to get more details about Python.
The >>> symbol in the last line is called the prompt. This is where you will type your code.
Go ahead and type 2+3 at the prompt and press Enter. When you hit Enter, Python evaluates
the expression, displays the result 5, and then prompts you for more input:
Lesson
1 Continue..
❖ Let’s try something a little more interesting than adding two numbers.
❖ A rite of passage for every programmer is writing their first “Hello, world” program
that prints the phrase “Hello, world” on the screen.
❖ To print text to the screen in Python, you use the print() function. A function is a bit of code
that typically takes some input, called an argument.
It does something with that input and produces some output, called the return value.
Functions in code work like mathematical functions. For example,
the mathematical function A(r) = πr² takes the radius r of a circle as input and
produces the area of the circle as output.
❖ Python’s print() function takes some text as input and then displays that text on the screen.
To use print(),type the word print at the prompt in the interactive window, followed by
the text”Hello,World” inside of parentheses.
Lesson
1
Lesson
1 Continue..
❖ Here “Hello, world” is the argument that is being passed to print() function. The “Hello,
world” must be written with quotation marks so that Python interprets it as text and not
something else.
❖ The interactive window can execute only a single line of code at a time. This is useful for
trying out small code examples and exploring the Python language, but it has a major
limitation because code must be entered one line at a time!
❖ Alternatively, you can store some Python code in a text file and then execute all of the code
in the file with a single command. The code in the file is called a script, and files containing
Python scripts are called script files.
❖ Script files are nice not only because they make it easier to run a program, but also because
they can be shared with other people so that they can run your program, too.
Lesson
1 2.3:The Script Window
❖ Scripts are written using IDLE’s script window. You can open the script window by selecting
File then click New File from menu at the top of the interactive window.
In the script window, type in the same code you used to print “Hello, world” in the interactive
window:
Lesson
1 Continue..
❖ Before you can run your script, you must save it. From the menu at the top of the window,
select File then click Save and save the script as [Link]. The .py file extension is the
conventional extension used to indicate that a file contains a Python program.
❖ Once the script is saved, all you have to do to run the program is to select Run then click Run
Module (You can also press F5 to run a script from the script window), and you'll see "Hello,
world" appear in the interactive window:
Lesson
1 Continue..
❖ To open an existing script in IDLE, select File then click Open from the menu in either the
script window or the interactive window. Then browse for and select the script file you want to
open. IDLE opens scripts in a new script window; you can have several scripts open at a time.

2.4:Values,Data types,Variables and Expressions


❖ A value is one of the fundamentals of programing__like a letter or a number__that a program
manipulates. The values we have seen so far are 5 (the result when we added 2+3), and “Hello,
World”.
❖ These values are classified into different data types, for example 5 is an integer,
And “Hello, World” is a string, so-called because it contains a string of letters.
Lesson
1 Data types
❖ The term data type refers to what kind of data a value represents. Specifically,
there are three different data types that you need to be aware of at this time, namely:
•Strings
•Integers
•Floats

String
❖ A string is a text, consisting of zero (empty string) or more characters.
In Python, a string is enclosed by either double quotes (") or single quotes (‘).
In principle, it does not matter which of the two you use, for example,
"Hello" is equivalent to 'Hello'. However, if you have a text which contains a single quote,
if you want to avoid problems you will have to enclose it in double quotes, for example,
"I can't wait to see you" is a legal string,
while 'I can't wait to see you' is not a legal string. Vice versa for double quotes in a string,
of course.
You (and the interpreter) can identify strings because they are enclosed in quotation marks.
If you are not sure what class a value falls into, Python has a function called type
which can tell you.
Lesson
1Integers
❖ Integers are whole numbers, which can be positive or negative (or zero). There is a certain
maximum size that integers can become, which depends on the kind of computer and
operating system you are running.
When you use integers in Python, you cannot write thousands with separators (commas in
English) to make them more readable.
❖ For example, the number one billion should be written as 1000000000 rather than
1,000,000,000.
Lesson
1 Floats
Floats, or "floating-point numbers," are numbers with decimals. For instance, 3.14159265 is a
float. Note that you have to use a period as the decimal separator. If there is an integer that for
some reason you want to use as a float, you can do so by adding .0 to it. For example, 13 is an
integer, while 13.0 is a float.

Expressions
❖ An expression is a combination of one or more values (such as strings, integers, or floats)
using operators, which result in a new value. In other words, you can think of expressions as
calculations.

2.5 Basic Calculations in Python


Python has numerous operators that can be used to perform mathematical calculations because
most real-world algorithms require calculations to be performed. A programmer’s tools for
performing calculations are math operators.
The table below lists the math (arithmetic) operators that are provided by the Python language:
Symbol Operation Description
+ Addition Adds numbers

- Subtraction Subtracts one number from another

* Multiplication Multiplies one number by another

/ Division Divides one number by another and


gives
The result as a floating-point
number
// Integer division Divides one number by another and
gives
The result as an integer
% Remainder Divides one number by another and
gives the remainder
** Exponent Raises a number to a power
Lesson
1 Continue..
❖ Programmers use the operators shown in the above table to create math expressions.
A math expression performs a calculation and gives a value. The following is an example of a
simple math expression:
18+5
❖ The values on the right and left of the + operator are called operands.
These are the values that the + operator adds together.
If you type this expression in interactive mode, you will see that it gives the value 23.
Lesson
1 2.6:More Complex Calculations
❖ You are allowed to combine operators into bigger calculations, just as you can do on the more
advanced calculators. To help you out, you are also allowed to use parentheses in your
calculations, and you can even nest these parentheses. Python will process the operators in
the order prescribed by mathematicians, often referred to as
PEMDAS(Parenthesis,Exponents,Multiplication and Division, Addition and Subtraction).
❖ Check out the calculation below, and try to predict what it will result in before you write it to the
Python shell and run the code.
print(5 * 2 - 3 + 4 / 2)
Lesson
2.7:String expressions
1

❖ Some of the math operators given above table can also be used for strings, though not all of
them. In particular, you can use the addition operator (+) to concatenate two strings and you
can use the multiplication operator (* ) with a number and a string to create a string that
contains a repetition of the original string. Check it out:
print(“hello ”+”world”)
print(3 “hello”)
Print(“goodbye” *3)

❖ You cannot add a number to a string, or multiply two strings. Such use of the operators is
undefined, and will give error messages. None of the math operators will work on strings
either.
Lesson
2.8:Variables
1

❖ programs usually store data in the computer’s memory and perform operations on that data.
Programs use variables to access and manipulate data that is stored in memory. A variable is a
name that represents a value in the computer’s memory. For example, a program that calculates
the distance between two cities might use the variable name distance to represent that value in
memory. When a variable represents a value in the computer’s memory, we say that the variable
references the value.

Creating Variables with Assignment Statements


❖ use an assignment statement to create a variable and make it reference a piece of data.
Here is an example of an assignment statement:
Age=25
➢ After this statement executes, a variable named age will be created, and it will reference
the value 25.
Lesson
Continue..
1

❖ An assignment statement is written in the following general format:


Variable=expression
The equal sign (=) is known as the assignment operator. In the general format,
variable is the name of a variable and expression is a value, or any piece of code
that results in a value. After an assignment statement executes, the variable listed
on the left side of the = operator will reference the value given on the right side of the = operator.
To experiment with variables, you can type assignment statements in interactive mode,
as shown here:
>>> width = 20
>>> length = 25
➢ The first statement creates a variable named width and assigns to it the value 20.
The second statement creates a variable named length and assigns it the value 25.
Next, you can use the print function to display the values referenced by these variables,
as shown here:
>>> print(width)
20
>>> print(length)
25
Lesson
Program 2
1

Age=18
Print(“I’m young my age is”)
Print(age)
Program Output
I’m young my age is
18
➢ Note:
You cannot use a variable until you have assigned a value to it. An error will occur if you try to
perform an operation on a variable, such as printing it, before it has been assigned a value.
Lesson
Variable names
1

❖ When you create variables, you are free to choose the names of your variables as you like,
provided that you follow a few simple rules, namely:
•A variable name must consist of only letters, digits, and/or underscores (_).
•A variable name must start with a letter or an underscore.
•A variable name should not be a reserved word.
Here’s a list of all reserved keywords in Python Programming:
false await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

➢ You can use capitals and lower-case letters in variable names, but you should realize
that variable names are case sensitive, i.e., the variable age is not the same as the variable Age.
Lesson
Comments in Python
1

❖ When writing code in Python, it’s important to make sure that your code can be easily
understood by others. Giving variables obvious names and organizing your code are
all great ways to do this. Another awesome and easy way to increase the readability of
your code is by using comments.
❖ Comments are short notes placed in different parts of a program, explaining how those parts
of the program work.
Although comments are a critical part of a program, they are ignored by the Python interpreter.
Comments are intended for any person reading a program’s code, not the computer.
To write a comment in Python, simply put the hash mark # before your desired comment.
When the Python interpreter sees a # character, it ignores everything from that character to
the end of the line. This line is an example of a comment:
#this is a comment
➢ python ignores everything after the hash mark and up to the end of the line. You can insert
them anywhere in your code, even in line with other code:
Print(“this will run”) # this is a comment and won’t run.
Lesson
continue
1

❖ For example, the first lines of this program are comments that briefly explain the program’s
purpose.
#This program displays a person’s
#name and address
Print(“cash cadelle”)
Print(“farjanno,kismaayo”)
Program Output
Caasha cadelle
Farjanno,kismaayo.
❖ Programmers commonly write end-line comments in their code. An end-line comment is a
comment that appears at the end of a line of code.
❖ Example:
Print(“caasha cabdulle”) #Display the name.
Print(“farjanno,kismaayo”) #Display the address.
Lesson
1

❖ n
Lesson
1

❖ n
Lesson
1

❖ n
Lesson
1

❖ n
Lesson
1

❖ n

You might also like