You are on page 1of 18

Python

An
Introduction
Learning Outcome

• To introduce Python programming language syntax.


• To be able to program using Python.
Hello World

print("Hello, World!")
or
print (‘Hello World’)

• Indentation
• Python uses indent to indicate code of block.
• Syntax error:
• If 5 > 10 :
print (“5 is grater than 10”)
• Comment
#This is a comment
Variable Rules

• A variable identification must start with a letter


or an underscore.
• Can not start with a number.
• Can contain alphanumeric character and
underscore.
• It is case sensitive.
Sample Variable

• Valid
uname = “Feroz”
u_age = 38
z = float(5.0)

• Invalid
u-name = “Feroz”
u age = 38
Variables

• NO specific code to declare a variable.

X = 10
Y = ”Feroz”
print (x)
print (y)

• Multiple Value
x , y , z = “Perodua”, “Proton”, “Honda”
print (x)
print (y)
print (z)
Joining words

X = “virus”
print (“Covid-19 is a “ + X)
Get the Data Type

x = 100
y = “Feroz”
print (type(x))
print (type(y))
Accept Input

• myvar = input(“Please enter a name:\n”)


• print(f ’You have entered {myvar}’)

• mynum = input(“Please enter a number:\n”)


• mynum = int(mynum)  
• print(f’You entered {mynum} and square of it is {mynum
** 2}’)
If…Else

• Equals (==): x == y
• Not Equals (!=): x != y
• Less than (<): x < y
• Less than or equal to (<=): x <= y
• Greater than (>): x > y
• Greater than or equal to (>=): x >= y
If…Else – Sample 1

x=5
y = 10
if x < y :
print (“X is less than y”)
If…Else – Sample 2

x = 100
y = 50
if y > x:
print(“y is greater than x)
else:
print(“y is not greater than x”)
Elif

x = 50
y = 50
if y > x:
print("y is greater than x")
elif y == x: #if previous conditon is not true, run this
print("x and y are equal")
If…Elif…Else

x = 100
y = 50
if y > x:
print("y is greater than x")
elif x == y:
print("x and y are equal")
else:
print("x is greater than y")
Looping - while

Example 1
x = 1
while x < 5:
  print (x)
  x += 1

Example 3 Example 4
Example 2
x = 1
x = 1 x = 1
while x < 5: while x < 5:
while x < 5:
  print (x) print (x)
  x += 1
if x == 3:    if x == 3: x += 1
break continue else:
x += 1    print (x) print(“x is no longer less than 5”)
  
Looping - For

Example 1
for x in range (10): #not including 10
  print(x)

Example 2
for x in range (2, 10): #not including 10
  print(x)

Example 3 Example 4
cars = [“perodua”, “proton”, “honda”]
for x in range (2, 10, 2): #not
for z in cars: including 10
print(z)   print(x)
Lists and Tuple

Lists - changeable
mylists = [“perodua” , “proton”, “honda”]
print(mylists)

mylists = [“perodua” , “proton”, “honda”]


mylists[1] = “bmw”
print(mylists)

Tuple – unchangeable
mylists = (“perodua” , “proton”, “honda”)
print(mylists)
Dictionary

• Ordered, changeable and not allow duplicates.

Mylists = {
“name”: “Feroz”,
“title”: “lecturer”,
“address”: 123
}
print(Mylists)

You might also like