Introduction to Python Programming D2 chap 1
Python and Artificial Intelligence
- Created by Guido van Rossum in the late 1980s.
- Design focuses on code conciseness and readability.
- Used by companies like Instagram and Spotify.
Program Development
- Algorithms can be expressed in pseudocode but computers cannot understand it.
- Python programming language is used to communicate with computers.
From Pseudocode to Programming Languages
- Example: Calculating area of a square in Python:
print("This is to find the area of a square!")
length = input("Please enter a side length for a square: ")
length = float(length)
area = length * length
print(area)
- Example: Calculating area of a square in C++:
#include <iostream>
using namespace std;
int main() {
float area, length;
cout << "This is to find the area of a square!" << endl;
cout << "Please enter a side length for a square: ";
cin >> length;
area = length * length;
cout << area;
}
Python Integrated Development Environment (IDE)
- IDE is an application with a code editor and programming-related functions.
Hello World!
- Simplest program to print "Hello World!".
Activity 4.1: Debugging "Hello World!"
Error 1
- Program Code:
print "Hello World!"
- Error Message:
SyntaxError: invalid syntax - Cause of Error: Missing brackets.
Error 2
- Program Code:
print(Hello World!)
- Error Message:
SyntaxError: invalid syntax - Cause of Error: Missing quotation marks around "Hello World!".
Error 3
- Program Code:
print("Hello World!"
- Error Message:
SyntaxError: unexpected EOF while parsing - Cause of Error: Unclosed brackets; brackets must come in pairs. Quotation marks must also come in pairs.
- Case Sensitivity: Python is case-sensitive (e.g., "Print" is different from "print").
- print() function: Prints the text within the quotation marks; the content does not affect the program's execution.
Basic Programming Concepts
- Programming languages have keywords and similar concepts.
Variables
- Most programming languages require declaring the name and data type of a variable.
- The name becomes the identifier of the variable.
Common Data Types in Python
- Integer (int): Integers (positive and negative). Examples: 288, -101
- Float (float): Integers and decimals (positive and negative). Examples: 56.5, -30.0, -0.382
- Boolean (bool):
TrueorFalse.1(True),0(False) - String (str): Series of characters. Examples: "abc", "P%ssword123", "1", "k"
Assignment Operator
- Python uses "=" to assign data to a variable.
- Example:
- Pseudocode:
length<-12 - Python:
length = 12 - Output:
<class ‘int’>
- Pseudocode:
- Variables can switch between different data types in Python.
Built-in Functions for Data Type Conversion
- int(): Converts the input to an integer (rounds down if float).
length = "12"
print(length) # Output: 12
print(type(length)) # Output: <class ‘str’>
length = int(length)
print(length) # Output: 12
print(type(length)) # Output: <class ‘int’>
- float(): Converts the input to a float.
length = 12
print(length) # Output: 12
print(type(length)) # Output: <class ‘int’>
length = float(length)
print(length) # Output: 12.0
print(type(length)) # Output: <class ‘float’>
- str(): Converts the input to a string.
length = 12.1
print(length) # Output: 12.1
print(type(length)) # Output: <class ‘float’>
length = str(length)
print(length) # Output: 12.1
print(type(length)) # Output: <class ‘str’>
Activity 4.2: Debugging Data Types
Error 1
- Program Code:
length = "12.1"
length = int(length)
- Error Message:
ValueError: invalid literal for int() with base 10: '12.1' - Cause of Error: A decimal string cannot be directly converted to an integer. Convert to float first, then to int.
length = "12.1"
length = float(length)
length = int(length)
print(length)
print(type(length))
Error 2
- Program Code:
length = "ten"
length = int(length)
- Error Message:
ValueError: invalid literal for int() with base 10: 'ten' - Cause of Error: Text in a string cannot be converted to numbers.
Constants
- Variables with fixed data, e.g., .
Arithmetic Expressions
- Store the result of an arithmetic expression in a variable:
variable = expression - Arithmetic expressions are formed by data (numbers, variables, or constants) and arithmetic operators.
Python Arithmetic Operators
| Operation | Pseudocode Operator | Python Operator | Python Example | Value of y |
|---|---|---|---|---|
| Addition | + | + | y = 1 + 2 | 3 |
| Subtraction | - | - | y = 5 – 2 | 3 |
| Multiplication | * or × | * | y = 2 * 3 | 6 |
| Division | / or ÷ | / | y = 10 / 3 | 3.33333 |
| Integer Division | DIV | // | y = 10 // 3 | 3 |
| Modulus | MOD | % | y = 10 % 3 | 1 |
| Exponent | ^ | ** | y = 2 ** 3 | 8 |
Activity 4.3: Debugging Variables
Error 1
- Code:
“code” = 404
print(“code”)
- Cause of error: The variable name does not include the double quotation marks.
Error 2
- Code:
SUBJECT = “ICT”
print(subject)
- Cause of error: Python is case-sensitive; SUBJECT and subject are two different variables.
Error 3
- Code:
B = A + 1
print(B)
- Cause of error: The undeclared variable A is used.
Error 4
- Code:
import = “5**”
print(import)
- Cause of error: “import” is a keyword, thus it cannot be used as the name of a variable.
Error 5
- Code:
fullname = “Peter Chan”
nickname = fullname – “Chan”
- Cause of error: Arithmetic operators are not applicable to the string data type.
Activity 4.4
Problem 1
A = 5
B = 9
C = A + B
print(C)
A = 3
B = A + 6
C = A * B
print(C - B)
Output: 14, 18
Problem 2
A = 3
B = 2
B = 2 * (A + B)
C = B ** 3
print(C - B)
A = 9
B = A * 5
print(A % B)
print(A // B)
Output: 990, 9, 0
Problem 3
a = 12
b = a + 10
c = b % 10
a = a**c
print(a//b)
print(type(a//b))
Output: 6,
Checkpoint 4.1
Problem 1.a
length = 20
width = 15
area = length * width
print(area)
Problem 1.b
length = 35
width = 10
perimeter = (length + width) * 2
print( perimeter )
Problem 1.c
PI = 3.14
r = 5
area = PI * r * r
print( area )
Problem 1.d
a = 13
b = 26
h = 5
area = ((a + b) * h) / 2
print(area)
Output and Input Statements:
- The
print()function prints the content within the brackets (strings, variables, or expressions).
Examples:
String:
print(“Text”)Output: Text
Variable:
length = 10 print(length)Output: 10
Expression:
python name = "Sam" print("Hi", name)
Output: Hi Sam
Lab 4.2
name = "David"
mark = 89
print("Hi", name)
print("Your mark is", mark)
name = "David"
mark = 89
print("Hi", name, "your mark is", mark)
Output:
Hi David
Your mark is 89
Hi David your mark is 89
print("print something \"special\"")
name = "Sam"
print("Hi")
print(name)
print("Bye")
name = "Sam"
print("Hi", end="")
print(name, end="")
print("Bye")
Output:
print something "special"
Hi
Sam
Bye
HiSamBye
Input Statement:
- Programs require users to input the values of the variables using
input(). - Input obtained by Python through the
input()function will be stored as a string in a variable.
Example:
- Pseudocode: Input length
- Python:
length = input()
Lab 4.3
length = input()
print(type(length))
length = int(input())
print(type(length))
width = float(input())
print(type(width))
Output:
<class ‘str’>
<class ‘int’>
<class ‘float’>
length = int(input())
width = float(input())
area = length * width
print(area)
print(type(area))
A = input()
B = input()
sum = A + B
print(sum)
print(type(sum))
Output:
300.0
<class ‘float’>
11
<class ‘str’>
Debugging Input:
Error 1
- Code:
mark = int(input()
print(mark)
- Cause of error: The brackets must come in pairs.
Error 2
- Code:
mark1 = input()
mark2 = input()
avg_mark = (mark1 + mark2) / 2
print(avg_mark)
- Cause of error: Arithmetic operators are not applicable to string data types. Need to convert mark1 and mark2 to float or int before calculate.
Checkpoint 4.2 Solutions:
Problem 1:
d = float(input("Please enter the diameter of the cylinder: "))
h = float(input("Please enter the height of the cylinder: "))
PI = 3.14
vol = PI * ((d/2)**2) * h
area = 2 * PI * (d/2) * h + 2 * PI * (d/2)**2
print("The volume of the cylinder is:", vol)
print("The surface area of the cylinder is:", area)
Problem 2:
name = input("Please enter your name: ")
test1 = float(input("Please enter the first test result: "))
test2 = float(input("Please enter the second test result: "))
exam = float(input("Please enter the exam result: "))
TEST1_WEIGHT = 0.2
TEST2_WEIGHT = 0.3
EXAM_WEIGHT = 0.5
overall = test1*TEST1_WEIGHT + test2*TEST2_WEIGHT + exam*EXAM_WEIGHT
print(name , end = "")
print(", your overall result of ICT is:", overall )
Problem 3:
print("This is a BMI Calculator!")
height = float(input("Please enter your height in meters: "))
weight = float(input("Please enter your weight in kg: "))
bmi = weight / (height**2)
print("Your BMI is", bmi)
Problem 4:
time = int(input("Input the number of seconds: "))
minutes = time // 60
seconds = time % 60
print("Your record is", minutes, "minute(s) and", seconds, "second(s).")
Functions:
- Python has many built-in functions, like
print(),input(),type(), andint().
More built-in functions
| Built-in Functions | Description | Example | Value of variable y |
|---|---|---|---|
| abs(x) | Return the absolute value of the number x | y = abs(-10)y = abs(20) | 10 20 |
| round(x, y) | Round the number x to y decimal places | y = round(10/3, 2)y = round(10/3, 5) | 3.33 3.33333 |
Mathematical Functions
- To use functions not built-in, import a library (e.g.,
math). - Some mathematical functions in the “math” library include:
| Mathematical functions | Description | Example | Value of variable y |
|---|---|---|---|
| sqrt(x) | Calculate the square root of x | import mathy = math.sqrt(16) | 4.0 |
| sin(x) | Calculate the sine of x radian | import mathy = math.sin(x) | 0.89399666360… |
Checkpoint 4.3
import math
a = float(input("One side of right triangle: "))
b = float(input("Another side of right triangle: "))
c = math.sqrt(a**2 + b**2)
print("The length of hypotenuse side is", c)
Random Functions
| Random Functions | Description | Example | Value of variable y |
|---|---|---|---|
| random() | Return a random floating-point number from 0 to 1 (excluding 1). | import randomy = random.random() | 0 <= y < 1 |
| uniform(a, b) | Return a random floating-point number from a to b (excluding b). | import randomy = random.uniform(1, 10) | 1 <= y < 10 |
| randint(a, b) | Return a random integer from a to b. | import randomy = random.randint(1, 10) | 1 <= y <= 10 |
Problem 4.4
import random
DrawNumber = random.randint(1, 100)
print(DrawNumber)
Output: A single random integer between 1 and 100
Selection:
- The selection control structure allows the program to make decisions based on specified conditions.
Boolean Expressions:
| Relational operator | Pseudocode Operator | Python Operator | Meaning | Python Boolean expression | Logical result of inputting 50 as mark |
|---|---|---|---|---|---|
| == | = | == | equal to | mark == 50 | True |
| < | < | < | less than | mark < 50 | False |
| <= | <= | <= | less than or equal to | mark <= 50 | True |
| > | > | > | greater than | mark > 50 | False |
| >= | >= | >= | greater than or equal to | mark >= 50 | True |
| != | != | != | not equal to | mark != 50 | False |
Binary-way Selection:
"if…then" in Python:
- Pseudocode:
if {condition} then
{“then” body}
- Python:
if {condition}:
{“then” body}
- Example:
mark = 70
if mark >= 50:
grade = "Pass"
print(grade)
"if…then…else" in Python:
- Pseudocode:
if {condition} then
{“then” body}
else
{“else” body}
- Python:
if {condition}:
{“then” body}
else:
{“else” body}
- Example:
mark = 70
if mark >= 50:
grade = "Pass"
else:
grade = "Fail"
print(grade)
Debugging Conditional Statements:
Error 1:
- Code:
mark = 70
if mark >= 50
print("Pass")
- Cause of error: Colon ":" should be added after the condition.
Error 2:
- Code:
mark = 100
if mark = 100:
print("Congratulation!")
- Cause of error: Instead of assignment operator "=", relational operator "==" should be used in the condition.
Error 3:
- Code:
mark = 70
if mark >= 50:
print("Pass")
else:
print("Fail")
- Cause of error: Indentation should be added before `print(