0% found this document useful (0 votes)
11 views25 pages

Python Resource

This document outlines the learning outcomes for students in a Python programming course, including the ability to create flowcharts, pseudocode, and understand basic programming concepts. It covers Python syntax, data types, variables, conditional statements, loops, and debugging techniques. Additionally, it introduces the Python IDLE environment and emphasizes the interaction between programs and hardware.
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)
11 views25 pages

Python Resource

This document outlines the learning outcomes for students in a Python programming course, including the ability to create flowcharts, pseudocode, and understand basic programming concepts. It covers Python syntax, data types, variables, conditional statements, loops, and debugging techniques. Additionally, it introduces the Python IDLE environment and emphasizes the interaction between programs and hardware.
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

Programming the

Computer-Python

Student Learning Outcomes

After going through this chapter, students will be able to:


1. Process and convert an algorithm into a flowchart.
2. Create solution steps using pseudo-codes.
3. Understand the concept of a computer program.
4. Understand that the program interacts with hardware.
5. Familiarize with Python programming language and user interface of Python IDLE
6. Work with basic commands of python such as print, input, comments, and
calculation with numbers, list and delete
7. Understand and work with conditional and looping structures in Python
8. Create robust programs by using functions in Python
9. Create shapes and graphics through programming
10. Create dynamic programs through user actions and event handling
11. Debug program by identifying logical and syntax errors

ISTE Student Standard Coverage

Empowered Computational Creative


Learner Thinker Communicator
1a 1d 5c 5d 6d
2023-2024

5.1. Overview
Computer programming is a way of giving
computers instructions about what they should
do next. These instructions are known as code,
and computer programmers write code to solve
problems or perform a task.
The end goal is to create something: that could
mean anything from a web page, or a piece of
software, or even just a pretty picture. That’s
why computer programming is often described
as a mix of art and science; it’s technical and
analytical, yet creative at the same time.

5.2. Flowcharts and Algorithms


Algorithms and flowcharts are two different tools used for creating new programs,
especially in computer programming. An algorithm is a step-by-step analysis of the
process, while a flowchart explains the steps of a program in a graphical way.

Algorithms
To write a logical step-by-step method to solve
Making a PB&J Sandwich
the problem is called an algorithm. In other undo the twist tie
get out two slices of bread

words, an algorithm is a procedure for solving get out two slices of bread
place them on a plate

problems. In order to solve a mathematical or open the jelly jar


scoop them out with a knife
spread jelly on one slice
computer problem, this is the first step of the wipe off the knife
open the peanut butter jar

procedure. An algorithm includes calculations, scoop some out with a knife


spread peanut butter on the other

reasoning and data processing. Algorithms can


set the knife down
pickup each of the slices
keep the dry sides on the outside
be presented by natural languages, pseudocode put the slices together
place the sandwich back down

and flowcharts, etc. pick the knife back up again


cut the sandwich into two halves
Flow Charts
A flowchart is a type of diagram that represents an algorithm, workflow or process.
The flowchart shows the steps as boxes of various kinds, and their order by connecting
the boxes with arrows. Flowcharts are used in analyzing, designing, documenting or
managing a process or program in various fields.

Flow Chart Symbols

Terminal

The rounded rectangles, or terminal points,


indicate the flowchart’s starting and ending
points.

Flow Lines
The default flow is left to right and top to bottom
(the same way you read English). To save time
arrowheads are often only drawn when the flow
lines go contrary the normal.

Input/Output

The parallelograms designate input or output


operations.

Process

The rectangle depicts a process such as a


mathematical computation, or a variable
assignment.

Decision

The diamond is used to represent the true/false


statement being tested in a decision symbol.
Example

Start

Read
temperature

temperature<32

Print Print
Below freezing Above freezing

End

5.3. Pseudocode
Pseudocode is an informal high-level description of
the operating principle of a computer program or Pseucode Example

other algorithm. It uses the structural conventions BEGIN


of a normal programming language but is intended input hours
input rate
for human reading rather than machine reading. pay=hours*rate
Pseudocode typically omits details that are essential print pay
for machine understanding of the algorithm, such END

as variable declarations, system specific code etc.


In simple words, Pseudocode is a precise form of an
algorithm without unnecessary steps of vocabulary/
words.
{Code}
5.4. What is a Program

In computing, a program is a specific set of


ordered operations for a computer to perform.
In the modern computer that John von Neumann
outlined in 1945, the program contains a one-at-a-
time sequence of instructions that the computer
follows.

How a Program Interacts with Hardware


Hardware is a term we use to describe the electronics and mechanical parts of the
computer. To be able to use it, we need programs, the software. A computer program
is a list of instructions stored as a file on a storage device. If this program is embedded
inside a hardware device it is called firmware.
When we run the program, the computer reads the list of commands or instructions
and does what the program tells it to do.

5.5. Getting Started with Python


Python is a high-level programming language
designed to be easy to read and simple to implement.
It is open-source, which means it is free to use, even
for commercial applications. Python can run on Mac,
Windows, and Unix systems.
Python is considered a scripting language, like Ruby
or Perl and is often used for creating Web applications
and dynamic Web content.

Programming Language v/s Scripting Language


Programming languages work with full-length code and are capable of running
independently while a scripting language generally runs on small chunks of code and needs
embedding into parent programs.
There are tens of thousands of famous python websites on the internet, few of them
are listed:

Uber Reddit Dropbox Google

Spotify Netflix Pinterest Amazon

Python IDLE

Python is a Programming language is popular because of its easy syntax. We will


start writing some code in PYTHON IDLE (Integrated Development and Learning
Environment).

File menu: it is for basic operations like opening, saving and printing programs.
Shell menu: it is to reset the environment
Debug menu: it is to check your program from any errors
Writing your First Program in Python

1. Open File menu and select New File or press Ctrl+N.

2. Type print (“My first program in Python”).

3. Open File menu and save the program or press Ctrl+S.

4. Run the program from the Run menu or press Ctrl+F5.


Python Indentations

Indentation refers to the spaces at the


Indentation Example
beginning of a code line. Where in other
programming languages the indentation in if 5 > 2
print (”Five is
code is for readability only, the indentation
greater than two”)
in Python is very important. Python uses
indentation to indicate a block of code.

5.6. Variables and Data Types “a” “hello”


A variable is nothing but a name given
to a storage area that our programs can
manipulate.
A variable is a container of data in a
computer’s memory where the computer stores
4 2.5
the different types of data and this could be
numeric or text. To create and access these
Variable (data containers) we name them so
we can call them in our program where it is
necessary.

Data can be of any type like text, numbers,


integers, etc. A variable can store values only in one
data type either it could be numeric or string. Python
has no command for declaring a variable.
Numeric data type: This data type is used to hold Comments in Python
numeric values like integers, or Float like decimal
#this is comment
numbers.
String data type: The string is a sequence of print(”hello world”)

characters like a simple text “Hello World”.


Python supports Unicode characters. Generally,
strings are represented by either single or double-
quotes. In Python variables are created the moment we assign a value to it. Unlike
other programming languages, Python has no command for declaring a variable. A
variable is created the moment we first assign a value to it.

Example

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, car_
name, total_volume). Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores(A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

Assign Value to Multiple Variables

Python allows us to assign values to multiple variables in one line:


Output Variables

The Python print statement is often used to output variables. To combine both text
and a variable, Python uses the + character:

We can also use the + character to add a variable to another variable:

5.7. Comments

Python has the ability to add comments for


the purpose of in-code documentation. In Comments in Python
other words, comments are just a dead piece
#this is comment
of code which can be used for our references
only. Comments start with a #, and Python will print(”hello world”)
render the rest of the line as a comment.
5.8. Python Numbers
There are three numeric types in Python:
• Integer: also known as int, is a whole number,
positive or negative, without decimals, of
Python Numbers

unlimited length. x=1 #int


• float: also known as floating point number, is a y=2.8 #float
z=1j #complex
number, positive or negative, containing one or
more decimals.
• complex: are written with a “j” as the imaginary
part
Variables of numeric types are created when we assign a value to them. To verify the
type of any object in Python, use the type() function. A sample code that determines
type is shown below:

Type Conversion

We can convert from one type to another with the int()and float() methods. A
sample code is shown below:
5.9. Calculation with Numbers

We can also use Python to do any kind of calculation: addition, subtraction,


multiplication, division, etc. The rules that we have learned in Microsoft Excel for the use
of parentheses apply here, too.
For example, let’s suppose that we want to display the term percentage of a student
for a subject by using averages in exam marks and course work. Multiplications and
divisions are calculated before additions and subtractions. This means that 4+2*5 gives
you 14 and not 30. Use parentheses to prioritize the sequence of calculations. For this
example, we will also look into the user interaction using INPUT feature of python to
take data from the user end.

Sample Code

#calculate the percentage of a subject


subject=(input(“enter the subject name: “))
exam= float(input(“enter the marks obtained in exam”))
CW=float(input(“enter the marks obtained in coursework”))
percentage=(exam+CW)/2
print(“The average percentage of: “, subject,”:”,percentage)

1. In this example, the first line is having a comment


2. In the 2nd line, we have declared a variable named subject with user input to
take subject name form user.
3. In the 3rd line, we have declared a variable name exam while setting its data type to
float.
4. In the 3rd line, we have declared a variable for course work with the name of CW
while setting its data type to float.
5. In the 5th line, we declare the variable name Percentage while setting its value to a
mathematical calculation of exam+cw divided by 2 to get the average percentage
of the subject.
6. In the 6th line, we have printed the string value along with the values of the
subject variable and percentage variable.
5.10. LIST in Python
In Python, you can store your data into variables,
but you can also put them in lists. A list is just an
Checkpoint
ordered collection of items which can be of any data
type. Creating a list is as simple as putting different Algorithms can be presented by natural
languages, pseudocode and flowcharts
comma-separated values between square brackets. Hardware is a term we use to describe
the electronics and mechanical parts of

Each element of a list is assigned a value by using an the computer.


Comments are used for the purpose of
in-code documentation.
index.
An example of a list could be:
NewList=[10,20,30,”Samsung”]
To call a list element is very easy as calling a cell reference in excel:
print(NewList[3]). By this code, pythons output will be Samsung, as the count in
the list starts from 0.

Deleting an Item from List


Del command is used to delete a list element as mentioned in the example below

Adding an Item to the List

To add an item to the end of the list, use the append() method
5.11. Conditional Statements in Python

Conditional statement is a set of rules performed if a certain condition is met.

IF Statement

IF statement is a programming conditional statement that, if proved true, performs a


function or displays information. An if statement in python is written by using the IF
keyword. The sample code below shows the if statement in python.

Sample Code
# This program compares two numbers
using if
a = 33
b = 200
# if block
if b > a:
print(“b is greater than a”)

In this example, we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know that
200 is greater than 33, and so we print to screen that “b is greater than a”.
Indentation is necessary; if we do not use the indentation as mentioned in example,
python will give an error.

ELIF Statement
The ELIF keyword is Python’s way of saying if the previous conditions were not true,
then try this condition. The sample code below demonstrates Elif statement.
Sample Code
# This program compares two numbers
using elif
a = 33
b = 200
# if block
if b > a:
print(“b is greater than a”)
# elif block
elif b = = a:
print(“a and b are equal”)

In this example a is equal to b, so the first condition is not true, but the elif condition is
true, so we print to screen that “a and b are equal”.

Else Statement
The else keyword catches anything which isn’t caught by the preceding conditions. The
sample code below shows else statement.

Sample Code
# This program compares two numbers using else
statements
a = 33
b = 200
# if block
if b > a:
print(“b is greater than a”)
# elif block
elif b == a:
print(“a and b are equal”)
# else block
else
print(“a is greater than b”)
In this example a is greater than b, so the first condition is not true, also the elif
condition is not true, so we go to the else condition and print to screen that “a is
greater than b”. We can also use the else without using elif.

5.12. Loops in Python


A For loop is used for repeating over a sequence (that is either a list or a string). This
is less like the FOR keyword in other programming languages and works more like an
iterator method as found in other object-orientated programming languages.
For example, we have a list of students and we want to display the student with the
highest marks without using the max() function:

Sample Code

# This defines a list of student marks


stdMarks = [70, 80, 92.5, 60.2]
# This variable keeps track of the max marks
maxMarks = 0
# for loop block
for i in range(0,4):
if stdMarks[i] > maxMarks:
maxMarks = stdMarks[i]
# Prints highest student marks
print(“highest marks are: “, maxMarks)
1. In the 1st line of this code, we have created a list StdMrks with four values stored
in it.
2. In the 2nd line, we have declared a variable name MaxMarks with an integer value
of 0.
3. In the 3rd line, we use for loop while declaring another variable i with the range of
four.
4. This means this loop will run 4 times. Every time FOR loop runs, it will increase the
value of the i variable.
5. In the 4th line, we have set a condition to check that if StdMrks[i] variable is
greater than MaxMrks (declared 0 in 2nd line) variable then change the value of
MaxMarks[i] to StdMrks value. (StdMrks[i] variable is going to change its
value every time the loop runs and change the index of StdMrks. This process is
also known as unary increment). Using indention is compulsory or python will not
consider the For loop elements and give an error.
6. In the 5th line, MaxMrks is setting its value equal to the current value of StdMarks
only if the condition in the previous line is true.
7. In the 6th line, we have just printed the value of MaxMrks along with a string
sentence.

5.13. Functions in Python

In Python, a function is a group of related


statements that perform a specific task.
Functions help break our program into smaller
and modular chunks. As our program
grows larger and larger, functions make it
more organized and manageable.
Furthermore, it avoids repetition and makes
code reusable. Function names cannot
have spaces in between. Instead of spaces use
_ underscore to connect the words.
In Python, a function is defined using the def keyword and for executing the function
we can use the function name along with parentheses ().
Sample Code-1
The sample code below demonstrates how functions are used in python:

# This declares the function


called my_function()
def my_function():
print(“Hello from a
function”)
# Calling the function
my_function()

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. The last line executes the function, we can call or use the function in our code
wherever it is needed.

Sample Code-2

# This declares the function


called print_name()
def print_name():
print(“Enter your name”)
yourName=input()
print(“Hi ”+yourName)
# Calling the function
print_name()

Sample Code-3

We have already experienced this code earlier but now we have converted the same
into a function and now it can be recalled and reused whenever required in the
program.
# This declares the function called my_function()
def getMarks():
Subject=(input(“Enter the subject name:”))
Exam=float(input(“Enter the marks obtained in the Exam:”))
CW=float(input(“Enter the marks obtained in the course work:”))
Percentage= (Exam+CW)/2
print(“The Average Percentage of”, Subject,”:”, Percentage)
# Calling the function
getMarks()

5.14. Error Handling in Python

A software bug is a coding error that causes an


unexpected defect in a computer program. In
other words, if a program does not perform as Checkpoint
intended, it is most likely because of a bug.
A list is just an ordered collection of
There are bugs in software due to unclear or items which can be of any data type.
constantly changing requirements, software IF statement is a programming
conditional statement that, if proved
complexity, programming errors, timelines, true, performs a function or displays
information.
errors in bug tracking, communication gap,
documentation errors, deviation from standards
etc.
There are two types of errors/bug in
python or any other programming
language.
Syntax Error: errors in typing the
commands and variables. Syntax
errors will be automatically detected
by the Python IDLE and will show
you the error in a dialogue box with a
suggested solution or the line number
where the mistake has been done:
Logical Error: a logical mistake while designing the program which occurs due to the
improper planning of the program flow. Logical errors can be avoided by working on a
Data Flow Diagram (DFD), one practice of DFD is also a flowchart which is an extract
of the algorithm. Mentioned below are the few areas which can be used to avoid
logical errors in your program:

Form a hypothesis or two before looking at code.


• Resolve syntax errors.
• Start the debugger.
• Identify key variables or conditions.
• Step to your suspicious code.
• Look at the relevant variables.
• Predict what the suspicious line should do.
• Compare your expectations with reality.
• Think about your logic.

5.15. Creating Graphics with Python

The Canvas widget supplies graphics facilities for Tkinter. Among these graphical
objects are lines, circles, images, and even other widgets. With this widget, it’s possible
to draw graphs and plots, create graphics editors, and implement various kinds of
custom widgets and for using those we need to call/import the library of Tkinter so we
can use these functions.

Example-Creating Line

We will draw our first example, drawing a line.


The method create_line(coords, options) is used to draw a straight line. The
coordinates “coords” are given as four integer numbers: x1, y1, x2, y2 this means that
the line goes from the point (x1, y1) to the point (x2, y2).
from tkinter import*
master=Tk()
canvas_width=80
canvas_height=40
w=Canvas(master, width=canvas_
width,height=canvas_height)
[Link]()
y=int(canvas_height/2)
w.create_line(0,y,canvas_width,y,fill=”#476042”)
mainloop()

Sample Code-Creating Rectangle

For creating rectangles, we have the method create_rectangle(coords, options).


Coords are again defined by two points, but this time the first one is the top left point
and the bottom right point of the rectangle.

from tkinter import*


master=Tk()
w=Canvas(master, width=200, height=100)
[Link]()
w.create_
rectangle(50,20,150,80,fill=”#470642”)
w.create_rectangle(65,35,135,65,fill=”yellow”)
w.create_line(0,0,50,20,fill=”#470642”,width=3)
w.create_line(0,100,50,80,fill=”#470642”,width=3)
w.create_line(150,20,200,0,fill=”#470642”,width=3)
w.create_line(150,80,200,100,fill=”#470642”,width=3)
mainloop()
The following image with the coordinates will simplify the understanding of the
application of create_lines and create_rectangle in our previous example.

Sample Code-Creating Oval

We can create an oval on a canvas c with the method id = C.create_oval (x0,


y0, x1, y1, option, ... ) This method returns the object ID of the new oval
object on the canvas C. The following script draws a circle around the point (50,50)
with the radius 100:
from tkinter import*
canvas_width=190
canvas_height=150
master=Tk() As per [Link], there are over
500,000 openings for
w=Canvas(master, width=canvas_width, computing jobs in the USA.
height=canvas_height)
[Link]()
w.create_oval(50,50,100,100)
mainloop()
5.16. Event Handling in Python
Events in python are more likely we have in other programming languages. They also
execute at any specific action/signal occurred for i.e. hovering a mouse at a certain
point, clicks of the mouse either right click or left click and so on.
A Tkinter application runs most of its time inside an event loop, which is entered via the
mainloop method. It waits for events to happen. Events can be key presses or mouse
operations by the user.
Tkinter provides a mechanism to let the programmer deal with events. For each
widget, it’s possible to bind Python functions and methods to an event.
[Link](event, handler) If the defined event occurs in the widget, the handler
function is called with an event object, describing the event.

Sample Code-1
from tkinter import*
def hello (event):
print(“Single click, Button-1”)
def quit(event):
print(“Double click, so let’s
stop”)
import sys;[Link]()
widget=Button(None,text=’Mouse
Clicks’)
[Link]()
[Link](‘<Button-1>’,hello)
[Link](‘<Double-1>’,quit)
[Link]()

In this program, the event will be triggered by clicking on the Tkinter widget window. If
we click once it will say “Single Click, Button-1” as defined in string values and
if we double click it will say “Double click, so let’s stop as defined in a string
value.
Sample Code-2

Let’s have another simple example, which shows how to use the motion event, i.e. if the
mouse is moved inside of a widget:

from tkinter import*


def motion(event):
print(“Mouse position:(%s %s)” % (event.x,event.y))
return
master=Tk()
whatever_you_do=”Expect the best, Prepare for the worst.\n
Mohammad Ali jinnah”
msg=Message(master,text=whatever you do)
[Link](bg=’lightgreen’,font=(‘times’,24,’italic’))
[Link](‘<Motion>’,motion)
[Link]()
mainloop()

Every time we move the mouse in the Message widget, the position of the mouse
pointer will be printed. When we leave this widget, the function motion() is not called
anymore.

Color Codes in Python

Basic colour list plot for python. There are more colours which can be used with basic
words like forest green or lime etc.

gray olive blue

brown green purple

orange cyan red


Let’s Review

1. Algorithms can be presented by natural languages, pseudocode and flowcharts, etc.


2. A flowchart is a type of diagram that represents an algorithm, workflow or process.
3. Pseudocode is an informal high-level description of the operating principle of a
computer program or other algorithm
4. A program is a specific set of ordered operations for a computer to perform
5. Python is a high-level programming language designed to be easy to read and
simple to implement.
6. Indentation refers to the spaces at the beginning of a code line.
7. A variable is a name given to a storage area that our programs can manipulate.
8. A list is just an ordered collection of items.
9. For loop is used for repeating over a sequence.
10. Conditional statement is a set of rules performed if a certain condition is met.
11. A function is a group of related statements that perform a specific task.
12. A software bug is a coding error that causes an unexpected defect in a computer
program.
13. Syntax errors in typing the commands and variables.
14. A logical mistake while designing the program which occurs due to the improper
planning of the program flow is called logical error.

My Notes!!

You might also like