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

Lecture10 - Python programming 1(2)

Lecture 10 for MM2425

Uploaded by

kcehlel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views44 pages

Lecture10 - Python programming 1(2)

Lecture 10 for MM2425

Uploaded by

kcehlel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Python Programming

Basic programming concepts

1
First questions first
• What is Python?
– Python is an interpreted, high-level, general-purpose
programming language.
• What is a programming language?
– A programming language is a formal language, which
comprises a set of instructions that produce various kinds
of output.
– A computer program = instructions written by the human
and executed by the computer.
• What is a formal language?
– A formal language is well-formed according to a specific set
of rules (like grammars of human languages). 2

Why do people learn and use Python?
1. Python is easy to learn.
2. Python is quite popular and in demand.
3. Python has many libraries and frameworks.
4. Python is used in data science.
5. Python is used in machine learning and artificial intelligence.
6. Python is used in Web development.
7. Python is portable and extensible.
8. Python has a large community.
9. Python is used for building graphical user interfaces.
10. Python is used in scripting and automation.

3
How many people are using Python?
Usage percentages of the most popular programming languages

Source: https://www.youtube.com/watch?v=Og847HVwRSI 4
Programming Environment

Using a Python interpreter

5
Python interpreter
• To run Python programs, you will need the
Python interpreter. A Python interpreter
executes Python code.

6
How do you access a Python interpreter?
• Option 1
– Download the latest
version of Python.
• https://www.python.org/d
ownloads
/
– Run the installer file and
follow the steps to install
Python on your
computer.
– Once you finish the
installation process, you
7
can run Python.
How to install the Python interpreter on
your computer?
1) Click “Download
Python 3.8.2”
yellow button.

2) Save the file on


your hard disk.

3) Run the
downloaded file to
install the interpreter.

8
How to install the Python interpreter on
your computer?
4) Select the two options on the
bottom of the window.

5) Click “Install Now” to install, and


wait for a few minutes to complete.

6) Click “Close” button after


installation.

9
How to run your Python program on your
computer?
1) Find the Program
“Python 3.8” on your
computer.

2) Select and run “IDLE


(Python 3.8 32-bit)”

3) Click “File”.

4) Select “New File”.

10
How to run your Python program on your
computer?
5) A new window appears
and type your program
there.

6) Click “Run” and select


“Run Module”.

7) If the file is not saved,


save the file in any folder
you like.

11
How to run your Python program on your
computer?

The result of running the program will be shown on the “Python 3.8.2 Shell” window.

12
How do you access a Python interpreter?
• Option 2
– Using free online interpreters
• https://www.programiz.com/python-programming/online-
compiler
/ (suggested; used in this lecture)
• https://www.onlinegdb.com/online_python_interpreter
• https://repl.it/languages/Python3
• https://www.python.org/shell/

13
We use this online programming
environment in lectures
• https://www.programiz.com/python-program
ming/online-compiler/
2) Click “Run” button.

1) Write your program here. 3) Read the output of the program.


14
Syntax errors
• What happens when your program contains
syntax error(s) that cannot be understood by
the computer?

15
Your first programs

Output to the screen

16
Your first Python program
• Type and run the following program
print("Hello world!")
• Output
Hello world!

17
Comments
• Type and run the following program
#This is a comment
#print out Hello
print("Hello")
• Output
Hello

18
Try more print statements
• Type and run the following program.
print("First line")
print("Second line")
print()
print("Third line")
• Output
First line
Second line

Third line
19
Try to use semi-colon
• Type and run the following program using semi-
colon to write two or more statements on one line.
print("First line"); print("Second line"); print()
print("Third line")
• Output
First line
Second line

Third line

20
Print numbers and calculation results
• Type and run the following program.
print(1)
print(2)
print(1+2)
print("1+2")

• Output
1
2
3
1+2
21
Using variables
and assignment statements
Your computer can calculate

22
Numerical Variables
• Type and run the following program.
number = 10
print(number)
number = 1.1
print("The value =", number)
• Output
10
The value = 1.1
23
String (text) Variables
• Type and run the following program.
website = "www.apple.com"
print("My favorite website is", website)
• Output
My favorite website is www.apple.com

24
Python Keywords
• We cannot use a keyword as a variable name.
They are used to define the syntax and
structure of the Python language.
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
25
Rules for variable names
1. Variable names can be a combination of
letters in lowercase (a to z) or uppercase (A
to Z) or digits (0 to 9) or an underscore _.
e.g. myClass, var_1, print_this_to_screen
2. A variable name cannot start with a digit.
e.g. 1variable is invalid, but variable1 is valid.
3. Keywords cannot be used as variables (see
the previous slide).
e.g. class is invalid, but class1 is valid.
26
Rules for variable names
4. We cannot use special symbols like !, @, #, $,
% etc. in variable names
e.g. a@ is invalid
5. A variable name can be of any length.

27
Which are invalid variable names?
• computer
• computeR
• computer-1
• computer1
• computer_1
• 1computer
• 1_computer
• computer%
• $computer
• computer_
• _computer
28
Arithmetic calculation
• Type and run the following program.
num1 = 10
num2 = 1
num3 = num1 + num2
print("The sum of", num1, "and", num2, "is", num3)

• Output
The sum of 10 and 1 is 11

29
Arithmetic Operators
+ Addition Adds values on either side of the operator. x = a+b

Subtracts right hand operand from left hand


- Subtraction x = a–b
operand.

Multiplies values on either side of the


* Multiplication x = a*b
operator
Divides left hand operand by right hand
/ Division x = b/a
operand

Divides left hand operand by right hand


% Modulus x = b%a
operand and returns remainder

Performs exponential (power) calculation on


** Exponent x = a**b
operators

30
Examples of arithmetic calculation
• Type and run the following program.
a = 2
b = 5
x = a + b
print(x)
x = (a - b) * a
print(x)
x = a + a ** b
print(x)
• Output
7
-6
34
31
A big program example:
Solving a quadratic equation
# Solve the quadratic equation ax**2 + bx + c = 0
a = 1
b = 5
c = 6

# calculate the square root of the discriminant


sqrt_d = (b*b - 4*a*c)** 0.5

# find two solutions


sol1 = (-b + sqrt_d)/(2*a)
sol2 = (-b - sqrt_d)/(2*a)

print("The solution are", sol1, "and", sol2) 32


A big program example:
Solving a quadratic equation
• Try to modify the program on the previous
slide to solve the following quadratic equations

33
How to exchange values
of two variables
• Suppose two variables are two cups.
• How do you exchange tea in these two cups?
• You need one more cup.
Step 2

Step 1 Step 3

34
How to exchange values
of two variables
• Type and run the following program.
a = 1
b = 2
print("a=", a, "b=", b)

old_a = a
a = b
b = old_a
print("a=", a, "b=", b)
• Output
a= 1 b= 2
35
a= 2 b= 1
Compound Assignment Operators
• a = a + 10
– Taking the original value of the variable
– Adding 10 to this original value
– Assigning the calculation result to the same
variable
– Overwriting the original value.
• a += 10
– Same as a = a + 10

36
Compound Assignment Operators
• Other compound assignment operators
x += 1 same as x = x+1
x –= 2 same as x = x–2
x *= 4 same as x = x*4
x /= 10 same as x = x/10

37
Compound Assignment Operators
• Type and run the following program
a = 1
print(a)
a = a + 10
print(a)
a += 2
print(a)

• Output
1
11
13 38
Compound Assignment Operators
• Type and run the following program
num1 = 4
num2 = 5
num1 += 2
res = num1 + num2
res += num1
print("Result is" , res)

• Output
Result is 17
39
Operator precedence
Operations with the higher precedence should be
performed first in the calculation.
Precedence Operator Description
5 () Parentheses (grouping)
4 ** Exponentiation
3 +x, -x Positive, negative

Multiplication, division,
2 *, /, %
remainder

1 +, - Addition, subtraction
40
Operator precedence
• Type and run the following program.
a = 2
b = 3
print(1 + a * b)
print(a + a ** a)
print((a + a)** a)
print( a + a * b - b)

• Output
7
6
16
5 41
Input from the users
• To allow flexibility we might want to take the
input from the user. In Python, we have the
input() function to allow this.
• Syntax
variable = input("prompt")
– where prompt is the string we wish to display on
the screen. It is optional.
• name = input("Enter your name: ")

42
Input from the users
• Type and run the following program.
name = input("What is your name? ")
age = float(input("What is your age? "))
print()
print("Hello,", name)
print("You are", age, "years old.")
print("You will be", age+1, "next year.")

• Output
What is your name? Peter
What is your age? 17

Hello, Peter
You are 17.0 years old.
You will be 18.0 next year. 43
A big program example:
Finding the area of a triangle
# Python Program to find the area of triangle
a = float(input("Enter first side: "))
b = float(input("Enter second side: "))
c = float(input("Enter third side: "))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print("The area of the triangle is", area)

44

You might also like