Location via proxy:
[ UP ]
[Report a bug]
[Manage cookies]
No cookies
No scripts
No ads
No referrer
Show this form
Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
220 views
Basic Python Programming 1st Edition
Uploaded by
Farina Luhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Basic Python Programming 1st Edition For Later
Download
Save
Save Basic Python Programming 1st Edition For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
220 views
Basic Python Programming 1st Edition
Uploaded by
Farina Luhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Basic Python Programming 1st Edition For Later
Carousel Previous
Carousel Next
Save
Save Basic Python Programming 1st Edition For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 117
Search
Fullscreen
BASIC PYTHON PROGRAMMING 1* Edition (July 2022)Authors Siti Noor Aishah Binti Mohammad Norbaizura Binti Mokhtar Johari Ahmad Bin Ghazali POLITEKNIK KUCHING SARAWAK MINISTRY OF HIGHER EDUCATION KM22, JALAN MATANG, 93050 KUCHING, SARAWAK. Phone No. _: (082) 845596/7/8 Fax No. (082) 845023 E-mail poliku.info@poliku.edu.my Website http://www.poliku.edu.my/ Copyright © 2022 Politeknik Kuching Sarawak ISBN 978-967-2953-S7-9 All rights reserved. No parts of this publication may be copied, stored in form or by any means, electronic, mechanical, photocopying and recording or otherwise or by any means for reproduced without the prior permission of Politeknik Kuching Sarawak. National Library of Malaysia Cataloguing in-Publication Data Siti Noor Aishah Mohammad BASIC PYTHON PROGRAMMING / Siti Noor Aishah Binti Mohammad, Norbaizura Binti Mokhtar, Johari Ahmad Bin Ghazali. — 1% Edition (July 2022), ISBN 978-967-2953-57-9 1. Python (Computer program language). 2, Programming languages (Electronic computers). 3, Scripting languages (Computer science), 4, Programming (Computers). 5. Government publications--Malaysia. I. Norbaizura Mokhtar. I. Johari Ahmad Ghazali. Ill, Title. 005.133 Published by: Politeknik Kuching Sarawak Ministry Of Higher Education Printed by: PC HOTSTAMPING BOOKBINDIN 20 Green Road, Jalan Cloud Estate, 93150 Kuching, Sarawak G SERVICES,PREFACE Basic Python Programming takes you from zero experience to a complete understanding of the key concepts, edge cases, and how to use Python for real-world application development. You'll move progressively from the basics to work with larger, more complex applications. After completing this book, you'll have the skills you need to dive into an existing application or start your own project. As we work with the language, you'll leam about control statements, delve into controlling program flow, and gradually work on more structured programs via functions. As you settle into the Python ecosystem, you'll leam about data structures and study ways to correctly store and represent information. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing. By the time you complete this book, you'll have built up an impressive portfolio of experience and armed yourself with the skills, you need to tackle Python projects in the real worldABSTRACT BASIC PYTHON PROGRAMMING By SITI NOOR AISHAH BINTI MOHAMMAD NORBAIZURA BINT! MOKHTAR JOHAR! AHMAD BIN GHAZALI Basic Python Programming module introduces students to the essential's skills of Python Programming language. The module provides knowledge on learning to design, write, debug, and run programs encoded in the Python language. Students will learn about the essential elements of programming and how to construct basic Python programs. Through this module, students will cover expressions, variables, functions, logic, and conditional, which are foundational concepts in computer programming. It will also teach students how to use Python modules, which enable students to benefit from the vast array of functionality that is already a part of the Python language. These concepts and skills will help students to begin to think like a computer programmer and to understand how to go about writing Python programs. This module uses Python 3, which is specifically designed to help beginning programmers learn quickly. Python IDLE allowing students to start writing and running small programs immediately. Keywords : Python Programming, essential elements of programming, Python 3Contents Chapter 1: Introduction to Basic Operations in Python 441 Downloading and Installing Python 1 1.2 Start Working with Python 1-2 1.3 Literals in Python 134 print( ) function 2-3 13.2 Literals, 14 Operators in Python 144 Basic Operators 3 142 Arithmetic Operators 3-4 143 Unary operator and binary operator 4 144 Operator Precedence 5 145 Operators and parentheses 5 Lab Activities 1 6-8 1.5 Variables for Python 154 Naming Variables 9 152 Assign Variables 9 153 Python Keywords 9-10 Lab Activities 2 11-14 1.6 Python Literals 16.1 input( ) Functions 15 16.2 Typecasting 15-16a Lab Activities 3 17-19 Chapter 2: Making Decisions in Python 21 Relational Operators in Python 20 2.2 Conditional Operators in Python 224 Condition statements 20-22 Lab Activities 4 23-28 222 The use of layout manager 29-30 Lab Activities 5 31-36 23 List For Python 37-39 Lab Activities 6 40-48 Chapter 3: Writing Functions in Python 3.4 Python Functions 344 Built-in functions 49-51 3.1.2 User-defined functions 51-52 3.2 Local and Global Scope in Function 52 Lab Activities 7 53-603.3 Tuples and Dictionaries within Python 3.3.1 Tuples 61-62 3.3.2 Dictionaries 62-65 Lab Activities 8 66-73 Chapter 4: Python Modules and Exception Handling 41 Python Random Module 74-77 42 Python Math Module 77-79 43 Python Platform Module 79-81 44 Create and Access a Python Package 81-82 Exercises 83 45 Exception Handling 84-85 Lab Activities 9 86-91 Chapter 5: Python and MySQL 5.1 STRUCTURED QUERY LANGUAGE 92 5.2 Data Types in MySQL 92 5.3 XAMPP Installation 92 - 96 Lab Activities 10 97 - 108 Referencesintroduction to Basic Operations in Python CHAPTER 1 INTRODUCTION TO BASIC OPERATIONS IN PYTHON 1.1 DOWNLOADING AND INSTALLING PYTHON There are several ways to get a copy of python. But it depending on the operating system and system type was used by the machine. All users can download a copy at (www.python.org/downloads/ site. From the website, you need to choose the appropriate version that suitable with your machine. Start to download .exe file and follow all the steps. Leave the default settings the installer suggests and look at the checkbox named Add Python 3.x to PATH and check it. 1.2. START WORKING WITH PYTHON Python installation contains a very simple but extremely useful application named IDLE. IDLE is an acronym: Integrated Development and Learning Environment. To start your work, you need the following tools: 1. Editor: Support in writing the code Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 1 | Page(UCHAPTER!) Introduction to Basic Operations in Python 2. Console: Can launch a newly written code. 3. Debugger: Able to launch a code step by step and allowing programmer to inspect it at each moment of execution 1.3 LITERALS IN PYTHON 1.3.1 __print()) function print ("I Love Python Programming") The print( ) command, which is one of the easiest directives in Python, simply prints out a line to the screen. print ("1 Love\nPython Programming") Through this code, there is a character look like this \n. The backslash ( \) is called escape character. The letter n placed after backslash comes from the word newline. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 2 | Page(UCHAPTERT!) Introduction to Basic Operations in Python 13.2 print ("I Love") print ("Python") print ("Programming") There are three (3) lines and all of them are strings. To put them all on one line, the arguments will separated by commas. It shown like below. print ("I Love", "Python", "Programming™) Otherwise, use ent above. print ("I Love", end="") print ("python", end="") print ("Programming") " at the end of argument also give the same solution as Literals Literal are notations for representing some fixed values in code. There are different types of literal: 1. Integers are numbers written without a fractional component. 2. Floats is designed to represent and to store the numbers that have a non- empty decimal fraction. 3. Strings are used to process text. 4, Boolean used to represent a very abstract value which makes use of only ‘two distinct values: True and False, denoted as 1 and 0. 1.4 OPERATORS IN PYTHON 14.1 1.4.2 Basic Operators ‘An operator is a symbol of the programming language, which is able to operate on the values. The operators which are associated with the most widely recognizable arithmetic operations: HLM Arithmetic Operators Exponentiation ‘A ** (double asterisk) sign is an exponentiation (power) operator. Classical mathematics prefers notation with superscripts, just like this: » Coding Example: x ** y Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 3 | Page(UCHAPTER!) Introduction to Basic Operations in Python 1.43 Multiplication ‘An * (asterisk) sign is a multiplication operator. Coding Example: x * y Divi A / (slash) sign is a divisional operator. The result produced by the division operator is always a float. Coding Example: x /y Integer Division A// (double slash) sign is an integer divisional operator. The results are always rounded. Coding Example: x //y Remainder (Modulo, %! The result of the operator is a remainder left after the integer d value left over after dividing one value by another. Coding Example: x % y ion. It is the Ad The addition operatoris the + (plus) sign, which is fully in line with mathematical standards. Coding Example: x + y ion Subtraction The subtraction operator is the - (minus) sign. Coding Example: x- y Unary operator and binary operator Aunary operator is an operator with only one operand. Example: -x, + Abinary operator is an operator with two operands. Example: x+y, x-y. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 4 | Page(UCHAPTER) Introduction to Basic Operations in Python 1.4.4 Operator Precedence Python precisely defines the priorities of all operators, and assumes that operators of a larger (higher) priority perform their operations before the operators of a lower priority. Any operators of equal precedence are performed in left-to-right order. Here is the order of precedence of the Python operators, from lowest to highest: (Operator Description or Boolean OR and Boolean AND not Boolean NOT =<, <=, >, >=, is, is not comparisons, identity I bitwise OR * bitwise XOR & bitwise AND <> bit shifts +, addition, subtraction “LM multiplication, division, floor division, modulo unary positive, unary negation, 1, bitwise negation exponentiation 1.4.5 Operators and parentheses Parentheses can be used to change the natural order of a calculation. In accordance with the arithmetic rules, sub expressions in parentheses are always calculated first. Prepared by SITI NOOR AISHAH BINTI MOHANIMAD | TMK PKS 5 | Pageintroduction to Basic Operations in Python NAME REG. NUM. DATE 6 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(WGHAPTERD)) Introduction to Basic Operations in Python Activity 1 #This is a simple Python Program print ("Programming is great fun!!!") Activity 2 print ("Programming is great fun!") print ("I can't get enough of it!") Activity 3 print ("Programming is") print ("great fun!") Activity 4 print ("these are our top sellers: \n") print ("Computer games\nCo!fee\n") print ("Aspirin") Activity 5 print ("These are our top sellers: \n") print ("\tComputer games\n\tCoffee\n") print ("\tAspirin") Activity 6 print("These are our top sellers" , "Computer games" , "Coffee" “Aspirin") Activity 7 print ("The works of Wolfgang include " , end= print ("the following " , end="") print ("he Turkish March " , end="") print ("and Symphony No. 40", print ("in G minor") “y Activity 8 print("l + 5=", (145) ) print("l-5=", (1-5) ) print("l x 5=", (1 * 5) ) print ("1 power of 5=", (1 ** 5) ) print("1 / 5 =", (1/5) ) print ("L // 5 print ("1 § 5 » f/f 5) ) ", as 5)) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 7 | Page(UCHAPTER!) Introduction to Basic Operations in Python Exercises: 1. Write a program that will display your name on the first line; your street address on the second line; your city, state and ZIP code on the third line; and your telephone number on the fourth line, Place a comment with today’s date at the top of the program. Test your program by entering, compiling, and running it. 2. What's the output of the following: a print((2 ** 4), (2 * 4.), (2 * 4)) b. print ((-2 / 4), (2 / 4), (2 // 4), (-2 // 4d) © print((2 8-4), (2% 4), (2 ** 3 -** 2)) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 8 | Page(UCHAPTER!) Introduction to Basic Operations in Python 1.5. VARIABLES FOR PYTHON 15.1 15.2 15.3 Variable have name and value. There are some rules to follow in order to give a name to a variable. 1, Must be composed of upper-case or lower-case letters, digits, and the character of underscore. 2. Must begin with a letter. 3. Uppercase and lowercase letters are treated as different. 4, No spaces or special characters are allowed. 5. The name of the variable must not be any of Python's reserved words. Samples of acceptable variable | Samples of unacceptable variable names: YES names: NO Grade Grade(Test) GradeOnTest GradeTest#i Grade_On_Test 3rd_Test_Grade GradeTest Grade Test (has a space) Assign Variables Avariable comes into existence as a result of assigning a value to it. The following code demonstrates how a simple variable can be created. 10 Use the name of the desired variable, then the equal sign ( =) and the value you want to put into the variable. The first of them creates a variable named a, and assigns a literal with an integer value equal to 10. This process is called an assignment operation. Python Keywords False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JT PKS, 9 | Page(UCHAPTER!) Introduction to Basic Operations in Python while with yield They are called keywords or reserved keywords. The meaning of the reserved word is predefined, and must not be changed in any way. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 10 | Pageintroduction to Basic Operations in Python NAME REG. NUM. DATE 11 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(WGHAPTER'D) Introduction to Basic Operations in Python Activity 1 #This program has a variable value = 5 print ("this value is" , value) Activity 2 price = 29.75; tax = 1.76; total = 31.51; print ("The price of the item" , "is" , price) print ("The tax is" , tax) print ("The total is" , total) Activity 3 bool = True; print (bool) bool = False; print (bool) Activity 4 letter = 'A'; print (letter) letter = 'B'; print (letter) Activity 5 a= 10; b = 20; c= 25; a= 25; print ("a + » (a+b) ) print ("a - 1 (a-b)) print ("a * » (arb) print ("b / 1 (bf ay) print ("b & 1 (bead) print ("c § 1 (c%a)) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 12 | Page(WGHAPTER) Introduction to Basic Operations in Python Activity 6 a= 10; atea print ("dit =", a) print("H+d =", +d) fdt++ not support because it is not python syntax Activity 7 basePay = 25 reqularkours = 40 overtimePay overtimeHours = 10 regularWages = basePay * regularHours overtimeWages = overtimePay * overtimeHours totaliages = regularWages + overtimeWages print ("Wages for this week are RM" , totalWages) Activity 8 books = 15; months = 6; booksPerMonth = books/months print("I read an average of" , booksPerMonth , " ooks per month.") Activity 9 books = 15; months = 6; booksPerMonth = books/months print ("I read an average of" , booksPerMonth , "books per month.") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTNK PKS 13 | Page(UCHAPTERT!) Introduction to Basic Operations in Python Exercises 1. Write statements that do the following. a. Declare a variable named letter. b. Assign the String “I Love Python Programming” to the letter variable. ¢. Display the contents of the letter variable. 2. Write a program that declares the following: A String variable named name, an integer variable named age and a double variable named annualPay. Store your age, name and desired annual income as literals in these variables. The program should display these values on the screen in a manner similar to the following; My name is Rentap, my age is 26 and T hope to earn RM100000.0 per year. 3. Write a program that stores the integers 62 and 99 in variables, and stores the sum of these two in a variable named total. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 14 | Page(UCHAPTER!) Introduction to Basic Operations in Python 1.6 PYTHON LITERALS 1.6.1 1.6.2 put{ ) Fun The input () function comes with an optional parameter such as string. Itallows user to write a message before the user input. The result of the input () function is a string. It is not an integer or a float. Code example Source Code input ("Ente: print ("Your course is your course: » course) Output Enter your course: Final Output Ent hon thon Programing gramming When the input () function is called, the program's flow is stopped, the prompt symbol keeps blinking until the user has entered an input and/or pressed the Enter key, Typecasting Typecasting is a process where users convert the data type of an object to required data type. Typecasting can be done by assigning the required data type function to the expression. Code example Source Code aye print("Value: " , nun er) 1", Type: " , type number = float (number) print ("Value: ", number , ", Type: ", type(number)) number = int (number) print ("Value: ", number , ", Type: " , type (number)) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 15 | Page(UCHAPTERT!) Introduction to Basic Operations in Python Output Value: 17 tstet> value: 17 s 'float'> value: 17, Hintt> Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTNK PKS 16 | Pageintroduction to Basic Operations in Python NAME REG. NUM. DATE 17 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(WGHAPTER'D) Introduction to Basic Operations in Python Activity 1 str = input ("Enter the data: ") print ("You have entered: ", str); Activity 2 str = input ("Enter the data: ") num = int (str) print ("You have entered num); Activity 3 numl = int (input ("Number num2 = int (input ("Number num3 = int (input ("Number ") ") ™) sum = numl + num2 + num? print ("The sum =", sum) Activity 4 num = int (input ("Enter an integer ")) square = num * num print ("fhe square of" , aum, "is" , square) Activity 5 first = int(input("Enter first integer: ")) second = int(input ("Enter second integer: ")} sum = first + second print("The sum of" , first , "plus" , second, "is" , sum) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 18 | Page(UCHAPTER!) Introduction to Basic Operations in Python Exercises: 1. Acar’s miles-per-gallon (MPG) can be calculated with the following formula: MPG = Miles driven / Gallons of gas used Write a program that asks the user for the number of miles driven and the gallons of gas used. It should calculate the car's miles-per-gallon and display the result on the screen. 2. Write a program that asks the user to enter three test scores. The program should display each test score, as well as the average of the scores. 3. Write a program that plays a word game with the user. The program should ask the user to enter the following: — — His or her name - — His or her age = Thename of acity — The name of a polytechnic = Aprofession — type of animal — — Apet’s name After the user has entered these items, the program should display the following story, inserting the user’s input into the appropriate locations: where once was a person named NAME who lived in CITY. At the age of AGE, NAME went to college at COLLEGE. NAME graduated and went to work as a PROFESSION. n, NAME adopted a(n) ANIMAL named PETNAME, They both lived happily ever after! Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 19 | Page(CHAPTER 2) Making decisions in Python CHAPTER 2 MAKING DECISIONS IN PYTHON 2.1 RELATIONAL OPERATORS IN PYTHON Relational operators or also called as comparison operators are used to compare values either it returns True or False according to the condition. The table below illustrates how the comparison operators work. (Assume that a= 0, b= ) and c= Operator Description returns if operands’ values are equal, and False otherwise returns True if operands’ values are not equal, and False otherwise > True if the left operand’s value is greater than | a>b #False the right operand's value, and False otherwise | b>c #True < True if the left operand's value is less than the |a
=b # False or equal to the right operand’s value, and False | a>=c # True otherwise b>=c # True True if the left operand's value is less than or a<=b #True equal to the right operand's value, and False | a<=c # True otherwise b<=c # False 2.2. CONDITIONAL OPERATORS IN PYTHON 2.2.1 Condition statements if statement Example 1) x= 10 # condition print ("x is equal te 10") # Executed if the condition is True. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | TMK PKS, 20 | Page(GHAPTER2)) Making decisions in Python Example 2: x= 10 if x > 5: # condition one print ("x is greater than 5") # Executed if condition one is True. if x < 10: # condition two print ("x is less than 10") # Executed if condition two is True. # condition three print ("x is equal to 10") # Executed if condition three is True. if-else statement Example x= 10 if x < 10: # Condition print ("x is less than 10") # Executed if the condition is True. else: print ("x is greater than or equal to 10") # Executed if the condition is False. Example 2: x= 10 ifx>5: # True print ("x > 5") ifx> 8: # True print ("x > 8") if x > 10 print # False "x > 10") else: print ("else will be executed") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 21 | Page(CHAPTER 2) Making decisions in Python if-elif-else statement Example 1: x= 10 x= 1 print 10") elif x > 15 print ("x > 15") elif x > 10 print ("x > 10") @ executed") if x>5: # True # False nested: x == 6") True nested: else") else: print ("else") Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMK PKS, 22 | Page(WGHAPTER2)) Making decisions in Python NAME REG. NUM. DATE 23 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(GHAPTER2)) Making decisions in Python Activity 1 scorel = float (input ("Enter score #1: ")) score2 = float (input ("Enter score #2: ")) score3 = float (input ("Enter score #3: ")) average = (scorel + score? + score3) / 3 print ("The average is ", average) if average > 80: print ("fhat's a great score.) Activity 2 scorel = float (input ("Enter score #1: ")) score? = float (input ("Enter score #2: ")) score3 = float (input ("Enter score #3: ")) average = (scorel + score? + score3) / 3 print ("The average is ", average) if average > 80: print ("That's a great score.") print ("End of AVERAGE SCOR# program.") Activity 3 num = int (input ("Enter an integer: ")) if num <0: print ("The number ",num," is negative.") else: print ("The number ",num," is zero or positive.") print ("Good bye for now.") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 24 | Page(WGHAPTER2)) Making decisions in Python Activity 4 num = int (input ("Enter an integer: ")) if num < 0: print ("The number ",num," is negative.") print ("Negative numbers are less than zero print ("fhe number ",num," is zero or positive.") print ("Positive numbers are greater than zero print ("Good bye for now.") Activity 5 print ("="*40) print (" PTPTN LOAN SYSTEM") print ("="*40) student = input("Are you a Politeknik Kuching Sarawak student? (y/n): recentGrad = input("Have you got your SPM certificate? (y/n) if student if recentGzad == 'y print ("You are qualify for PEPIN loan.") else: print ("You must have SPM certificate to process your PTPTN loan.") print ("You are not qualify for PTPTN loan because you are not Politeknik Kuching Sarawak student.") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 25 | Page(WGHAPTER2)) Making decisions in Python Activity 6 print ("="*40) print (" PTPTN LOAN SYSTEM") print ("="*40) student = input ("Are you a Politeknik Kuching Sarawak student? (y/n): ") recentGrad = input("Have you got your SPM certificate? (y/n): ") if student == 'y' or student == '¥': if recentGrad == 'y! or recentGrad == 'Y': print ("You are qualify for PIPTN loan.") else: print ("You must have SPM certificate to process your PTPTN loan.") print ("You are not qualify for PTPTN loan because you are not Politeknik Kuching Sarawak student.) Activity 7 print ("="*40) print ( PIPTN LOAN SYSTEM") print ("="*40) student = input ("Are you a Politeknik Kuching Sarawak student? (y/n): recentGrad = input ("Have you got your SPM certificate? (y/n): " if (student ty! or student '¥') and (recentGrad or recentGrad == 'Y'): print ("You are qualify for PTPTN loan.") elif (student ty! or student "Y¥') and (recentGrad == 'n' or recentérad mys print ("You must have SPM certificate to process your PTPTN loan Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 26 | Page(WGHAPTER2)) Making decisions in Python else: print ("You are not qualify for PTPTN loan because you are not Politeknik Kuching Sarawak student.") Activity 8 choice = input ("Enter A, B or C if choice == 'A' print ("You entered A.") elif choice tye print ("You entered B.") tor elif choice print ("You entered ¢.") else: print ("That's not A, Bor C!") Activity 9 choice = input ("Enter A, Bor C :") if choice == 'A' or choice print ("You entered A.") elif choice 'B' or choice print ("You entered B.") elif choice 'c! or choice print ("You entered ¢.") else: print ("That's not A, B or C!") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 27 | Page(CHAPTER 2) Making decisions in Python Exercises: customers based on the table shown below. supermarket will give cash vouchers ti Purchase Amount 0-30 31-50 51-100 >100 (RM) Voucher Value 0 2 5 8 (RM) You need to develop a program that displays the value of the voucher that will give to the customer based on the purchase amount. Prompt the user about the amount of their purchased. Use python programming to build the program, 2. In order to maintain health and overcome the problem of obesity among polytechnic students, you are asked to develop a program that will display a total of proposal calories allowed for a day based on gender and age of the user. Set the way need to follow the following recommended calorie intake schedule: Gender | a a Age | ov 13-15 2690 kcal 2180 kcal 16-18 2840 kcal 2050 kcal 19-29 2440 kcal 2000 kcal 30-59 2460 kcal 2180 kcal 260 2010 kcal 1780 kcal a) Identify the required inputs, i.e. gender and age of the user. b) Identify the control processes and structures involved, ©) Identify the required output, i.e. the recommended total calorie intake for a day. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | TMK PKS, 28 | Page(CHAPTER 2) Making decisions in Python 2.2.2 Looping statements The looping control structure allows the program to perform certain steps repeatedly. Each loop performed is called an iteration, ‘Two types of looping control structure frequently used is: 1. for statement - controlled by known number of iterations. 2. while statement - controlled by circumstances and the unknown number of iterations. for statement Syntax: var in range (stop): Example: Code Program for i in range (5) print ("I love Python Programming") Output I love Programming I love Programming I love Programming I love Programming T love Python Programming Syntax: ry var in range (start,stop): Example: Code Program Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS, 29 | Page(GHAPTER2)) Making decisions in Python Syntax: for var in range (st stop, skip): Example: Code Program for i in range (1,10,2): print (i) ited Output 1 while statement Syntax: while condition: Example: Code Program pilih " while pilin == pilih = input ("Continue the program? (y/n) :") Output tinue the progr: Col ? (y/a) ty ogram? (y/n) :y Continue the program? (y/n) in Continue the Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 30 | Page(WGHAPTER2)) Making decisions in Python NAME REG. NUM. DATE 31 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(WGHAPTER2)) Making decisions in Python Activity 1 number = 1 while number <= 5: print ("Hello.") number = number + 1 print ("That's all.") Activity 2 number = 1 while number <= print ("Hello.") number += 1 print ("That's all.") Activity 3 number = 1 while number <= 5: print ("Hello.") number += 1 if number break print ("Phat's all.") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 32 | Page(WGHAPTER2)) Making decisions in Python Activity 4 count = int (input ("Enter initial value :")) Limit = int (input ("Enter limit value :")) while count <= limit: print ("Count is :", count) count += 1 print ("Done with the loop.") Activity 5 count = int (input ("Enter initial value :")) Limit = int (input ("Enter Limit value while count <= limit: print ("Count is :", count) count #21 if count break print ("Done with the loop.") Activity 6 for prog in “python: print (prog) ‘Activity 7 for a in range (5): print (a) print ("Finally finished.") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 33 | Page(WGHAPTER2)) Making decisions in Python Activity 8 for a in range(2,5): print (a) Activity 9 for a in range (2,20,3): print (a) Activity 10 for number in range (2,5): numberSquared = number*number print (number, " : ", numberSquared) Activity 11 print ("I will display a table of numbers and their squares.") » maxValue = int (input ("How high should i go? while maxValue < 1: print ("Please enter positive number only!! maxValue = int (input ("How high should i go? print ("Number \t Number Squared") print ("="#20) for number in range (maxValue) : numberSquared = number*number print (number, "\t", numberSquared) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 34 | Page(WGHAPTER2)) Making decisions in Python Activity 12 repeat, jum_skor = 0 while repeat == '¥': print ("This program calculates the average of three test scores.") for score in range (3): skor = float (input("Enter score :")) jum_skor += skor average = jum_skor / 3 print ("The average is ",average,".") print ("™) print ("Would you like to average another set of test scores?") ) repeat = input ("Enter ¥ for Yes or N for No Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 35 | Page(GHAPTER2)) Making decisions in Python Exercises: Build a program using looping statement that displays a Multiplication Table when the user enters a number. The following display is an example of the output for your program. Output *** MULTIPLICATION TABL Enter your number:3 multiplication table for your number 3 is: 2. Design a program that stores an employee's ID number, gross pay, state tax, federal tax and FICA withholdings. The program should have a method that calculates the employee's net pay, as follows: net pay = gross pay — state tax — federal tax — FICA withholdings Alloop in the program should ask user for the employee ID number, gross pay, state tax, federal tax, and FICA withholdings. The loop should terminate when 0 is entered for the employee number. After the data is entered, the program should display totals for gross pay, state tax, federal tax, FICA withholdings and net pay. Input Validation: Do not accept negative numbers for any of the items entered. Do not accept values for state, federal, or FICA withholdings that are greater than the gross pay. If the state tax + federal tax + FICA withholdings for any employee are greater than gross pay, print an error message and ask the user to re-enter the data for that employee. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS, 36 | Page(CHAPTER 2) Making decisions in Python 2.3. LIST FOR PYTHON The is a type of data in Python used to store multiple objects. It is an ordered and mutable collection of comma-separated items between square brackets. my_list = [ foreate a list named my list Python has adopted a convention stating that the elements in a list are always numbered starting from zero, This means that the item stored at the beginning of the list will have the number zero, The value inside the brackets which selects one element of the list is called an index. Example: ny list = "I am a string", 4,9,10 Since lists are indexed, lists can have items with the same value. Example: my_list "I a string", 4,9,10,4] Access list by referring to the index number: Coding my_list TI, None, print (my_list[3]) print (my List [-1]) Output Tam a string 0 The Len () function may be used to check the list's length: Coding my_list = ["white", "purpl print (en (my_list)) = Tle", *yellow™, “green” del my_list(2] print (len(my_list)) Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 37 | Page(CHAPTER 2) Making decisions in Python Output To add an item to the list Coding TI, None! my_list{1] = '2" print (my list) , “first") nd ("last") print (my_list) Output Ti, ‘2, True, ‘I ama string’, t 56, Ol True, 'I ama string’, 256, 0, ist elements and lists can be deleted: Coding my_list = (1, 2, del my list(2] print (my_list) del my list print (my_list) Output Ti, 2, 4 NameExror 7. ~\App! back (most cent call last) e1_10448/110. cal\Temp/ipyk 48957.py in
y_list > 6 print (my_li meError: name ‘my list' is not defined Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | TMK PKS 38 | Page(CHAPTER 2) Making decisions in Python 's can be iterated through using the for loop: Coding my_list = ["white”, “purple”, “blue”, "yellow", "green™ for color in my list: print (color) Output white purple blue yellow Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 39 | Page(WGHAPTER2)) Making decisions in Python NAME REG. NUM. DATE 40 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(WGHAPTER2)) Making decisions in Python Activity 1 stuff = {1 #Adding values in List stuff = stuff + [23] stuff + [38] stufé + [742] stuff stuff #Display values in List print ([stuff[0], stuff[1], Activity 2 stuff = [] a-1 print ("Enter the value") print ("="*25) Adding values in List for i in range(5 print ("Value #",a, nilai = int (input ( stuff = stuff + [nilai) azati #Display values in List print ( ist of stuff print ( Activity 3 stuff = [] print ("Enter the value") *25) print ( stuff) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS, 41 | Page(GHAPTER2)) Making decisions in Python #Adding values in List while a <= 5: print ("Value #",a,"2 ") nilai = int (input ("")) stuff stuff + [nilai] azatl print ( print ("List of Stuff: ",stuff) Activity 4 stuff - [] asl print ("Enter the value") print ("="#25) #Adding values in List for i in range(5): print ("Value #",a,": ") nilai = int (input ("™)) stuff = stuff + [nilai) asatl display value one by one print ( nombor = iter (stufé) for i in range(len(stuff)): print (next (nombor) } Activity 5 stuff = [] a1 b=0 print ("Enter the value") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 42 | Page(GHAPTER2)) Making decisions in Python print ("="*25) #Adding values in List for i in range (5): print ("Value #",a," ailai = int (input ("")) stuff stuff + [nilail azatl display value one by one print ("™) nombor = iter (stuff) while b < len(stuff): print (next (nombor}) biel Activity 6 month = 1 day = [31, 28, 31, 30, 31, 30, hari = iter (day) for i in range (len(day)): print ("Month ",month," has month += 1 Activity 7 month = 1 day = [31, 28 31, 30, 31, 30, hari = iter (day) while month len (day) print ("Month ",month," has 1 month + 31, 31, 30, 31, 30, ",next (hari)," days. 31, 31, 30, 31, 30, ";next (hari)," days. 31) "y 31) " Prepared by SITI NOOR AISHAH BINTI MOHANIMAD | JTMK PKS, 43 | Page(WGHAPTER2)) Making decisions in Python Activity 8 array = [-20, 19, 1, 5, -1, 27, 19, 5) max = array[0] for i in range (len(array)): if array(i] > max: max = array[i] print ("fhe maximum of this list is: ",max) Activity 9 sample = ["Old Value", 1, 3, 5] print (sample) sample(0] = "New Value" print (sample) Activity 10 sample = ["Old Value", 1, 3, 5] print (sample) sample [0] = "New Value" print (sample) sample = sample + ("Added Value") print (sample) Activity 11 sample = ("Old Value", 1, 3, 5] print (sample) sample [0] = "New Value" print (sample) sample = sample + ["1"] Prepared by SITI NOOR AISHAH BINTI MOHANIMAD | JTMK PKS,(WGHAPTER2)) Making decisions in Python print (sample) del sample(2] fdelete by index print (sample) sample.remove(1) #delete by existed value from the lowest index print (sample) sample. remove(5) #delete by existed value print (sample) Activity 12 number = [1, 18, a, -21 sorting number permanently number. sort () print (number) sorting number temporarily sorted (number) Activity 13 number = [1, 18, 5, 1, -2] reverse order temporarily number [11-1] Activity 14 number = [1, 18 5, 1, ~2] length of list Len (number) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 45 | Page(GHAPTER2)) Making decisions in Python Activity 15 number = [1, 18 5, 1, -2] Method 1 total = number[0] + number[1] + number[2] + number[3] + number[4] print ("Total 1 :",total) #Method 2 total = sum(number) print ("fotal 2 :",total) #Method 3 total = 0 for i in range (Len(number)): total += number[i] print ("Total 3 :",total) Method 4 total = 0 for i in number: total += i print ("Total 4 :",total) iMethod 5 total = 0 iso while i < len(numbez): total += number[i] Gel print ("fotal 5 :",total) Activity 16 number = [1, 18, 5, 1, -2] total = 0 for i in range (Len(number)): Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 46 | Page(WGHAPTER2)) Making decisions in Python ifGd continue total += number [i] print ("Total :",total) Activity 17 petrol = ["Diesel", "Ron 95", "Ron 97") for jenis in petrol: "Ron 95 if jenis continue print ("type of petrol available: ",jenis) Activity 18 siapa = ["Girlfriend", "Boyfriend", "Wife", "Eusband") kataNama = ["Saya", "Awak", "Mereka"] for a in siapa: for b in kataNama: print (a,b) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 47 | Page(CHAPTER 2) Making decisions in Python Exercises 1. Ask the user to enter a list containing numbers between 1 and 12. Then replace all of the entries in the list that are greater than 10 with 10. 2. Write a program that asks the user to enter a length in feet. The program should then give the user the option to convert from feet into inches, yards, miles, millimeters, centimeters, meters, or kilometers. Say if the user enters a 1, then the program converts to inches, if they enter a 2, then the program converts to yards, etc. While this can be done with if statements, it is much shorter with lists and it is also easier to add new conversions if you use lists. Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 48 | Page(UCHAPTERS]) Writing Functions in Python CHAPTER 3 WRITING FUNCTIONS IN PYTHON 3.1 PYTHON FUNCTIONS Functions can be divided into 1. Built-in functions 2. User-defined functions Both have the same function, which is to perform a special task. A parameter is a variable used by function. Parameters are used for 1. Receive and store that data sent to function while called. 2. Return the data to the statement instruction, function, procedure or another arrangement that call the function 3.1.1 Built-in functions Built-in functions are functions that exist and are stored within programming language library. Source code for each built-in function cannot be seen by the programmer. Each built-in function has a descriptive name means, the name that can reflects the task of the built-in function in question. Built-in name function cannot be changed. Tasks performed by a built-in function supplied are limited and simple. The example of built-in function: sum(), max(), min( ) and index( ) Example Quest Get the name of the student who obtained the highest and lowest total marks. Student Name Math | Sc BM BI ‘Ali bin Abu 70 78 79 95 Bakar bin Ahmad 40 48 88 98 ‘Aminah bin Amin 85 58 82 99 Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | TMK PKS, 49 | Page(UCHAPTERS]) writing Functions in Python sum( ) function: Program Cod stud_name = ["Ali bin Abu", "Bakar bin Abmad","Aminah bin Anin"] markah_ali = [70,78,79,95] markah_bakar = (40, 48,88, 98] markeh_amineh = [85,58,82,99] jum sum (markab_ali) jum_bakar = sum(markah_bakar) jum_eminah = sum(markah_aminah) markah = [jum_ali,jum_bakar, jum_aminah] for i in range (len(stud_name)): print ("fotal marks for", stud_name [i], "i ",markah[i]) output: Total m Total marks for Bakar bin Ahmad is 274 © for Ali bin Abu is 322 Total m for Aminah bin Amin is 324 max{ ) and min( ) function: Program Code (Continue): markah_rendah = min(markah) markah_tinggi = max (markah) print " markah_rendah) print ("Highest Marks:",markah tinggi) owest Mark Output (Continue) : 27 324 Lowest Mark: Highest Marks: index( ) functioi Program Code (Continue) : indek_rendah dex (markah_rendah) indek_tinggi = markah. index (markah_tinggi) print (" re:", indek_rendah) print ("Index for highest score:", indek_tinggi) ex for lowest sc Output (Continue) : Index for lowest score: Index for high score Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 50 | Page(UCHAPTERS]) writing Functions in Python 3.1.2 inal Result: Program Code (Continue) : print ("Lowest Scor nt ("Highest § ", stud_name[indek_rendah]) rei", stud_name[indek_tinggi]) output (Continue) : : Bakar bin Ahmad Aminah bin Amin Highest User-defined functions A user-defined function is a set of instructions written by programmer to perform a special task that will be repeated in the main program. User-defined function written should also have a descriptive name, that is, a name that can reflect his duties. Usually, user-defined functions are written due to the absence of built-in functions which can meet the requirements of the programmer. Like b function, user-defined function capable of accepting arguments and returns a value to the program that called it. Writing a user-defined function starts with defining the function at the beginning of the program. After that, the user can call the function each time a special assignment is a function needs to be implemented in the program. Syntax: def function_name (parameter) : function body return value Example: Prograi def tambah(a,b): total = a+b total ret © = int (input ("Enter number #1:")) d= int (input ("Enter number #2:")) e = tambah(c,d) print ("Total Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 51 | Page(UCHAPTERS]) writing Functions in Python Output: inter number #1:1 inter number #2:2 Total : 3 3.2 LOCAL AND GLOBAL SCOPE IN FUNCTION Global variables are those which are not defined inside any function and have a global scope whereas local variables are those which are defined inside a function and its scope is limited to that function only. =. —_ Global variable for i in range (5): b= 10 c= 1.5 Local variable def contoh(d): e=d-10 Local variable return e Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 52 | Page(WGHAPTERS)) writing Functions in Python NAME REG. NUM. DATE 53 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(WGHAPTERS)) Writing Functions in Python Activity 1 def getlength(): keyword return digunakan bg tujuan pengembalian nilai return length fnama pembolehubah sama seperti dim fungsi getlengta() length = 20 print (getlength()) Activity 2 def getlength (length) : keyword return digunakan bg tujuan pengembalian nilai return length nama pembolehubah TIDAK sama seperti dim fungsi getlength() a= 30 print (getlength (a)) Activity 3 def getlength(): 4cetakan nilai dilaksanakan secara langsung dr fungsi print (length) length = 40.5 fmemanggil fungsi untuk tujuan paparan output getlength() Activity 4 def getlength (Length) : #eetakan nilai dilaksanakan secara langsung dr fungsi print (length) a= 50.5 get length (a) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 54 | Page(WGHAPTERS)) Writing Functions in Python Activity 5 def getlength(): return length length = int (input ("Masukkan nilai : ")) print ("Nilai yang telah dimasukkan :",getlength(}) Activity 6 def getlength (length) : return length a = float (input ("Masukkan nilai : ")) print ("Nilai yang telah dimasukkan :",getlength(a)) Activity 7 def getArea(): return length * width length = 20 width = 10.5 print (getArea (}) Activity 8 def getArea (Length, width) : return length * width 1 = 10 10.5 print (getArea(1,w)) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTIK PKS, 55 | Page(WGHAPTERS)) Writing Functions in Python Activity 9 def getLength (len, widt) : return getArea(len,widt) def getArea (length, width) : print (length * width) 1= 40 w= 40.5 getLength (1, w) Activity 10 def getArea(): return length * width print ("Kira Luas Segiempat") print ("-"*40) length = float (input ("Masukkan ukuran panjang: " width = float (input asukkan ukuran lebar: ")) print ("Keluasan Segiempat ialah :",getArea()) Activity 11 def getArea (length, width) : return length * width print ("Kira Luas Segiempat") print ("-"*40) 1 = float (input ("Masukkan ukuran panjang: ")) w = float (input ("Masukkan ukuran lebar: ")) print ("Keluasan Segiempat ialah :",getArea(1,w)) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTNK PKS 56 | Page(WGHAPTERS)) writing Functions in Python Activity 12 def gajifour(jam,bayar) : return jam * bayar def gajitahun (gajitahun): return gajiTahun / 52 opt = input ("Enter H for hourly pay vate or ¥ for yearly pay rate: if opt == 'H' or opt == tht: j = int (input ("How many hours were worked?: ")) b = float (input ("What is the hourly pay rate?: ")) print ("The weekly gross pay is RM",gajifour(j,b)) elif opt "Yy! or opt tyes gt = float (input ("What is the annual salary?: ")) print ("The weekly gross pay is RM", gajiTahun(gt)) else: print ("Invalid selection!!! Activity 13, def datainput (): return input ("Enter H for hourly pay rate or Y for yearly pay rate: ") def pilinan(jwpn if jwpn tate ‘HY or jwpn j = int (input ("How many hours were worked? » b = float (input ("What is the hourly pay rate?: ")) print ("The weekly gross pay is RM",gajiHour(j,b)) elif jwpn == '¥" or jwpn gt = float (input ("What is the annual salary?: ")) print ("The weekly gross pay is RM",gajifahun(gt)) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 57 | Page(WGHAPTERS)) Writing Functions in Python else: print ("Invalid selection! def gajidour (jam,bayar) : return jam * bayar def gajivahun (gajifahun): return gajitahun / 52 gef maing: opt = dataTnput () pilihan (opt) main () Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 58 | Page(UCHAPTERS]) Writing Functions in Python Exercises: You are a member of the organizing committee book Fair. You are as: data on: Total Name ‘Story Book Exercise Book Reference Book Ali 5 6 4 ‘Abu 1 7 4 Bakar 8 4 8 2. Total number of books purchased by school pupils; i. asawhole. according to the type of material. b. The type of reading material most liked by school children. 2. The teacher asks you to produce a calculator program able to perform four basic operations, namely add, subtract, multiply and divide by two integer numbers entered by user program. To solve this problem, you need to: a. Construct THREE (3) functions based on the following requirements. i. menu( ) function is used to display menu ji, _user_option( ) function is used to accept user input for the selected menu. ili, _cetak() function is a function to perform the selected operation and display the output. b. Input: Operation options from the calculator menu and enter two numbers. c. Apply looping and selection statements. Expected Output: Calculator Menu 1. Add 2. Substract 3. Multiply 4. Divide Your Choice [1 Enter number 1 Enter number #2: 24527 Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | TMK PKS, 59 | Page(UCHAPTERS]) writing Functions in Python 2. 3. 4 Enter numbe Enter number #2:9 Calculator Menu Add Substract Multiply Divide Your Choice [1 to 5]:2 #15 9=-4 culator Menu Add Substract Multiply Divide Your Choice [1 to 51:5 Thank you for usin Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JT PKS, 60 | Page(UCHAPTERS]) writing Functions in Python 3.3 TUPLES AND DICTIONARIES WITHIN PYTHON 3.3.1. Tuples Syntax: empty_tuple = ( ) A tuple is an immutable sequence type. Immutable means there is no any modifications on tuple contents can be done. Tuples prefer to use parenthesis and its values separated by commas. Each tuple element may be of a different type. Example: tuple_one = (1,2,4,8) If the tuple only consist one element, the element must end with a comma. Example: one_elene: There are several things can tuples do: 1, __Ien{) function - returns the number of elements contained inside. 2. + operator - can join tuples together. 3. * operator - can multiply tuples. 4, _ inand not in operators - work in the same way as in lists. Example: Coding my_tuple = (1, 10, 100) tl = my tuple + (1000, 10000) t2 = my_tuple * 3 print (Len (t2)) print (t1) print (t2) print (10 i print (-10 1 my_tuple) in my_tuple) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 61 | Page(UCHAPTERS]) Writing Functions in Python Output (1, 10, 100, 1000, 10000) (1, 10, 100, 1, 10, 100, 1, 3.3.2. Dictionaries A dictionary is a set of key-value pairs. Each key must be unique and it is not possible to have more than one key of the same value. A key may be any immutable type of object. It can be a number (integer or float), or even a string. Syntax: empty_dictionary = ( kamus = (keys:values} The list of pairs is surrounded by curly braces, while the pairs themselves are separated by commas, and the keys and values by colons. Example 1: [dictionary = {"cat":"chat", “dog":"chien™) ‘| phone_numbe: "suzy! :22657854310} empty dictionary = { # Print the values here. print (dictionary['cat")) print (phone_numbers['Suzy"]) Output chat 22657854310 Example 2: Coding dictionary = ("cat":"chat", "dog": "chien"} words = ['cat', 'lion'] Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTNK PKS 62 | Page(UCHAPTERS]) writing Functions in Python for word in words if word in dictionary: print (word, "->", dictionary[word]) else: print (word, "is not in dictionary") Output cat -> chat lion is not in dictionary If the expression too big or lengthy, keep it vertically aligned. Example: dictio teat" "dog": keys{ ) method Method named keys( ) returns an iterable object consisting of all the keys gathered within the dictionary. Example: Coding "cat": "chat", "dog": "chien", "horse": "cheval" for key in dictionary. keys () print (key, "->", dictionary(key]) Output horse -> cheval dog -> chien cat -> chat Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 63 | Page(UCHAPTERS]) writing Functions in Python values( ) method Method named values( ) which works similarly to keys(), but returns values. Example: Coding a for french in dictionary.values(): n) pri Output cheval chien chat Adding a new key Example 1; Coding dictionary dog": "chien", "horse": "cheval" dictionary['swan'] = 'cygne print (dictionary) Output Teat': ‘chat’, ‘dog’: ‘chien’, ‘horse’: ‘cheval’, ‘swan’: ‘eye Example 2: Coding dictionary = { "chat" "dog": "chien", "horse": "cheval" Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | TMK PKS, 64 | Page(UCHAPTERS]) writing Functions in Python dictionary. in": print (dic "eygne"}) Output Yeat': ‘chat’, ‘dog’: ‘chien’, ‘hors "swan": 'cygne! Removing a key Example: Coding a onary "horse": "cheval" del dictionary['dog! print (dictionary) Output {Teat': ‘minou', ‘horse’: ‘cheval'} "horse": "cheval" dictionary['cat'] = 'minou' print (dictionary) Output Teat': ‘mi ‘chien’, ‘horse’: ‘cheval’) Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | TMK PKS, 65 | Page(WGHAPTERS)) Writing Functions in Python NAME REG. NUM. DATE 66 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(WGHAPTERS)) writing Functions in Python Activity 1 #initialize tuple sampTuple = () print (sampTuple) Activity 2 tuple values sampTuple = (3, 7, 4, 2) print (sampTuple) Activity 3 ftuple one value sampTuple = (3,) print (type (sampTuple) } Activity 4 print selected tuple sampTuple = (3, 7, 4, 2) #sampTuple[indexs mula : indeks akhir), cetak dr indeks mula hingga indeks sblm indeks akhir print (sampTuple[1:3)) Activity 5 #print selected tuple sampTuple - (3, 7, 4, 2) print (sampTuple[:2]) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 67 | Page(WGHAPTERS)) Writing Functions in Python Activity 6 fexisted tuple sampTuple = (3, 7, 4, 2) fnew tuple addTuple = ('Aishah',) newTuple = sampTuple + addTuple print (newLuple) Activity 7 ftuple index sampTuple = (7, 3, 4, 3, 2) print (sampTuple. index (3)) Activity 8 #tuple count same value sampTuple = (3, 7, 4, 3, 2) print (sampTuple.count (4)) Activity 9 #print value tuple one by one sampTuple = (3, 7, 4, 3, 2, ‘Aishah") for i in range (len(sampTuple)): print (sampTuple(i]) Activity 10 # Creating an empty dict using empty brackets wordFrequency = {} # Creating an empty dict using dict() wordFrequency = dict () Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 68 | Page(WGHAPTERS)) Writing Functions in Python Activity 11 wordFrequency = { "Hello" 7, "hi": 10, "there" : 45, mat" : 23, "this" : 77 ) print (wordFrequency) Activity 12 ListofStrings - ["Hello", "hi", "there", "at", "this"] wordFrequency = dict.fromkeys(listofStrings,0 ) print (wordFrequency) Activity 13 listefstrings = ["Hello", "hi", "there", "at", "this") ListefInts = (7, 10, 45, 23, 77] # Merge the two lists to create a dictionary wordFrequency = dict( zip(listofStrings, listofints }) print (wordFrequency) Activity 14 word_freq = { Prepared by SITI NOOR AISHAH BINT MOHANIMAD | JT PKS, 69 | Page(WGHAPTERS)) Writing Functions in Python ar rate over the dictionary using for loop for key in word_freq value - word_frea{key] print (key, ": ", value) Activity 15 word freq # modify the dictionary word_freq["hi"] = 90 print (word_freq) Activity 16 # Dictionary of string and int word freq = ( “Hello”: 56, Nat": 23, “eest": 43, “chis": 78 key = "test? # python check if key in dict using "in" if key in word_freq: print (f"¥es, key: '{key}' exists in dictionary") else: print (£"No, key: '{key}' does not exists in dictionary") Prepared by SITI NOOR AISHAH BINT MOHAMMAD | JTIK PKS.(WGHAPTERS)) Writing Functions in Python Activity 17 # Dictionary of string and int word _freq = ( value = 43 # python check if value exist in dict using "in" & values() if value in word freq.values() : print (f"¥es, Value: '(value}' exists in dictionary") else: print (f"No, Value: '{value}' does not exists in dictionary") Activity 18 # Dictionary of strings and int word freq dict = { Hell 36, at": 23, est": 13, this": 43 , # Deleting an item from dictionary using del del word_freq_dict[‘at'] print (word_freq dict) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 71 | Page(WGHAPTERS)) writing Functions in Python Activity 19 # List of tuples listofTuples = (("Riti" , 11), ("Aadi" , 12), ("Sam" , 13), ("John" , 22), ("Eucy" , 90)) # Convert a list of tuple to dictionary studentsDict = dict (listofTuples) print (student sDict) Activity 20 # Create first dictionary dict] = { 'Ritika': 5, 'Sam': 7, 'John’ : 10 } # Create second dictionary dict? = {'Aadi': 8,'Sam': 20,'Mark' : 11} # Merge contents of dict2 in dicti dict1.update (dict2) print (‘Updated dictionary 1 :') print (dictl) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 72 | Page(UCHAPTERS]) writing Functions in Python Exercises: Convert this table using Dictionary and display the content using print{ ) function and a for loop. EmployeeName | EmployeelD Gender Location Department ‘Abdul Abbas 11 Male Kuching Marketing Lily Hui 112 Female Sibu HR Ramasamy 113 Male Miri Technical Patrick 114 Male Miri Marketing Wahidah 115 Female Kuching Technical ‘Amrita 116 Female Kuching ‘Admin 2. Write a program that uses a dictionary that contains ten user names and passwords. The program should ask the user to enter their username and password. If the username is not in the dictionary, the program should indicate that the person is not a valid user of the system. If the username is in the dictionary, but the user does not enter the right password, the program should say that the password is invalid. If the password is correct, then the program should tell the user that they are now logged in to the system. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTIMK PKS, 73 | PageCHAPTER’) Python Modules and Exception Handling CHAPTER 4 PYTHON MODULES AND EXCEPTION HANDLING 4a PYTHON RANDOM MODULE Python Random module is an in-built module of Python which is used to generate random numbers. 1, random. randint () - is used to generate random integers between the given range. Syntax: randi start, end) Program: © random andom.randint ndom number between 5 and 15 is", rl) r2 = random.randint (-10, -2) print ("Random number between -10 and -2 is", 12) Output: Random numb Random numb T between 5 and 15 i between -10 and -2 is -9 2, random. random() - is used to generate random floats between 0.0 to 1. Syntax: random, random) Program: from random import random print (random ()) Output: 0. 0537253444448 7 698 Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 74 | Page(UGHAPTER'2)) Python Modules and Exception Handling 3. random. choice () - is used to return a random item from a list, tuple, or string. Syntax: random. choice (sequence) Program: ¥ import random mport random a random value from the list (1, 2, 3, 4 5, 6 print (random. choice (1ist1)) # prints a random item ring = "geeks" print (random. choice ( rom the string tring)) # prints a random item from the tuple tuplel = (1, 2, 3, 4, 5) print (random. choice (tuple1)) Output: 4, random. shuffle() - is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Syntax: random. shuffle (sequence) Program: ¥ import the random module mport random # declare a list sample_list = [1, print ("Original list : ") print (sample_list) # first shuffle Prepared by SITI NOOR AISHAH BINTI MOHANIMAD | JTRAK PKS. 75 | Page(UCHAPTER'2)) Python Modules and Exception Handling random, shuffle (sample_list) print ("\nAfter the print (sample_list) irst shuffle :") second shuffle random. shuffle (sample_list) print ("\nAfter the second shuffle : ") print (sample_list) Output: Original list 1, 2, 3, 4 second shuffle 2, 8) 4, Vy 3) 5. randrange () - a function that can generate random numbers from a specified range and also allowing rooms for steps to be included. Syntax: randrange () Program: mport random # Using randrange() to ge te numbers from 0-100 print ("Random number from 0-100 is : ",end="") print (random. randrange (100)) # Using randrange() to generate numbers from 50-10 print ("Random number from 5 print (zandom. randrange (50,100) ) 00 is # Using randrange() to generate numbers from 50-100 skipping print ("Random number from 50-100 skip 5 is : ",end="") print (random, randrange (50, 100,5)) Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMIK PKS 76 | Page(CHAPTER) Python Modules and Exception Handling Output: Random number from 0-100 is : 98 Random number from 50-100 is : 71 Random number from 50-100 skip 5 is 4.2 PYTHON MATH MODULE Python provides the math module to deal with such calculations. Math module provides functions to deal with both basic operations such as addition (+), subtraction (-), multiplication (*), division (/) and advance operations like trigonometric, logarithmic, exponential functions. 1, math. pi - provides a more precise value for the pi. Syntax: math.pi Program: # Import math Library import math # radius of the circle # value of pie pie = math.pi # area of the ci print (pie * r * r) ‘Output: 50.26548245743669 Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | TMK PKS 77 | PageCHAPTER’) Python Modules and Exception Handling 2. math. factorial() to find the factorial of a number in a single line of the code. Syntax: math. factorial () Program: import math # returning the factorial of 5 print ("The factorial of 5 is: ", print (math. factorial (a)) Output: The factorial of 5 is : 120 3. math. pow() - is used to find the power of a number. Syntax: math. pow (x,y) Program: math imp. print ("The value of print (math.pow(3, Output: value of 3**4 is : 81.0 Prepared by SITI NOOR AISHAH BINTI MOMANIMAD | TI PxS 78 | Page(UGHAPTER'2)) Python Modules and Exception Handling 4, math. £sum() - is used to find sum between some range or an iterable. Syntax: math. fsum (sequence) Program: . 09) print (math. fsum(arr)) Output: i1.0 7.99 4.3. PYTHON PLATFORM MODULE The Platform module is used to retrieve as much possible information about the platform on which the program is being currently executed, 1, platform.processor () - to display platform processor. Syntax: platform. process Program: ¥ import module import platform # displaying platform processor print ("Platform processor:', platform.processor ()) Outpul Platform processor: Intel64 Family @ Model 165 Stepping 2, Genuinetnte Prepared by SITI NOOR AISHAH BINTI MOMANIMAD | TI PxS 79 | PageCHAPTER’) Python Modules and Exception Handling 2, platform.architecture() —to display platform architecture. Syntax: platform.arenitecture() Program: Import pl tiorm # displa print ("PL form.architecture ()) Output: Platform architecture: ('64bit', 'WindowsPE") 3. platform.machine () - to display machine type. Syntax: platform machine () Program: # displaying print ("Machine ype platform.machine ()) Output: Machine type: ANDed 4, platform. system() - is used to display the name of the operation system on the current device being used to run the program. Syntax: platform. sy Program: mport platform print (‘Operating system:' form.system(}) Output: Operating system: Windows Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | TMK PKS. 80 | Page(UCHAPTER'2)) Python Modules and Exception Handling 5. platform.uname() - returns a tuple that stores information regarding the system Syntax: platform. anaive () Program: mport platform # displaying system info print ("System info:', p uname_result (system='Windows', node="DESKTOP— EOFAGHM', release='10', version='10.0.19043", machine="AMD64") 4.4 CREATE AND ACCESS A PYTHON PACKAGE Packages are a way of structuring many packages and modules which helps in a well- organized hierarchy of data set, making the directories and modules easy to access. A module can contain multiple objects, such as classes, functions, etc. Physically, a package is actually a folder containing one or more module files. Follow this step to create a package. 1. Create a new folder named mypackage. 2. Inside mypackage folder, create modules named greet.py and functions.py with following code: greet.py def SayHello (name) : print ("Hello ", name) functions.py def sum(x,y): return x+y def average (x,y): return (x+y) /2 Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMIK PKS 81 | Page(CHAPTER) Python Modules and Exception Handling def power (x,y): return x**y . Test the package using following code. (Create the code outside mypackage folder) import mypackage om mypackage import greet greet .SayHello("Aishah") = functions .power (3,2) print ("power (3,2) +", x) Compile and run the code. Expected output: Hello Aisha power (3,2) : 9 Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMIK PKS 82 | Page(UCHAPTER'2)) Python Modules and Exception Handling Exercises: Create TWO modules as described as follows: 1. calculate.py - import math module - has TWO functions i. cale_power() - using pow() method from MATH module ji, sum_list() - using fsum() method from MATH module 2. numbers.py - import random module - has THREE functions i. power_num() - generate first number as an argument for calc_power{) with range numbers of (1-10) {integers only) ji, power_num2() - generate second number as an argument for calc_power{) with range numbers of (1-10) (integers only) ili, list_numbers() - generate a list that has 7 numbers as arguments for sum_list() with range numbers of (0-100) (integers only) Create main.py to = import modules calculate and numbers - invoke functions power_num1{) and power_num2() and print the random integer 1. and random integer 2. Then print the results of cale_powerl). - invoke function list_numbers() and print the generated random numbers of a list. Then print the result of the sum_list() Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMIK PKS 83 | Page(UGHAPTER'A)) Python Modules and Exception Handling 4.5 EXCEPTION HANDLING A runtime error will appear or appear when user-defined function, procedure or program is being executed. This type of error will result in the execution of the command code stops abruptly and an error message will be displayed Syntax: try: # It's a place to put the code that suspect is risky # and may be terminated in case of error except: is designed to handle the exception. Any part of the code placed between try and except is executed in a very special way. Any error which occurs here won't terminate program execution. Instead, the control will immediately jump to the first line situated after the except keyword, and no other part of the try branch is executed. The code in the except branch is activated only when an exception has been encountered inside the try block. Example: No exception handling ‘Ferogram Code value = int (input (‘Enter a natural number: ')) print ("The reciproc. of", value, 'is', 1/value) #Output Enter a natural number: Traceback (most recent File “main.py", line 1, in
value = int (input (‘inter a na ral number: ')) ValueError: invalid literal for int() with base 10: ' Implement exception handling FProgram Code value = int (input (‘Enter a natural numb print (‘The reciproca ae) » value, 'is', 1/value) except: print ("I do not know what to do.) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMIK PKS 84 | Page(UGHAPTER'A)) Python Modules and Exception Handling #Output Enter a natural number: a I do not know what to do. Prepared by SIT! NOOR AISHAH BINTI MOHAMMAD | JTMIK PKS 85 | Page(CHAPTER!) Python Modules and Exception Handling NAME REG. NUM. DATE 86 | Page Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTNAK PKS.(CHAPTER!) Python Modules and Exception Handling Activity 1 demo = 0; try: print (20/demo) ; except ZeroDivisionError: print ("Cannot divide by zero.") Activity 2 num = int (input ("Enter an integer: ")) try: print ("The square of ",num," is ", (num*num)); except TypeBrror: print ("You entered bad data." ); print ("Run the program again." }; Activity 3 num = 0 div =0 try: num = int (input ("Enter the numerator div = int (input ("Enter the divisor print (num," / ",div," is ", (num/div) (num8div) ) except ValueBrror: print ("You entered bad data." ) print ("Run the program again." ) except ZeroDivisionError: print ("You can't divide ", num, "by", div); Prepared by SITI NOOR AISHAH BINT MOHAMMAD | JTNAK PKS. 87 | Page(UCHAPTER2)) Python Modules and Exception Handling Activity 4 try: scorel = float (input ("Enter score #1: ")) score2 = float (input ("Enter score #2: ")) score3 ~ float (input ("Enter score #3: ")) average = (scorel 4 13 print ("the average is ", average) if average > 80: print ("Th "sa great sco: except Exception as detail: print (detail) print ("End of AVERAGE SCORE program.") Activity 5 Fopen text file fsave as buckpasser.py def methedB (divisor) : result = 12 / divisor rn result od (nilai): value = int (nilai) int ("Result is + methodB (value) ) pt ValueError: print ("Bad Input Data except ZeroDivisionError: int ("D) zero!! Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 88 | Page(CHAPTER) Python Modules and Exception Handling import buckpasser as bp " ("Enter the divis inData = inpu bp.methodA( inData } def caleInsurance (birthY. currentYear = 2000 age = currentYear - birthYear if age <1 print ("Age is: ", age) if drivenYears < 4: try: lahir = int (input ("Enter birth y: ance (lahir)) print ("Your insurance "| rate.cal except Exception as detai print (detail) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS 89 | Page(CHAPTER) Python Modules and Exception Handling Activity 7 def getArea (length, width) : return length * width pilin = input ("Masukkan Y untuk teruskan :") print ("™) while pilin 'y! or pilin = try: print ("Kira Luas Segiempat") print ("-"*40) 1 = float (input ("Masukkan ukuran panjang: ")) w = float (input ("Masukkan ukuran lebar: ")) print ("Keluasan Segiempat ialah :",getArea(1,w)) except Exception as detail: print (detail) print ( pilih = input ("Masukkan ¥ untuk terusken :") print ( Prepared by SITI NOOR AISHAH BINT MOHAMMAD | JTNAK PKS. 90 | Page(CHAPTER) Python Modules and Exception Handling Exercises: Build a Python program using condition statements for the following situation. Students will not be allowed to sit in final examination if their attendances are less than 80%. Notes: i, Set the total number of classes held for the semester = 30 ii, Prompt user to key in number of classes attended. iii, Use exception handling to manage error when the user keys in negative numbers, other character than integers and integer more than 30. iv, print the percentage of the attendance (attendance = classes attended /number of classes * 100) v. print if the student’s attendance equal and more 80% they can sit final exam else they cannot sit the final exam Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMIK PKS 91 | PageSGHAPTERS]| Python and Mysal CHAPTER 5 PYTHON AND MYSQL 5.1 STRUCTURED QUERY LANGUAGE Structured Query Language with the acronym known as SQL is used to achieve and updating data from the database. SQL is a standard programming language which is used to communicate with the database through the system database management. SQL statements used to create and modify database structure (CREATE, ALTER, DROP) and to manipulate data in table (SELECT, INSERT, UPDATE, DELETE) 5.2. DATA TYPES IN MYSQL Data type cHaR Fixed string between 0 and 255 words. CHAR used for columns containing fixed data and uniform. ‘Strings that can be changed between 0 and 255 words. VARCHAR VARCHAR is used for columns that contain data that does not uniform. TINYTEXT String with a maximum length of 255 words. TEXT String with a maximum length of 65,535 words. int Numbers in the range —2,147,483,648 to 2,147,483,647 or positive numbers 0 to 4,294,967,295. FLOAT ‘A small number that has a decimal point. DOUBLE Large numbers that have decimal points. DATE Dates in YYYY-MM-DD format. DATETIME Date and time in YYYY-MM-DD/HH: MM: SS format. TIME Time with format HH: MMI: SS 5.3 XAMPP INSTALLATION Step 1: Download XAMPP is a release made available by the non-profit project Apache Friends and available for download on the Apache Friends website. (http://www.apachefriends.org/de/download.html) Step 2: Run .exe file ‘Once the software bundle has been downloaded, start the installation by double clicking on the file with the ending .exe. Prepared by SITI NOOR AISHAH BINT! MOHAMMAD | JTMK PKS 92 | Page(UGHAPTERS]| Python and Mysal Step 3: Deactivate any anti Since an active antivirus program can negatively affect the installation process, it’s recommended to temporarily pause any antivirus software until all XAMPP components have successfully been installed. us software ‘nterere the stalin ofthe sftaare Please vit the flown ink learn sore shou he ‘tp/pachetends rg/entag-xampp-wndowshimi#ontiire Contin wth ination? Gee) es) Step 4: Deactivate UAC User Account Control (UAC) can interfere with the XAMPP installation because it limits writing access to the C: drive, so we recommend you deactivate this too for the duration of the installation process. To find out how to tur off your UAC, head to the Microsoft Windows support pages. (https://support.microsoft.com/en-us/help/17228/windows-protect-my-pe-from- viruses#) Important! Because an activated User Account Cont (UAC) on your stem ‘somefunctens of JAMPF are possibly restricted. Wh UAC please avo to Install KAMP te CiProgr Fle 6) (miaing ve permtzsions. OF eactvte UAC wth mecenig ater thi setup Getta) Step 5: Start the setup wizard After opened the .exe file (after deactivating the antivirus program(s) and taken note of the User Account Control, the start screen of the XAMPP setup wizard should appear automatically. Click on ‘Next’ to configure the installation settings. Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 93 | Page(IGHAPTERS]| Python ana Mysal Step 6: Choose software components Under ‘Select Components’, there is the option to exclude individual components of the XAMPP software bundle from the installation. But for a full local test server, use the standard setup and all available components. After making a choice, click ‘Next’ Step 7: Choose the installation directory In this next step, choose where the XAMPP software packet to be installed. For the standard setup, then a folder with the name XAMPP will be created under C:\. After chosen a location, click ‘Next’. Prepared by SITI NOOR AISHAH BINT! MOHAMMAD | JTMIK PKS 94 | Page(UGHAPTERS]| Python and Mysal Step 8: Start the installation process Once all the aforementioned preferences have been decided, click to start the installation. The setup wizard will unpack and install the selected components and save them to the designated directory. This process can take several minutes in total. Follow the progress of this installation by keeping an eye on the green loading bar in the middle of the screen. Welcome to XAMPP! XAMPP is an easy to install Apache distribution containing MySQL. PHP and Peri Prepared by SITI NOOR AISHAH BINT! MOHAMMAD | JTMK PKS 95 | PageSUGHAPTERS]| Python and Mysal Step 9: Windows Firewall blocking Firewall may interrupt the installation process to block the some components of the XAMPP. Use the corresponding check box to enable communication between the ‘Apache server and your private network or work network. Remember that making XAMPP server available for public networks is not recommended. Step 10: Complete installation Once all the components are unpacked and installed, close the setup wizard by clicking ‘on ‘Finish’, Click to tick the corresponding check box and open the XAMPP Control Panel once the installation process is finished. Completing the XANPP Setup Ward ‘Setphas rane ear AMF? oyu arose Prepared by SITI NOOR AISHAH BINT! MOHAMMAD | JTMK PKS 96 | Page(IGHAPTERS]| Python and Mysal NAME REG. NUM. DATE 97 | Page Prepared by SIT NOOR AISHAH BINTI MOHAMMAD | JTMK PKS.(GHAPTERS]| Python ana Mysal Activity 1 Database « Collation Action OC chapter jae utfBnb4_general_ci | Check privileges CO contoh utfBnb4_general_ci=:| Chock privileges O oat utf8nb4_general_ci m:| Check privleges import pymysql connection = pymysql.connect (host="localhost", user="root", passwd: create db = "CREATE DATABASE contoh" cursor = connection.cursor () cursor.execute (create db) Activity 2 import pymysq1 connection = pymysql.connect (host="localhost", use: "root", passwi cursor = connection.cursor () cursor.execute ("SHOW DATABASES") for x in cursor: print (x) Activity 3 4 Search ‘Table structure 4 Relation view # Name Type. Collation, Attributes O 1 noke P in(11) 2 Mama varchar(100) vti8mb4_general_ct 3. Jabatan vaichar(100) uttémb4_general_ci Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 98 | Page(GHAPTERS]| Python ana Mysal import pynyaq connection ",db="contoh") "localhost", use: pymysql .connect (hos cursor = connection.cursor () cursor.execute ("CREATE TABLE info (nokp INT PRIMARY KEY, nama VARCHAR (100), jabatan VARCHAR (100))") Table maklumat ©) Browse J Structure GJ sol 4 Searcn 3¢ inser YY Table structure 4 Relation view # Name Type Collation ‘Attributes Null 1 PORE A ints) No (3 2 ama Vaiciar(100) uitinb_goneral ei Yor (D3 eget varchar(100) uttamd4_general.ci Yes gama varchar(100) uifemibt_general_c Yes import pymysql connection = pymysqi.connect (host="localhost", use cursor = connection.cursor () cursor-execute ("CREATE TABLE maxlumat (nokp INT PRIMARY KEY, nama VARCHAR (100), negeri VARCKAR(100), agama VARCHAR (100)) Activity 5 import pymysql connection "localhost", use: , db="contoh") pymysql. connect (hos cursor = connection.cursor () cursor.execute ("SHOW TABLES") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 99 | Page(GHAPTERS]| Python ana Mysal for x in cursor: print (x) Activity 6 import pymysq1 connection pymysql.connect (hos passwd="", db="contoh") curser = connection "Before delete or drop table maxlumat print ("BEFORE! print (" cursor.execute ("SHOW TABLES") for x in cursor: print (x) delete table maklumat cursor.execute ("DROP TABLE IF EXISTS maklumat") print (" #list of table after table maklumat is deleted print ("APTER") print (" cursor.execute ("SHOW TABLES") for x in cursor: print (x) Prepared by SITI NOOR AISHAH BINT! MOHAMMAD | JTMK PKS 100 | Page(GHAPTERS]| Python ana Mysal Activity 7 import pymysql connection = pymysal.connect (host="localhost",user="root",passwd="", db={"contoh") cursor = connection.cursor () query = "INSERT INTO info (nokp,nama,jabatan) VALUES (%s,%s,%s)" val = ("42101","Aishah", "JTMK") cursor. execute (query, val) connection. commit () print (cursor.rowcount, “record inserted") Activity 8 import pymysql connection = pymysql.connect (hos "localhost", use cursor = connection.cursor () query = "INSERY INYO info (nokp,nama, jabatan) VALUES (Ss, %s,%s)" no_kp Anput ("No KP name = input ("Nama jab = input ("Jabatan val = (no_kp,name, jab) cursor.execute (query, val} connection.commit () print (cursor.rowcount, “record inserted") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 101 | Page(IGHAPTERS]| Python ana Mysal Activity 9 import pymysql connection = pymysal.connect (host="localhost" ,user="root",passwd="", db={"contoh") cursor = connection.cursor () query = "INSERT INTO info (nokp,nama,jabatan) VALUES (%s,%s,%s)" val = [("123","Aishah", "OTMK"), ("345", "Abu", "JKE") ] cursor.executemany (query, val) connection.commit () print (cursor.rowcount, “record inserted") Activity 10 import pymysql connection = pymysql.connect (host="localhost",user="root ",db="contoh") cursor = connection.cursor () query = "INSERT INTO info (nokp,nama,jabatan) VALUES (%s,%s,%s)" val = [1 no_kp = input ("No KP name = input ("Nama : " jab = input ("Jabatan val = val + [(no_kp,name, jab) } print ("" pilih = input ("Teruskan? (¥ - Ya) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 102 | Page(GHAPTERS]| Python and Mysal while pilib * or pilin print (" no_kp = input ("No KP name = input ("Nama jab = input ("Jabatan : print (" pilih = input ("Teruskan? (¥ - Ya) print (" val = val + [(no_kp,nane, jab) ] cursor .executemany (query, val) connection. commit () " print (cursor.rowcount, “record inserted") Activity 11 import pymysql connection = pymysq1.connect (hes localhost", use: cursor = connection.cursor () query = "SELECT * FROM info" cursor execute (query) myresult = cursor. fetchail () for x in myresul print (x) root", passw "contoh") Prepared by SIT NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 103 | Page(GHAPTERS]| Python and Mysal Activity 12 import pymysql connection pymysql.connect (hos: "root! "localhost", use: passwd="", db="contoh") cursor = connection.cursor () query = "SELECT * FROM info WHERE jabatan = %s" jab = ("OTMK",) cursor.execute (query, jab) myresult = cursor. fetchall() for x in myresult: print (x) Activity 13, import pymysql connection pymysql.connect (hos "localhost", use. cursor = connection.cursor () query = "SELECY * FROM info WHERE jabatan = 3s" jab = input ("Senarai staff mengikut Jabatan : ") cursor. execute (query, jab) myresult = cursor. fetchall () for x in myresult: print (x) Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 104 | Page(IGHAPTERS]| Python and Mysal Activity 14 import pymysql connection = pymys¢l.connect (host="localhost",user="root", passwd="", db="contch") cursor = connection.cursor () query = "UPDATE info SET jabatan = %s WHERE nokp = 4s" val = ("UKE","2") cursor.execute (query, val} connection.commit () print (cursor.rowcount, “record updated") Activity 15 import pymysql connection = pymys¢l.connect (host="localhost", use cursor = connection.cursor () query = "UPDATE info SET jabatan = %s WHERE nokp = %s" kp = input ("No KP Staf : ") jab = input ("Jabatan Terkini: ") val = (jab, kp) cursor. execute (query, val) connection. commit () print (cursor.rowcount, “record updated") Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 105 | Page(GHAPTERS]| Python ana Mysal Activity 16 import pymysql connection pymysql.connect (hos: "localhost", use: ",db="contoh") cursor = connection.cursor () query = "DELETE FROM info WHERE nokp = %s" kp = input ("No KP Staf : ") val = (kp,) cursor.execute (query, val) connection.commit () print (cursor.rowcount, “record deleted") Activity 17 import pymysql connection pymysql.connect (hos: "localhost", use: passw , d="contoh") cursor = connection.cursor () cursor.execute ("CREATE TABLE IF NOT EXISTS maklumat (nokp INT PRIMARY KEY, nama VARCHAR(100), negeri VARCHAR(100), agama VARCHAR (100) }") Activity 18 import pymysql connection = pymysql.connect (hos create_db = “CREATE DATABASE IF NOT EXISTS contch" "localhost", user="root", passw: curser = connection.cursor () cursor execute (create_db} Prepared by SITI NOOR AISHAH BINTI MOHAMMAD | JTMK PKS. 106 | Page(GHAPTERS]| Python and Mysal Activity 19 import pymysql connection = pymysql.connect (host="localhost",user="root", passwd="", db="conteh") cursor = connection.cursor () cursor.execute ("ALTER TABLE maklumat ADD COLUMN bangsa VARCHAR (100) ") Prepared by SITI NOOR AISHAH BINT! MOHAMMAD | JTMK PKS 107 | PageSGHAPTERS]| Python and Mysal Exercises: Build a Python program based on the following, 1. Build a database named customer_db. 2. Build a table named customers with fields - ID (primary key and auto-incremented), firstName, lastName, gender and location. 3. Insert THREE records in the table. 4. Display all the records. Prepared by SITI NOOR AISHAH BINT! MOHAMMAD | JTMK PKS 108 | PageSN eterences References BOOKS Chris, A. (2018). Machine Learning with Python Cookbook. Sebastopol, US: O'Reilly Media, Inc. (ISBN: 9781491989388) Code Quickly. (2020). Leam Python Quickly: A Complete Beginner's Guide to Learning Python, Even If You're New to Programming. Drip Digital LLC. (ISBN: 1951791274) Eric, C. (2018). Mastering Python Networking (2nd Edition). Birmingham, UK: Packt Publishing Limited. (SBN: 1789135990) James, T. (2020). Python Programming for Beginners In 2020: Learn Python In 5 Days with Step-By-Step Guidance, Hands-On Exercises and Solution - Fun Tutorial for Novice Programmers. Millennium Publishing Ltd. (ISBN: 1913361357) Yuxi, H. L. (2020). Python Machine Leaming by Example: Build intelligent systems using Python, TensorFlow 2, PyTorch, and scikit-learn, 3rd Edition. Packt Publishing. (ISBN: 1800209711)BASIC PYTHON PROGRAMMING ISBN 978-967-2953-57-9 9789672953579 SIT NOOR AISHAH BINTI MOHAMMAD NORBAIZURA BINTI MOKHTAR JOHARI AHMAD BIN GHAZALI Department of Information Technology and Communication Politelnik Kuching Sarawak KM 22, Jalan Matang 93050 Kuching, Sarawak. Tel: 082-845596, Fax: 082-845023 Website: http://www.poliku.edu.my/
You might also like
Wiley - Python For Everyone, 3rd Edition - 978-1-119-49853-7
PDF
0% (2)
Wiley - Python For Everyone, 3rd Edition - 978-1-119-49853-7
2 pages
The Complete C++ & Python Manual - 18th Edition 2024
PDF
No ratings yet
The Complete C++ & Python Manual - 18th Edition 2024
148 pages
Python OOP Exercises
PDF
No ratings yet
Python OOP Exercises
245 pages
Tutorialspoint Python
PDF
100% (3)
Tutorialspoint Python
444 pages
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
PDF
No ratings yet
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
5 pages
Mastering PyCharm
PDF
75% (4)
Mastering PyCharm
232 pages
Using Python Libraries
PDF
100% (1)
Using Python Libraries
101 pages
Python For Beginners. 2 Books in 1 - A Completed Guide To Master The Basics of Python Language
PDF
100% (2)
Python For Beginners. 2 Books in 1 - A Completed Guide To Master The Basics of Python Language
370 pages
Advance Python
PDF
No ratings yet
Advance Python
202 pages
Python
PDF
100% (1)
Python
191 pages
Python Sheet
PDF
No ratings yet
Python Sheet
132 pages
Python
PDF
No ratings yet
Python
9 pages
Python 3 Cheat Sheet: Int Float Bool STR List Tuple
PDF
No ratings yet
Python 3 Cheat Sheet: Int Float Bool STR List Tuple
2 pages
Super Advanced Python PDF
PDF
No ratings yet
Super Advanced Python PDF
120 pages
Comp Phys Python
PDF
No ratings yet
Comp Phys Python
194 pages
Python For Advance 3 Days With Python
PDF
No ratings yet
Python For Advance 3 Days With Python
263 pages
An Intro To Python and Algorithms
PDF
No ratings yet
An Intro To Python and Algorithms
199 pages
Learn Python With Examples
PDF
100% (3)
Learn Python With Examples
92 pages
Python Cheat Sheet (2009) PDF
PDF
No ratings yet
Python Cheat Sheet (2009) PDF
1 page
Datascience With Python
PDF
100% (1)
Datascience With Python
110 pages
The Complete Python Manual by The Complete Python Manual
PDF
No ratings yet
The Complete Python Manual by The Complete Python Manual
197 pages
Complete Guide To Python Programming
PDF
100% (1)
Complete Guide To Python Programming
114 pages
Top 100 Codes Prep Insta
PDF
No ratings yet
Top 100 Codes Prep Insta
20 pages
Python Extra Tutorial
PDF
50% (2)
Python Extra Tutorial
172 pages
DIY Cozmo Robot Expressions: Technology Workshop Craft Home Food Play Outside Costumes
PDF
No ratings yet
DIY Cozmo Robot Expressions: Technology Workshop Craft Home Food Play Outside Costumes
7 pages
Python Libraries PDF
PDF
No ratings yet
Python Libraries PDF
22 pages
Python Guide Documentation: Release 0.0.1
PDF
No ratings yet
Python Guide Documentation: Release 0.0.1
167 pages
Python Writing Algorithms
PDF
No ratings yet
Python Writing Algorithms
10 pages
Python Machine Learning Projects
PDF
No ratings yet
Python Machine Learning Projects
135 pages
Python Course by Yogesh
PDF
No ratings yet
Python Course by Yogesh
87 pages
Python Notes
PDF
No ratings yet
Python Notes
1,018 pages
Inside The Python Virtual Machine PDF
PDF
100% (1)
Inside The Python Virtual Machine PDF
126 pages
Ultimate Python Guide 1721491488
PDF
No ratings yet
Ultimate Python Guide 1721491488
225 pages
Python Roadmap
PDF
No ratings yet
Python Roadmap
28 pages
Python Notes 2020
PDF
100% (1)
Python Notes 2020
329 pages
Slither Into Python
PDF
No ratings yet
Slither Into Python
221 pages
Python Fundamentals
PDF
No ratings yet
Python Fundamentals
982 pages
Hands On Python Advanced
PDF
100% (1)
Hands On Python Advanced
896 pages
Kivy PDF
PDF
No ratings yet
Kivy PDF
29 pages
Computational Physics - Chapter 2
PDF
No ratings yet
Computational Physics - Chapter 2
79 pages
Python For Beginners - Daniel Correa Paola Vallejo
PDF
No ratings yet
Python For Beginners - Daniel Correa Paola Vallejo
408 pages
Python Automation Part 1
PDF
No ratings yet
Python Automation Part 1
138 pages
PYTHON PROGRAMMING FOR BEGINNERS A CRASH COURSE WITH HANDS-ON PROJECTS TO LEARN PYTHON CODING, GAME PROGRAMMING WITH NO CODING... (Mike Kernell)
PDF
No ratings yet
PYTHON PROGRAMMING FOR BEGINNERS A CRASH COURSE WITH HANDS-ON PROJECTS TO LEARN PYTHON CODING, GAME PROGRAMMING WITH NO CODING... (Mike Kernell)
242 pages
PYTHON Course Content - Nexson IT
PDF
100% (1)
PYTHON Course Content - Nexson IT
10 pages
00 01 Python Course Guide PDF
PDF
100% (1)
00 01 Python Course Guide PDF
148 pages
(Numpy) - Extended Cheatsheet
PDF
No ratings yet
(Numpy) - Extended Cheatsheet
8 pages
Kivy Documentation
PDF
No ratings yet
Kivy Documentation
782 pages
Python3: Introduction To Python3 Programming Language
PDF
100% (1)
Python3: Introduction To Python3 Programming Language
81 pages
Python Programming For Beginner - Jackson, Kit
PDF
No ratings yet
Python Programming For Beginner - Jackson, Kit
311 pages
Dokumen - Pub Algorithm Design Techniques
PDF
No ratings yet
Dokumen - Pub Algorithm Design Techniques
555 pages
Python Data Science Wilkinson CH
PDF
100% (1)
Python Data Science Wilkinson CH
153 pages
Python Examples Over 50 Examples Torin Foss4030 (WWW - Ebook DL - Com)
PDF
No ratings yet
Python Examples Over 50 Examples Torin Foss4030 (WWW - Ebook DL - Com)
80 pages
Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
PDF
No ratings yet
Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
27 pages
Rneklerle Python 1724763272
PDF
No ratings yet
Rneklerle Python 1724763272
90 pages
CS106-Week-02
PDF
No ratings yet
CS106-Week-02
55 pages
unit-1 python
PDF
No ratings yet
unit-1 python
118 pages
Python Module 1 Notes.docx - MODULE 1 NOTES
PDF
No ratings yet
Python Module 1 Notes.docx - MODULE 1 NOTES
29 pages
Python Introduction-1
PDF
No ratings yet
Python Introduction-1
56 pages
Basic Python
PDF
No ratings yet
Basic Python
101 pages
Record Experiment 6
PDF
No ratings yet
Record Experiment 6
69 pages
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
Wiley - Python For Everyone, 3rd Edition - 978-1-119-49853-7
PDF
Wiley - Python For Everyone, 3rd Edition - 978-1-119-49853-7
The Complete C++ & Python Manual - 18th Edition 2024
PDF
The Complete C++ & Python Manual - 18th Edition 2024
Python OOP Exercises
PDF
Python OOP Exercises
Tutorialspoint Python
PDF
Tutorialspoint Python
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
PDF
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
Mastering PyCharm
PDF
Mastering PyCharm
Using Python Libraries
PDF
Using Python Libraries
Python For Beginners. 2 Books in 1 - A Completed Guide To Master The Basics of Python Language
PDF
Python For Beginners. 2 Books in 1 - A Completed Guide To Master The Basics of Python Language
Advance Python
PDF
Advance Python
Python
PDF
Python
Python Sheet
PDF
Python Sheet
Python
PDF
Python
Python 3 Cheat Sheet: Int Float Bool STR List Tuple
PDF
Python 3 Cheat Sheet: Int Float Bool STR List Tuple
Super Advanced Python PDF
PDF
Super Advanced Python PDF
Comp Phys Python
PDF
Comp Phys Python
Python For Advance 3 Days With Python
PDF
Python For Advance 3 Days With Python
An Intro To Python and Algorithms
PDF
An Intro To Python and Algorithms
Learn Python With Examples
PDF
Learn Python With Examples
Python Cheat Sheet (2009) PDF
PDF
Python Cheat Sheet (2009) PDF
Datascience With Python
PDF
Datascience With Python
The Complete Python Manual by The Complete Python Manual
PDF
The Complete Python Manual by The Complete Python Manual
Complete Guide To Python Programming
PDF
Complete Guide To Python Programming
Top 100 Codes Prep Insta
PDF
Top 100 Codes Prep Insta
Python Extra Tutorial
PDF
Python Extra Tutorial
DIY Cozmo Robot Expressions: Technology Workshop Craft Home Food Play Outside Costumes
PDF
DIY Cozmo Robot Expressions: Technology Workshop Craft Home Food Play Outside Costumes
Python Libraries PDF
PDF
Python Libraries PDF
Python Guide Documentation: Release 0.0.1
PDF
Python Guide Documentation: Release 0.0.1
Python Writing Algorithms
PDF
Python Writing Algorithms
Python Machine Learning Projects
PDF
Python Machine Learning Projects
Python Course by Yogesh
PDF
Python Course by Yogesh
Python Notes
PDF
Python Notes
Inside The Python Virtual Machine PDF
PDF
Inside The Python Virtual Machine PDF
Ultimate Python Guide 1721491488
PDF
Ultimate Python Guide 1721491488
Python Roadmap
PDF
Python Roadmap
Python Notes 2020
PDF
Python Notes 2020
Slither Into Python
PDF
Slither Into Python
Python Fundamentals
PDF
Python Fundamentals
Hands On Python Advanced
PDF
Hands On Python Advanced
Kivy PDF
PDF
Kivy PDF
Computational Physics - Chapter 2
PDF
Computational Physics - Chapter 2
Python For Beginners - Daniel Correa Paola Vallejo
PDF
Python For Beginners - Daniel Correa Paola Vallejo
Python Automation Part 1
PDF
Python Automation Part 1
PYTHON PROGRAMMING FOR BEGINNERS A CRASH COURSE WITH HANDS-ON PROJECTS TO LEARN PYTHON CODING, GAME PROGRAMMING WITH NO CODING... (Mike Kernell)
PDF
PYTHON PROGRAMMING FOR BEGINNERS A CRASH COURSE WITH HANDS-ON PROJECTS TO LEARN PYTHON CODING, GAME PROGRAMMING WITH NO CODING... (Mike Kernell)
PYTHON Course Content - Nexson IT
PDF
PYTHON Course Content - Nexson IT
00 01 Python Course Guide PDF
PDF
00 01 Python Course Guide PDF
(Numpy) - Extended Cheatsheet
PDF
(Numpy) - Extended Cheatsheet
Kivy Documentation
PDF
Kivy Documentation
Python3: Introduction To Python3 Programming Language
PDF
Python3: Introduction To Python3 Programming Language
Python Programming For Beginner - Jackson, Kit
PDF
Python Programming For Beginner - Jackson, Kit
Dokumen - Pub Algorithm Design Techniques
PDF
Dokumen - Pub Algorithm Design Techniques
Python Data Science Wilkinson CH
PDF
Python Data Science Wilkinson CH
Python Examples Over 50 Examples Torin Foss4030 (WWW - Ebook DL - Com)
PDF
Python Examples Over 50 Examples Torin Foss4030 (WWW - Ebook DL - Com)
Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
PDF
Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
Rneklerle Python 1724763272
PDF
Rneklerle Python 1724763272
CS106-Week-02
PDF
CS106-Week-02
unit-1 python
PDF
unit-1 python
Python Module 1 Notes.docx - MODULE 1 NOTES
PDF
Python Module 1 Notes.docx - MODULE 1 NOTES
Python Introduction-1
PDF
Python Introduction-1
Basic Python
PDF
Basic Python
Record Experiment 6
PDF
Record Experiment 6