BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Bab 3.3 Kod Arahan – Python
https://www.w3schools.com/python/
https://www.learnpython.org/
Tanda Simbol Penerangan
‘’ Tanda petikan tunggal / single quote
“” Tanda petikan berganda / double quote
: Tanda titik berindih
() Tanda Kurungan
[] Square brackets
{} curly brackets
<> angle brackets
PYTHON keyword :
import keyword import keyword ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
print(keyword.kwlist) print(keyword.kwlist) 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Python comment
# - 只可以用 1 行的 single line comment
''' ''' – Multiple lline comment ''' 把 mulitple comment 写在这里 , 最后 end comment 要关上'''
1
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Pemboleh ubah di PYTHON
Syarat –syarat menamakan pemboleh ubah Contoh yang betul Contoh yang salah
Semua nama pemboleh ubah mesti dimulakan dengan huruf
Setelah dimulai dengan huruf , nama pemboleh ubah boleh Pelajar , pelajar, Pelajar_1 1Pelajar
mengandungi digit 0 hingga 9 .
( Tidak boleh bermula dengan digit ) nombor1 , no3 , user2 1nombor
Pemboleh ubah tidak boleh mengandungi ruang kosong (space)
NamaPelajar Nama
Huruf besar adalah berbeza dengan huruf kecil. Ingat nama Pelajar
pemboleh ubah case sensitive. Pelajar
pelajar !Bilik , @Bilik , #Bilik ,
Pemboleh ubah tidak boleh mengandungi aksara istimewa peLajar Bilik$, Bilik% , Bilik-2-3 ,
kecuali underscore _ No=bilik,
No_bilik Bilik+2, Bilik& ,Bilik^1
Nama yang dipilih tidak boleh terdiri daripada KEYWORD Bilik_3
Aturcara True , False , If , else , def ,
global, not , and, with, or,
none, break, import,
pass,return, class, def ,
del,continue, for, while,
except,is,
2
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Python Sintaks Segmen Kod Output :
print ( ) print ( " Hello , Python ." ) Hello , Python .
这个是用来 paparkan 你要 mesej “所有写在“” 里面的 mesej 会 papar 出来” Cikgu Amanda
28
# add data into print()
Markah anda ialah : 80
name = "Cikgu Amanda"
umur = 28 Markah anda ialah :80
print ( name )
print ( umur ) ASK Senang!ASK Senang!ASK Senang!
@@@@@
当我们 print mesej 和 markah = 80
pembolehubah 时 不一样的 jenis print ("Markah anda ialah :", markah )
data , 我们用 , 来 combine .
markah = 80
, 会有空格 space 一格。 print ("Markah anda ialah :" +
str(markah) )
如果你要 combine 两不一样的 你
用+ print ( "ASK Senang!" * 3 )
要把 pemboleh ubah convert 去 print ( "@* 5 )
String.
str( )
+ 不会有空格的
*可以 print 一个 statement 跟着你
要的次数
3
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
input ( ) # User input data # User keyin Python , output as
当我们 keyin data 一定要 assign 一 yourname = input ( "Please enter your Please enter your name. :Python
个 pembolehubah 来 store 我们 name. :" ) Hi Python Nice to meet you.
keyin 的 data. print ("Hi", yourname , "Nice to meet
如果 input 前面没有 you.") # User keyin 10 , output as
int( ) , float() Umur = int ( input ("Please enter your Please enter your age :10
直接 assign jenis data string age :") ) Hi , your are 10 years old.
Convert keyin 的 data 是 interger - print ("Hi , your are " , Umur , " years
整数 nombor positif , nombor old.") Markah Ujian 1 :35.68
Markah Ujian 2 :45.976
negatif Purata : 40.828
要 int ( ) Purata : 40.83
Purata : 40.82800
Convert keyin 的 data 是 float 有小 Markah1= float( input ("Markah Ujian
数点 1 :") ) format 的好处可以把零补上当成你要的小数点,如
要 float ( ) Markah2= float ( input ("Markah Ujian 果数目本身的小数点少于你要的小数点 output
2 :") )
format ( Purata , ".02f" )) Purata = (Markah1 + Markah2) / 2 36.78
".02f" - 里面的数字代表你要的小 print( "Purata : " , Purata )
数点。 print( "Purata : " , format ( Purata , Output 出来不会 3 个小数点, 因为数目本身原本只
".05f" 就是 5 个小数点 ".02f" )) 有 2 个小数点。
print( "Purata : " , format ( Purata ,
round ( ) ".05f" ))
markah = 36.78
round ( pembolehubah, 小数点的数目)
print( round(markah,3))
round ( ) 和 format( ) 的分别,
round 如果数目的小数点少不会把小
数点零不上
4
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Python Sintaks Segmen Kod Output :
30 lebih besar daripada 5
if condition : a = 30
b=5
你所有的在这个 condition
一定要 Indent 进去 if a > b :
print ( a," lebih besar daripada", b )
else :
else :
所有的 if- else 后面一定要放 : print ( b," lebih besar daripada", a)
else 不用放 condition 的
Condition 通常我们 compare if a > b :
> 大过 print ( a," lebih besar daripada", b )
< 小过
>= 大过和相等于 if b > a :
<= 小过和相等于 print ( b," lebih besar daripada", a)
= = 两个的等值 一样
!= 两个的等值 不 样
为啥要 indent 进去?
这是 indent 代表了
所有在这个 indent 进去的 coding 都属
于在 if 这个里面。
5
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
if condition : markah = float(input("Masukkan markah # User keyin 50 , output as
elif condition : anda :"))
else : if markah >84 : Masukkan markah anda :50
50.0 - Gred D
( 通常老师建议你们 set 最大的 range print( markah ," - Gred A")
在第一个 condition ) elif markah >69 :
print( markah ," - Gred B")
elif markah >59 :
print( markah ," - Gred C")
elif markah >49 :
print( markah ," - Gred D")
elif markah >39 :
print( markah, " - Gred E")
else :
print( markah, " - Gred F")
markah = float(input("Masukkan markah
anda :"))
if 84 < markah <= 100 :
print( markah ," - Gred A")
elif 70 <= markah < 85 :
print( markah ," - Gred B")
elif 60 <= markah < 70 :
print( markah ," - Gred C")
elif 50 <= markah < 60 :
print( markah ," - Gred D")
elif 40 <= markah < 50 :
print( markah, " - Gred E")
else :
print( markah, " - Gred F")
6
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Python Sintaks Segmen Kod Output : ( 1 次)
for a in range ( henti ) print("Ulangan (mula)") Ulangan (mula) ( 2 次)
for a in range (5): 0 ( 3 次)
这个 for 会从 0 开始算起第一次 loop 重复到 1 ( 4 次)
henti 的次数就停。 print(a) 2 ( 5 次)
3
4
end= “” for a in range (5): 0,1,2,3,4,
print(a , end="," )
这个的意思就是在 for loop 里面每一次重复
gelung loop , 不会 print new line 会一直接着
下去, 如果 “ ” 这个里面放 simbol 就会把
simbol print 进去。
for a in range ( mula, tamat ) print("\nUlangan ( mula, tamat)") Ulangan ( mula, tamat)
for b in range ( 1,6): 1
这个 for( 开始算起, loop 重复到 tamat 的 2
次数就停 tamat ) print(b) 3
一到 tamat 的次数就直接停所有不会 loop 4
( 6 就是停 , 所以就只 print 到 5 ) 5
for a in range ( mula, tamat, langkau ) # langkau 跳过几个 Ulangan ( 1, 10, 2)
1
for a in range ( 开始,停, 跳越过次数 ) print("\nUlangan ( 1, 10, 2)") 3
for c in range (1, 10 , 2) : 5
7
print(c) 9
7
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
逆序 c = "abcd" a
i=0 b
for a in range ( mula, tamat, langkau ) c
for i in c : d
逆序就是 langkau 的 value 是 negatif print(i) 10 hingga 0
10
print ( "10 hingga 0 ") 9
for a in range ( 10,0,-1): 8
7
print ( a ) 6
5
4
3
2
1
8
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Print Pattern For Segmen Kod Output :
print(("* "*1))
Python Sintaks print(("* "*2)) *
print(("* "*3)) **
print 星星的 pattern ,普通的 print(("* "*4)) ***
print(("* "*5)) ****
通常老师建议放 “ * space 一个空格 ” for a in range (1,6) : *****
print 出来的 pattern 比较好看 *
print(("* "*a)) **
***
****
*****
如果我们用 alignment center, left , right for a in range (1,7) :
.center( 你要从那个 space 的位置开始的数目) print(("* "*a).center(12))
*
**
***
****
*****
******
( 看你最后一行要 print 多少次拿来
乘 2 就是你 space 的数目, 记得你要
print( “* ” ) * 然后加 space
9
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
for a in range (1,6) :
print(("* "*a).rjust(10))
for a in range (1,6) :
print(("* "*a).ljust(10))
10
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Python Sintaks Segmen Kod Sifir 2 : Output :
while condition : a=1 1 x2= 2
print ("Sifir 2 :") 2 x2= 4 所有在 while
所有在 while 的 condition 只要 true 就 while ( a < 13 ) : 3 x2= 6
会一直会重复的 loop , 一直 loop 到 4 x2= 8 loop
condition false 才停。 print ( a, " x 2 = ", a*2 ) 5 x 2 = 10
a=a+1 6 x 2 = 12
break print ("Tamat") 7 x 2 = 14
( 直接停 Loop, 跳出 looping . ) ( indent 出来的就是 while 的 condition false 接着 8 x 2 = 16
的要做的 ) 9 x 2 = 18
10 x 2 = 20
# loop from 1 till 3 only cause if setting 11 x 2 = 22
when I run till 3 will stop 12 x 2 = 24
Tamat
i=1 1
while i < 6: 2
print(i) 3
if i == 3:
break
i += 1
11
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
String FORMAT
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
12
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
isdigit()
isidentifier() Returns True if all characters in the string are digits
islower()
isnumeric() Returns True if the string is an identifier
isprintable()
isspace() Returns True if all characters in the string are lower case
istitle()
isupper() Returns True if all characters in the string are numeric
join()
ljust() Returns True if all characters in the string are printable
lower()
lstrip() Returns True if all characters in the string are whitespaces
maketrans()
partition() Returns True if the string follows the rules of a title
replace()
rfind() Returns True if all characters in the string are upper case
Joins the elements of an iterable to the end of the string
Returns a left justified version of the string
Converts a string into lower case
Returns a left trim version of the string
Returns a translation table to be used in translations
Returns a tuple where the string is parted into three parts
Returns a string where a specified value is replaced with a specified value
Searches the string for a specified value and returns the last position of where it was
found
13
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
rindex()
Searches the string for a specified value and returns the last position of where it was
rpartition() found
rsplit()
rstrip() Returns a tuple where the string is parted into three parts
split()
splitlines() Splits the string at the specified separator, and returns a list
startswith()
swapcase() Returns a right trim version of the string
title()
translate() Splits the string at the specified separator, and returns a list
upper()
zfill() Splits the string at line breaks and returns a list
Returns true if the string starts with the specified value
Swaps cases, lower case becomes upper case and vice versa
Converts the first character of each word to upper case
Returns a translated string
Converts a string into upper case
Fills the string with a specified number of 0 values at the beginning
14
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Tips untuk format String :
Python Sintaks Segmen Kod Output :
Masukkan nombor digit sahaja : df
isdigit() n = ( input("Masukkan nombor digit sahaja : ")) df bukan digit !
Masukkan nombor digit sahaja :-3
while ( n.isdigit() == False ) : -3 bukan digit !
print(n, "bukan digit !") Masukkan nombor digit sahaja :0.9
n = ( input("Masukkan nombor digit sahaja :")) 0.9 bukan digit !
Masukkan nombor digit sahaja :50
print(n,"ialah digit.") 50 ialah digit.
15
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Tips untuk mengirakan nombor binary
Python - segmen kod
nom_perpuluhan = (input("Masukkan nombor perpuluhan : "))
while ( nom_perpuluhan.isdigit() == False) :
nom_perpuluhan = (input("Masukkan nombor perpuluhan : "))
nom_perpuluhan = int(nom_perpuluhan)
hasil_baki = nom_perpuluhan
jawapan =""
while ( hasil_baki != 0 ) :
baki = hasil_baki % 2
hasil_baki = hasil_baki // 2
print ( str(nom_perpuluhan) , "\t"+chr(0x00F7) , "2" , "\t=", str(hasil_baki),"\tbaki", str(baki))
nom_perpuluhan = hasil_baki
jawapan=str(baki)+jawapan
print("Nombor perduaan : "+ jawapan)
Tips : chr(0x00F7) 是 ASCII code character
16
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
Contoh Output :
Masukkan nombor perpuluhan : 25
25 ÷ 2 = 12 baki 1
12 ÷ 2 = 6 baki 0
6 ÷ 2 = 3 baki 0
3 ÷ 2 = 1 baki 1
1 ÷ 2 = 0 baki 1
Nombor perduaan : 11001
17
BAB 3 Kod Arahan Python T2 Pn Lai Yen Wei
jawapan =""
while ( hasil_baki != 0 ) :
baki = hasil_baki % 2
hasil_baki = hasil_baki // 2
print ( str(nom_perpuluhan) , "\t"+chr(0x00F7) , "2" , "\t=", str(hasil_baki),"\tbaki", str(baki))
nom_perpuluhan = hasil_baki
jawapan=str(baki)+jawapan
print("Nombor perduaan : "+ jawapan)
Tips : chr(0x00F7) 是 ASCII code character
Contoh Output :
Masukkan nombor perpuluhan : 25
25 ÷ 2 = 12 baki 1
12 ÷ 2 = 6 baki 0
6 ÷ 2 = 3 baki 0
3 ÷ 2 = 1 baki 1
1 ÷ 2 = 0 baki 1
Nombor perduaan : 11001
18