0% found this document useful (0 votes)
28 views27 pages

ENGG1003 08 PythonBasics-A

This document provides an overview of Python basics including variables, types, expressions, operators, and branching statements. It explains that Python supports many data types like integers, floats, strings, and booleans. Variables are created using assignments and can be used in expressions along with operators to perform calculations. Branching statements like if/else allow executing code conditionally based on boolean expressions.

Uploaded by

蛇精男
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)
28 views27 pages

ENGG1003 08 PythonBasics-A

This document provides an overview of Python basics including variables, types, expressions, operators, and branching statements. It explains that Python supports many data types like integers, floats, strings, and booleans. Variables are created using assignments and can be used in expressions along with operators to perform calculations. Branching statements like if/else allow executing code conditionally based on boolean expressions.

Uploaded by

蛇精男
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/ 27

ENGG1003

Python Basics
Background
• Python is a computer programming language.
• We can realize computations using Python.
• Milestones:
• Python Installation and BMI calculation
• Python IDLE Interactive Shell
• Key in instructions and get results interactively in a
Read-Eval-Print Loop (REPL)

• Python Turtle Graphics and Drawing


• Python IDLE Module Editor
• Edit, Save and Run instructions in a .py script/ module file
Outline – Python Basics
• Variables

• Operators and Expressions

• Branching constructs – if: elif: else:

• Repetition constructs – for-loop


Type Name Object/Value

Musician beethoven

Painter van_gogh

Philosopher karl_marx
Type, Name and Value/ Object
• Type: for classification
• Many types have been defined and can be used readily.
• We can still define new types (as known as classes.)
• Many computing operations require type matching.

• Name: for identification; a reference to something

• Value/ Object: actual data stored


type Examples in Turtle Graphics
• Create a turtle pet and let the pet forward 100
>>> import turtle
>>> pet = turtle.Turtle()
>>> pet.forward(100)

>>> type(pet)
<class 'turtle.Turtle'>
>>> type(pet.forward)
<class 'method'>
>>> type(100)
<class 'int'>
100 is an integer-type value
according to their kinds
-- Genesis 1, Bible (NIV)

Type
• Python supports MANY types of data, such as:
• int – integers (whole numbers)
• Example int-type values: -7 , 0 , 999

• float – real numbers


• Example float-type values: -9.8 , 4.0 , 99.9

• string – some text in single or double quote pairs


• Example string-type values: "Hello" , 'Mary LAM' , 'Y' , "n"

• bool – truth values


• Only two possible values: True , False (case-sensitive, no quotes)
Floating-point numbers contain an integral part and a fractional part.
They usually bear a decimal point and some decimal places.
Simple scaling by powers of 10 can let the decimal point "float" to the left/ right.
So the man gave names to all
-- Genesis 2, Bible (NIV)

Identifier/ Name
• Names are for identification, usually meaningful words.
• Think about nouns and verbs, they are ubiquitous!
• Names usually start with a letter and form with letters, digits and _
• Some identifiers have been defined/ created already and can be
used readily
• Still, we have room to create our own names, examples:
Pythagoras, a and b are all identifiers.
COVID_death_toll = 0 math and sqrt are also identifiers.
peter_weight = 64.5 Identifiers are everywhere.

def Pythagoras(a:int, b:int):


return math.sqrt( a*a + b*b )
Variable Creation Using =
• A Python variable is for storing data, like boxes.
• A variable may vary. Its content can change over time.
• A variable bears a name, a value and a type.
• Variables are created via assignments:
studentCountENGG1003
57
56
studentCountENGG1003 = 57 (int)
air_temperature = -4.67 air_temperature
General_Manager = "Alex SZETO" -4.67
"Below zero"
studentCountENGG1003 = 56 (float)
(string)
General_Manager
air_temperature = "Below zero"
"Alex SZETO"
(string)
Expression
• Calculations and formula can be written as expressions.
Resulting value can be assigned to a variable or printed.

bodyWeight = 57
bodyHeight = 1.58
count
bmi = bodyWeight / bodyHeight / bodyHeight 1
2
3
print(bmi) (int)

Use the current value in the variable count in


count = 1
1 the expression (count + 1).
print(count)
count = count + 1
The sum is stored back (assigned) to the
variable count, thus overwriting/ updating
count = count + 1
the variable.
print(count * 2) 6
Operators in Expression
• Operators perform computation on data values in
an expression.

Basic Categories Operators

Arithmetic Operators + - * / % // **

Relational Operators == != < > <= >=

Logical Operators and not or

Membership Test Operators in not in

Not discussed here, useful set operations


Arithmetic Operators
OPERATOR MEANING (COULD BE integer OR float) EXAMPLE RESULT
7 + 2 9
+ Add two values 7.1 + 2 9.1
7 - 2 5
- Subtract two values OR minus (negation) 7.1 – 2 5.1
7 * 2 14
* Multiply two values 7.1 * 2 14.2
7 / 2 3.5
/ Division – always float results of or 8 / 2 4.0
7 % 2 1
% Modulus – remainder of a division 8.5 % 1.75 1.5
-8.5 % 1.75 0.25
7 // 2 = 3
// Floor division – kind-of "quotient" of a division -7 // 2 = -4
Actually for –ve results 7.5 // 2 3.0
7 ** 2 49
** Exponent – raising base value to the power 7.2 ** 2.0 50.41
Relational and Logical Operators
Always Result in True or False
BEWARE:
OPERATOR MEANING Assignment with = EXAMPLE RESULT
Comparison with ==
== Compare two values for equality 7 == 2 False

!= Compare two values for inequality 7 != 2 True

< Less than relation 7 < 2 False

> Greater than relation 7 > 2 True

<= Less than or equal to relation 7 <= 7 True

>= Greater than or equal to relation 7 >= 7 True

and Check if both logical statements are True 7 != 2 and 5 > 2 True

or Check if one or both logical statements are True 3 > 4 or -1 == 2 True

not Negate (flip) the truth value not 3 < 4 False


Chained Comparison: True / False
print( 3 < x and x < y and y < 10 )
is equivalent to
print( 3 < x < y < 10 )

print( x == y and y == z )
is equivalent to
print( x == y == z )
Printing on Screen
• We can print text (string) and values:
Hi, Peter !
name = 'Peter' Your weight is 57 kg
age = 21 Your BMI is 22.832879346258608
You will be 22 years old
bodyWeight = 57
bodyHeight = 1.58
bmi = bodyWeight / bodyHeight / bodyHeight
print("Hi,", name, "!")
print("Your weight is", bodyWeight, 'kg')
print("Your BMI is", bmi)
print('You will be', (age+1), "years old")
Input from User
• User may input some text (string) using input( )
name = input("What's your name? ")
print("Hi,", name, "!")

• User may input an integer, with int( ) conversion


age = int(input("What's your age? "))
print('You will be', (age+1), "years old")

• User may input a real number, with float( ) conversion


bodyWeight = float(input("What's your weight in kg? "))
print('Your weight is', bodyWeight, "kg")
Branching Statement if:
• So far, all instructions are executed sequentially.
• How to perform some operations conditionally?
• Based on a bool expression:

bool_ True
if bool_expression: expression
statement False
statement
4 spaces/ Tab here!
next_statement
next_statement
Branching Statement if:
• If condition is True, execute statement.
• If condition is False, skip statement.
• Anyway, move on to next_statement.

True
if condition: condition

statement False
statement
4 spaces/ Tab here!
next_statement
next_statement
Branching Statement if: more
• If condition is True, execute statement1 & statement2.
• If condition is False, skip statement1 & statement2.
• Anyway, move on to next_statement.

True
if condition: condition

statement1 False
statement1
statement2
4 spaces/ Tab here! statement2

next_statement
next_statement
Branching Example if:
1 score = int(input("Please enter your score: "))
2
3 if score >= 60:
4 print("Passed!")
5 print("Congratulations!")
6
7 if score < 60:
8 print("Failed!")
9
10 print("Your score is", score)
11
Please enter your score: 80 Please enter your score: 40
Passed! Failed!
Congratulations! Your score is 40
Your score is 80 20
Branching Statement if:else:
• If condition is True, execute only statement_T.
• If condition is False, execute only statement_F.
• Anyway, move on to next_statement.

if condition: False True


condition
statement_T
else: statement_F statement_T
statement_F
4 spaces/ Tab here!
next_statement next_statement
Branching Example if:else:
1 score = int(input("Please enter your score: "))
2
3 if score >= 60:
4 print("Passed!")
5 print("Congratulations!")
6 else: # remark:-
7 replaces if score < 60:
8 print("Failed!")
9
10 print("Your score is", score)

• Handles two mutually exclusive conditions.

22
Successive Conditions
if:elif:
1 year = int(input("Please enter year of study: "))
2
3 # handles multiple conditions successively
4
5 if year == 1:
6 print("Welcome, Freshman!")
7 elif year == 2:
8 print("O'camp Leader!")
9 elif year == 3:
10 print("O'camp Organizer!")
11 else:
12 print("Graduate!")

• Handles multiple mutually exclusive conditions.


23
Repetition Statement for:
• How to perform some operations repeatedly?
• Based on a range of values: from 1 to N-1.
• Variable i will take up new values, one at a time.
• The statement will repeat N-1 times.

for i in range(1, N):


statement
4 spaces/ Tab here!
next_statement
Repetition Statement for:
1 N = int(input("Please enter N: "))
2
3 for i in range(1, N):
4 print("Count", i)
5
6 print("Go!")
Please enter N: 7 Please enter N: 4
Count 1 Count 1
Count 2 Count 2
Count 3 Count 3
Count 4 Go!
Count 5
Count 6 Please enter N: 1
Go! Go!
25
Calculations in Statement for:
1 N = int(input("Please enter N: "))
2
3 for i in range(1, N):
4 print("Count", 10 + i * 2)
5
6 print("Go!")
Please enter N: 7 Please enter N: 4
Count 12 Count 12
Count 14 Count 14
Count 16 Count 16
Count 18 Go!
Count 20
Count 22 Please enter N: 1
Go! Go!
26
Summary
• Python allows us program a turtle to draw graphics
with direct instructions like forward(), left(), right().
• Python supports calculations and computations
with variables, expressions and operators.
• Key properties: types, names and values
• User interaction using print() and input().
• Branching statement if: elif: else:
• Repetition statement for:

You might also like