You are on page 1of 28

Introduction to Python

Tharaka Ilayperuma
MYSELF

Name: THARAKA ILAYPERUMA,

Qualifications: PhL as well as PhD in Computer and Systems Sciences from Stockholm
University, Sweden

Specializations: Requirements Engineering (broadly), and requirements engineering for


e-commerce systems (specifically)

Roles: University Lecturer (21 years +), Systems developer (two systems)
What we will cover in this course?

• Generally, we will cover topics related to:


• Variables and data types
• Control structures
• Functions
• Data structures
• Exception and File handling
• Object-oriented principles such as classes, objects, inheritance, and polymorphism
• Testing
Python
Download PyCharm Community edition
Download Python from
https://www.python.org/downloads/ depending on your OS
This is the Python interpreter

Editors are what you write Python instructions with Not all editors are equal!
So that they can be interpreted by the Python interpreter
This happens when you run your program
Find one that suits you…
(or at least your current purposes)

Editors usually provide utilities to make your life easier


Integration with other developer tools
Colour coding
Intellisense (code completion, parameter inform capabilities, etc,), debugging functionality
Python
General Introduction
This session will cover…

What is programming?

Why Python?

Good Programming Practices

General structure of a computer program

Variables, operators, and data types

Input and Output

So that you know the basics to start writing a simple Python program!
Assignment details
You will be given several tasks organised into three assignments to submit

When you pass the course you will get 20 level 4 credits – This will be a good
opportunity to improve your skill portfolio at free of charge!
What is programming?

• In computing, programming simply means writing programs using a programming


language
• Program: set of instructions that tells your computer (or computing device) what to do and your
computer or your computing device has different types of software that let you do things you want
• E.g. Your computer’s OS (Windows, Linux, Mac, etc.,)
• There are many programming languages
• Python, PHP, C, C#, C++, Java, etc.,
Good programming practices

Use appropriate comments to describe the functionality of the program


e.g. # Calculate average

Use proper spacing to increase the readability (within and between different blocks of statements)
Detecting and correcting errors in
your program
Carefully read what the error is about and in which line

There are different online help resources. e.g.

You may not be the only one who may be having some programming problem. So just
Google your error and try to get help
Why Python?

Python is
Easy to use
Powerful
Versatile

It is used in many domains including


Data analysis
AI and Machine Learning
Network Programming
Web Application Programming
GUI Applications

Python interpreted vs. compiled? closer to human language

Python is an interpreted, high-level programming language https://docs.python.org/3/faq/general.html#what-is-python


dynamic vs. static?
Python has a dynamic type system
• Dynamically typed means that the Python interpreter does type checking only as code runs, and
the type of a variable is allowed to change over its lifetime type is associated with run-time values

The Python language does not provide backward compatibility


• Python version 3 released end of 2008 – not backwards compatible with Python version 2 (which is
still in use)

Python is intended to be readable


Python Standard Library

Provides lots of functionalities


that you will need

You just need to import them!


Python program - Example
This is a simple Python program that
simulates the tossing of a coin.

It generates a random number (either


0 or 1) to represent heads or tails.

If the number is 0 the program


outputs ”Heads!”.

If the number is 1 the program


outputs ”Tails!”.
Do you find this easy to read?
Example (contd.) - coin_toss.py

coin_toss is the name of the script

The .py extension indicates that it is


a Python file

Convention says use snake_case for


variables, functions and file-names
(lower-case with underscore separating
words)
Style Guide for Python Code

style of writing in which each space is


replaced with an underscore (_) character
The script is interpreted from top to bottom
You can bring in useful Each line below the top line
functionality so you don’t is an instruction for the
have to write it interpreter to execute. #
indicates a comment
You can assign values
A colon precedes a code
This is your business block (in Python a
logic (where you do your ‘suite’). Python code
computing) blocks are always
indented
Python is case-sensitive
Detailed view of the program
A comment begins with the hash character
(remainder of the line is ignored by the interpreter)

The ‘random’ module


contains functions to random.randint(a, b)
generate random returns a random integer
numbers from the lowerbound (a)
to the upperbound (b)
inclusive
The ‘if’ statement
does one thing if the Strings are surrounded
condition is true by double quotes or
’else’ it does single quotes
something else ( it doesn’t matter which, just keep it
The print() function consistent)
causes output
1) Describe your program

(Optional) Import any


modules you’ll need.
Note that Python’s
standard library is 2) Assign values to
very rich and provides variables
lots of reusable code

3) Do some processing

4) Output results
Basic structure of the program..

Keep these at the top


of your file – it helps # A comment
anyone coming to 0..* imports
read your code Don’t worry about
Setting up data keeping these separate
(although it is
usually helpful to do
Processing data
so) – just treat the
separation as loose
Output results guidance to help you
structure your ideas
Variables & Data types
Naming Variables
You must stick to these!
Rules for variable names:
must begin with a letter (a - z, A - B) or underscore (_)
other characters can be letters, numbers or _
No spaces
case sensitive so that my_string is different from My_String
can be of any length
cannot be a reserved word (https://docs.python.org/3.0/reference/lexical_analysis.html#id8)

Conventions for variable names:


first letter should be lowercase.
You should stick to these
E.g. age as well!
where names are made of more than one word, each word is separated by an underscore
e.g. first_name
https://www.python.org/dev/peps/pep-0008/#naming-conventions
Data types

Python variables are dynamically assigned and their type doesn’t need to
be pre-declared
coin = "Heads!" OR coin = str (Heads!) A(string - str)
These are 3 examples of built-in
https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
types in Python

You might also come across age = 21 An(integer - int)


- None https://docs.python.org/3/library/functions.html#int

- bool
- tuple, list, dict average = 5.6 A(floating point number - float)
https://docs.python.org/3/library/functions.html#float

There are other types! - https://docs.python.org/3/library/stdtypes.html

Think about the most appropriate data type to hold the


data!
Exercise 1

Write a Python program to assign your name to a variable and display it using the print()
function.
Arithmetic operators
Python supports the standard arithmetic operators:
* multiply
/ divide
% remainder
+ add
- subtract

You might also find useful


** to the power of (e.g. 2 ** 3 = 8)
// floor division (e.g. 10 // 3 = 3)

Python also supports operators such as <,>, <=, >=, ==, !=, =
Exercise 2

Write a simple Python program to assign two integers to two variables and perform
addition, multiplication, subtraction, and any other arithmetic operation that we
discussed in the previous slide on them and display the results, separately.
Operator precedence

Operators have precedence which determines the order in which they are evaluated:
operators with the same order of precedence are evaluated from left to right
[*, /, %, //] are evaluated before [+, -]

Brackets can group operations


what would be the results of the following?
1. a = (5 + 2) / 2 ?
2. b = 5 + 2 / 2 ?
Summary

We looked at
• installing Python and using a Python editor
• Programming and debugging tips
• Overview of Python and it’s uses
• Data types and operators in Python
Questions?

You might also like