Year78Part1_88ffcbe7e3aa48309d770dea2bf73440 (3)
Year78Part1_88ffcbe7e3aa48309d770dea2bf73440 (3)
• Discuss and demonstrate how to use interactive mode and script mode in python
2. Script mode
2. Script mode • We can save the file with a .py extension
• To open a new file for programming in script mode
you click on File and then New File
• Then, save it to your Documents folder and run
your program by selecting Run Module from the
Run menu or pressing F5 on your keyboard.
Other Integrated Development Environments (IDEs)
Other types of IDEs
1. Thonny (contains both a Python shell and a script area in a single window)
2. Wing IDE 101
3. IDLE
Turtle Graphics
• Python has a special built-in module that we can use to create programs that draw patterns. This is an
implementation of the turtle graphics part of the Logo programming language.
• The great thing about this module is that the simple turtle commands can be combined with Python
code. This means that, as we learn more about Python, we will be able to make more sophisticated
and interesting turtle programs.
What is a turtle?
• A turtle is a robot that can be programmed to draw a line by following a path and placing a pen on the
floor to create a line.
A floor Turtle
Turtle Graphics
• The language that is used to control the robot consists of simple directional commands and is based
on the Logo programming language.
• There are many online sites and applications that allow users to control an onscreen turtle by using he
Logo programming language.
A few commands for a floor turtle
Turtle Graphics
• Python 3 comes with many commands that are ready to use – for example, print () and input ().
• There is also a large library of other commands we can use if we import one of the many built-in
modules that come with the standard install.
Example of Python built-in modules
1. Turtle
2. tkinter
There are different ways of importing these modules. How you import them affects the way you have
to write your commands.
Different ways of importing modules
• the turtle module is imported with the following line of code: From turtle import *
Turtle Graphics
3 Write a turtle program that draws a regular pentagon with sides of length 100 pixels.
Topic
• Use the data types Integer, Real, Char, String and Boolean
Types of data
• The data type is used by the computer to allocate a suitable location in memory.
How can we know what data type has been allocated by Python in our programs?
• To find out the data type of a variable or constant being used in a Python program, use the built-in
type () function.
Variables and arithmetic operators
Types of data
Variables and arithmetic operators
Types of data
Variables and arithmetic operators
Pseudo numbers
• Pseudo numbers are a collection of digits used to uniquely identify an item. They are not intended
to be used in calculations. They contain spaces or start with a zero.
• Pseudo numbers are normally stored in a String variable. If you store a mobile phone number as
an integer, any leading zeroes will be removed, while spaces and symbols are not permitted.
Examples of pseudo numbers
• Telephone numbers
• ISBN numbers
Variables and arithmetic operators
Naming conventions in Python
There are a variety of naming conventions in Python. Here are a few of them.
Things to consider when stating a variable names
• Use all lower case, starting with a letter and joining words with underscores. It is considered
good practice to use descriptive names. This aids readability and reduces the need for so much
commenting.
• Commenting is where the programmer writes notes in the program that the computer ignores. In
Python these start with the # symbol.
• In pseudocode, comments are preceded with two slashes (//)
Variables and arithmetic operators
Naming conventions in Python
Constants
• Constants are values that do not vary(change). Constants are used for data values that remain
fixed and keep the same value throughout our programs.
Things to consider when stating a constant
• Use all upper case characters to indicate constants.
Variables and arithmetic operators
Arithmetic operators
There are a number of operations that can be performed on numerical data in your programs.
Variables and arithmetic operators
Arithmetic operators
Variables and arithmetic operators
Arithmetic operators
Variables and arithmetic operators
Programming task
Variables and arithmetic operators
Solution to Programming task
• First we need to design the algorithm. Either with flowchart or pseudocode
Flowchart Pseudocode
Note: In Python, assignment is indicated by the use of the = symbol. In pseudocode, the <-- is used.
Variables and arithmetic operators
Note:
• To send a message to the user and collect their keyboard input, use Python’s input () function
• The input () function only returns string data types, so if we need to do calculations on numbers
supplied by the user, we will have to cast the string into an integer by using the int () function. For
example:
• age = int(input('How old are you?’))
Converting Demo task flowchart and pseudocode into python codes
# Initialize a variable to keep track of the result
result = 0
# Request and store user input
numberl = int (input('Please insert first number: '))
number2 = int (input('Please insert second number: '))
result = numberl * number2
Variables and arithmetic operators
# Display the value held in the variable result
print('The answer is ', result)
# End nicely by waiting for the user to press the return key.
input ('\n\nPress RETURN to finish.’)
Python modules
Python modules
• Python has lots of libraries of other code you can use in your programs. These are called modules.
• There are many built-in modules that have been made by other programmers around the world that you can
use and, of course, you can make your own.
• To access the tools in these modules, we first have to import them.
• // To import everything from the turtle library we use
From turtle import *
turtle(100)
However, It is safer to import your modules in the following way:
import turtle
This still gives your programs access to all the tools in this module but it now requires you to add turtle.
to all your commands.
Python modules
Python Turtle
turtle. forward(100)
Python modules
Python Turtle
Python modules
Python Turtle
To give the turtle direction
Note:
• picture should be in the same folder of the
python file
• Convert picture into gif format
• Use paint program or any picture editing program
Python modules
Python Turtle forward(100)/forward(-75)
Meaning /Help on function forward in module turtle:
• forward(distance)
• Move the turtle forward by the specified distance.
• Aliases: forward | fd
What you are to put inside the two brackets ()
Argument:
• distance -- a number (integer or float)
• Move the turtle forward by the specified distance, in the direction the turtle is headed.
Python modules
To draw a circle
Syntax
circle(radius, extent=None, steps=None)
• The center is radius units left of the turtle;
• extent - an angle - determines which part of the circle is drawn. If extent is not given, draw the
entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position.
• Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction.
• call: circle(radius) ------------------------ # full circle
--or: circle(radius, extent) ---------------- # arc
--or: circle(radius, extent, steps)
--or: circle(radius, steps=6)---------------- # 6-sided polygon
Python modules
To draw a circle
Example:
>>> circle(50) full circle
>>> circle(120, 180) # semicircle ------ radius and angle or extent no steps
>>> ----- radius and steps no angle
Python modules
To draw a square To draw a circle and color To draw a polygon and color
Random and Round
The random module provides functions that generate pseudorandom(random) numbers.
The function random returns a random float/decimal numbers between 0.0 and 1.0 (including 0.0 but not
1.0). Each time you call random (), you get the next number in a long series. We can assign a variable in
usual way:
my_random_number RANDOM()
To import the random module
Note:
• This program produces the following list of 10 random numbers between 0.0 and up to but not including
1.0.
• remember python is case sensitive and the indentation
• Run the program more than once and see what numbers you get.
Random and Round
The random function is only one of many functions that handle random numbers.
The function randint takes the parameters low and high, and returns an integer between low and
high (including both).
• A forever loop is an iterator that will keep repeating the code forever
• A repeat block will repeat the code for a set number of times
Algorithm design tools
Design Tools
• When you design programs, it is normal to plan the logic of the program before you start to code
the solution.
• The first step in the design process is to break down the problem into smaller problems. When we
do into it is called decomposition.
• Decomposition is computational thinking skills that involves thinking about large task and
breaking them down into smaller task
• The next stage is to design an algorithm for the individual problems. Two approaches that can be
used to design algorithms are flowcharts and pseudocode.
• You will need to be able to use them to explain the logic of your solutions to given tasks.
Stages of Design Process
Algorithm design tools
Flowcharts
• Flowcharts are graphical representations of the logic of the intended system.
• They make use of symbols to represent operations or processes and are joined by lines indicating
the sequence of operations.
Algorithm design tools
Flowcharts
Algorithm design tools
Flowcharts
What is Pseudocode?
• Pseudocode is a way of describing or representing the logic and sequence of an algorithm or
program using both natural language and code-like statement.
• It uses keywords and constructs, similar to those used in programming languages, but without the
need for a strict use of syntax.
Algorithm design tools
Principles underlying the usage of Pseudocode
• Use capital letters for keywords close to those used in programming languages.
• Use lower case letters for natural language descriptions.
• Use indentation to show the start and end of blocks of code statements, primarily when using
selection and iteration.
Advantage
• One of the advantages of learning to program using Python is that the actual coding language is
structured in a similar way to natural language and therefore closely resembles pseudocode.
• Python IDEs such as IDLE, Thonny and Wing IDE also automatically indent instructions where
appropriate
Algorithm design tools
Example of Pseudocode
• The following pseudocode is for an algorithm that accepts the input of two numbers. These values
are added together and the result is stored in a memory area called answer. The value in answer is
then displayed to the user.
Demo task: Construct a flowchart to represent the pseudocode example in Code snippet above.
Algorithm design tools
Topics
Subroutines
Objectivies
Subroutines
Introduction
Imagine you are writing a program that has 100 users who want to be able to change
their name. Imagine that to do this you had to write your code like this:
• If user1 wants to change their name:
<code that asks for user1's new name and then edits it>
• If user2 wants to change their name:
<code that asks for user2's new name and then edits it>
• If user3 wants to change their name:
<code that asks for user3's new name and then edits it> …….
• If user l00 wants to change their name:
<code that asks for userl00's new name and then edits it>
Subroutines
Introduction
• Your program would be very long and the chances of making a mistake would be high. Finding
errors would also be very tedious.
• We do not need to write code in this way. We can write one smaller program, within our larger
program, that can be called whenever any user needs to have their name changed. These smaller
programs are called subroutines.
• A subroutine is a code that performs a specific task that can be called from anywhere in the rest of
your program.
Characteristics of subroutine
All subroutines in Python require:
• An identifier (a name)
• A keyword define written as (def)
Subroutines
Introduction
For example:
def my_function():
chapter.
Subroutines
Types of subroutines Types of subroutines
There are Two main types of subroutine:
1. Functions
2. procedures
window = Tk()
window.title('My Application')
window.mainloop()
Graphical user interface (GUI) applications
When designing the layout of widgets in GUI applications, you can use the grid() method. This
organizes as many cells as you require in your window using a coordinate system.
Note how the numbers start from zero in the top left corner of the window:
Note: a recipe is another name for a piece of code that you use frequently):
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications (Solution)
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications (Solution)
from tkinter import *
def change_text():
my_label.config(text - gender.get())
window = Tk()
window.title('My Application')
gender = StringVar()
radiol = Radiobutton(window, text='Female', variable= gender, value='female')
radiol.grid(row=2, column=0, sticky=W)
window.mainloop ()
Graphical user interface (GUI) applications
Practice tasks:
• Study the code that inserts the radio buttons in previous slide
1. Which bit of code places them on the left side of the app?
2. How would you move them to the right side of the app?
3. Amend gender-gui. py by aligning the radio buttons to the East and see what happens when you
run it again.
Practice task:
4. Rewrite the radio button application but replace the radio buttons with a simple drop-down menu.