Programming In Python
CT088-0-M version 1 (November 2017)
Introduction to Python Programming
Topic & Structure of The Lesson
• Introduction to Python
– Syntax
– Data Type
– Data structure
– Function
CT088-0-M Programming In Python Introduction to Python Programming
Learning
Outcomes
• At the end of this lecture you should be
able to:
– Develop a problem-based strategy for creating and applying
programmed solutions.
– Create, edit, compile, run, debug and test programs using an
appropriate development environment
CT088-0-M Programming In Python Introduction to Python Programming
Key Terms You Must Be
Able To Use
• If you have mastered this topic, you should be able to
use the following terms correctly in your assignments
and exams:
– Program
– Programming
– Interactive Mode
– Script Mode
– Constant
– Variable
– Reserved word
– Type
– Comment
CT088-0-M Programming In Python Introduction to Python Programming
What is a
Program/Code/Software?
• A computer cannot solve or do any task on its own.
You must instruct it to do what you want it to do
• A Program is a set of instructions to the Computer
to perform a job/task.
– It is a little piece of our intelligence in the computer
– It is a little piece of our intelligence we can give to others
- we figure something out and then we encode it and
then give it to someone else to save them the time and
energy of figuring it out
• A piece of creative art - particularly when we do a
good job on user experience
CT088-0-M Programming In Python Introduction to Python Programming
What is programming?
• Computer Programming is the art of
making a computer do what you want it to
do.
• At the very simplest level it consists of
issuing a sequence of commands to a
computer to achieve an objective.
CT088-0-M Programming In Python Introduction to Python Programming
What do we need?
• PC (Windows/LINUX/OS X or others).
• Programming Language.
• Notepad / IDE.
• Plenty of practice.
CT088-0-M Programming In Python Introduction to Python Programming
What is a programming
language?
• A language used for the purpose of writing
programs or giving instructions to the
computer.
• They are hundreds of programming
languages.
• A program written in a language of choice
need to be compiled - that is, turn it into
lots of 0s and 1s, that the computer can
easily and quickly understand.
CT088-0-M Programming In Python Introduction to Python Programming
Python Programming Language
• A high-level general purpose programming
language.
• An interpreted programming language -
compiles the bits of the program on the fly.
• Python can be used as a scripting
language, Web application implementation
language, etc.
• Python can provide the speed needed for
even compute intensive tasks.
CT088-0-M Programming In Python Introduction to Python Programming
Learning Python
• Learning a new programming language is
similar to learning a new human language
like English
• First step would be to learn the language
elements: symbols, words, sentences,
grammar
• For a programming language: symbols,
variables, constants, statements, control
structures
CT088-0-M Programming In Python Introduction to Python Programming
Elements of Python
• Constants/Variables
• Expression: Something that describes a computation
that gives a value. For example, 2+3 is an expression
that can be evaluated to give 5, and (2+3)*4 is an
expression with another expression inside it.
• Statement: Something that describes an action to be
performed by the computer. For example,
print("Hello“) is a statement that tells the Python
system to output Hello.
• Scripts: Constructing a program for a purpose.
Python programs are called scripts because they are
executed immediately, one line at a time.
CT088-0-M Programming In Python Introduction to Python Programming
Constants
• Fixed values such as numbers, letters, and
strings are called “constants” - because their
value does not change
• Numeric constants
>>> print(123)
123
>>> print(98.6)
98.6
• String constants use single-quotes (')
or double-quotes (")
>>> print('Hello world‘)
Hello world
CT088-0-M Programming In Python Introduction to Python Programming
Variables
• A variable is a named place in the memory where a
programmer can store data and later retrieve the
data using the variable “name”
• Programmers get to choose the names of the
variables
• You can change the contents of a variable in a later
statement
x = 12.2 x 12.2100
y = 14
x = 100 y 14
CT088-0-M Programming In Python Introduction to Python Programming
Python Variable Names Rules
• Choose a meaningful name
• Can be as long as you like
• Can contain both letters and numbers
• Must start with a letter or underscore _
• Cannot begin with a number
• Cannot use keywords
• Case Sensitive (spam Spam SPAM)
• Legal to use uppercase, however all lowercase is the
convention
• Underscore can be used for multi-word variable name:
name_of_student
CT088-0-M Programming In Python Introduction to Python Programming
Keywords or Reserved Words
• Keywords are words reserved by python that have
predefined meaning. You can not use reserved
words as variable names / identifiers
False class finally is
return
None continue for lambda
try
True def from
nonlocal while
and del global not with
as elif if or
yield
CT088-0-M Programming In Python Introduction to Python Programming
Assignment Statements
• We assign a value to a variable using
the assignment statement (=)
• An assignment statement consists of an
expression on the right hand side and
a variable to store the result
x = 3.9 * x * ( 1 - x )
CT088-0-M Programming In Python Introduction to Python Programming
Numeric Expressions
• Because of the lack of Operator Operation
mathematical symbols on
computer keyboards - we use + Addition
“computer-speak” to express Subtracti
-
the classic math operations on
• Asterisk is multiplication Multiplica
*
• Exponentiation (raise to a tion
power) looks different from in / Division
math.
** Power
Remainde
%
r
CT088-0-M Programming In Python Introduction to Python Programming
Order of Evaluation
• When we write operators together -
Python must know which one to do first
• This is called “operator precedence”
• Which operator “takes precedence”
over the others
x = 1 + 2 * 3 - 4 / 5 ** 6
CT088-0-M Programming In Python Introduction to Python Programming
Operator Precedence Rules
• Highest precedence rule to lowest
precedence rule
– Parenthesis are always respected
– Exponentiation (raise to a power)
– Multiplication, Division, and Remainder
– Addition and Subtraction Parenthesis
– Left to right Power
Multiplication
Addition
Left to Right
CT088-0-M Programming In Python Introduction to Python Programming
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print(x)
11
>>> 1+8/4*5
1+2*5
Parenthesis
Power
Multiplication
Addition 1 + 10
Left to Right
11
CT088-0-M Programming In Python Introduction to Python Programming
>>> x = 1 + 2 ** 3 / 4 * 5
1 + 2 ** 3 / 4 * 5
>>> print(x)
11
>>> 1+8/4*5
Note 8/4 goes before 4*5
because of the left-right rule.
1+2*5
Parenthesis
Power
Multiplication
1 + 10
Addition
Left to Right
11
CT088-0-M Programming In Python Introduction to Python Programming
What does “Type” Mean?
• In Python variables and
constants have a “type”
• Python knows the difference
between an integer number >>> ddd = 1 + 4
and a string >>> print(ddd)
• For example “+” means 5
“addition” if something is a >>> eee = 'hello ' + 'there'
number and “concatenate” if >>> print(eee)
hello there
something is a string
CT088-0-M Programming In Python Introduction to Python Programming
Type Matters
>>> eee = 'hello ' + 'there'
• Python knows what “type” >>> eee = eee + 1
everything is Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• Some operations are TypeError: cannot concatenate 'str'
prohibited and 'int' objects
>>> type(eee)
• You cannot “add 1” to a <type 'str'>
string >>> type('hello')
<type 'str'>
• We can ask Python what >>> type(1)
type something is by <type 'int'>
using the type() function. >>>
CT088-0-M Programming In Python Introduction to Python Programming
Several Types of Numbers
• Numbers have two main
types >>> xx = 1
– Integers are whole numbers: -14, >>> type (xx)
-2, 0, 1, 100, 401233 <type 'int'>
– Floating Point Numbers have >>> temp = 98.6
decimal parts: -2.5 , 0.0, 98.6, >>> type(temp)
<type 'float'>
14.0
>>> type(1)
• There are other number types <type 'int'>
- they are variations on float >>> type(1.0)
<type 'float'>
and integer >>>
CT088-0-M Programming In Python Introduction to Python Programming
Type Conversions
>>> print(float(99) / 100)
• When you put an 0.99
>>> i = 42
integer and floating >>> type(i)
point in an expression <type 'int'>
the integer is implicitly >>> f = float(i)
>>> print(f)
converted to a float 42.0
• You can control this >>> type(f)
with the built in <type 'float'>
>>> print(1 + 2 * float(3) / 4 – 5)
functions int() and -2.5
float() >>>
CT088-0-M Programming In Python Introduction to Python Programming
String >>> sval = '123'
Conversions >>> type(sval)
<type 'str'>
>>> print(sval + 1)
• You can also use Traceback (most recent call last):
File "<stdin>", line 1, in <module>
int() and float() to TypeError: cannot concatenate 'str'
convert between and 'int'
strings and integers >>> ival = int(sval)
• You will get an error >>> type(ival)
<type 'int'>
if the string does not >>> print(ival + 1)
contain numeric 124
characters >>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
CT088-0-M Programming In Python Introduction to Python Programming
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
– Describe what is going to happen in a
sequence of code
– Document who wrote the code or other
ancillary information
– Turn off a line of code - perhaps temporarily
CT088-0-M Programming In Python Introduction to Python Programming
Installing Python
• Download Python from www.python.org
• Run the downloaded file and follow the on
screen commands.
CT088-0-M Programming In Python Introduction to Python Programming
Testing Python
Menu -> Python -> IDLE (Integrated Development
Environment)
CT088-0-M Programming In Python Introduction to Python Programming
Testing Python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23
2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]
on win32
Type "copyright", "credits" or "license()"
for more information.
>>>
You can type Python statements and expressions
for immediate execution or evaluation in the space
provided after the >>>
This is called the interactive mode
CT088-0-M Programming In Python Introduction to Python Programming
>>> 1 + 2
3
>>> 2 * 3
6
>>> x = 1
>>> print(x)
1
>>> x = x + 1
>>> print(x)
2
>>> exit()
This is a good test to make sure that you have Python
correctly installed. Note that quit() also works to end the
interactive session.
CT088-0-M Programming In Python Introduction to Python Programming
Writing a program (a script)
• Python programs are called scripts
because they are executed immediately,
one line at a time.
• To write a program, choose File, New
Window. An editing window pops up:
CT088-0-M Programming In Python Introduction to Python Programming
Saving Your Program
• Remember to save your program after you
finish (File, Save As...).
• You must give the script a name ending in .py.
• Note: As soon as you have saved the file with
a .py ending, its contents become color-coded
just like the things you typed in the Python
shell. That's because the editing window has
recognize you're typing a Python program.
CT088-0-M Programming In Python Introduction to Python Programming
Running your program
• To run your program, choose Run, Run
Module, or just press F5:
CT088-0-M Programming In Python Introduction to Python Programming
Running your program
• When you run your program, the Python
shell window will come to the front and
your program will run in it:
CT088-0-M Programming In Python Introduction to Python Programming
Modifying your program
• You can go back to the editing window, to
make small changes in your program, and
hit F5 again. The following cryptic
message will appear:
CT088-0-M Programming In Python Introduction to Python Programming
Making changes in your
program
• Source must be saved means "Your
program must be saved."
• It is called source code because it is code
written by a human being, not code
generated by a computer.
• As soon as you let IDLE save your
program, it runs again in the Python shell.
CT088-0-M Programming In Python Introduction to Python Programming
Programs with Errors
• Normally, if a program runs into an error
while executing, you'll get a message
about it in the Python shell window:
CT088-0-M Programming In Python Introduction to Python Programming
Syntax Error
• Serious syntax errors will prevent the
program from even starting.
• In that case, the editing window cannot
hand the program over to the Python shell,
so instead, it will show you where the error
was detected, like this:
CT088-0-M Programming In Python Introduction to Python Programming
Running programs outside
IDLE
• One way to run a Python program outside
IDLE is to simply right-click on it (in a
folder or on the desktop)
• (Python must be installed on your
computer, of course.)
• The program will then run in what is called
a console window:
CT088-0-M Programming In Python Introduction to Python Programming