Introduction to Computer Science (I) 2.
Python Basics and Expressions
Week-2
Python Basics and Expression
Yen-Ru Lai
yrlai@[Link]
Department of Civil Engineering, National Chung Hsing University
Copyright © 2024 Yen-Ru Lai, Tzu-Ching Chang, An-ting Chang, Chih-Ling Fan. All rights reserved. 2-1
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Download Anaconda
URL : [Link]
Enter your personal email address and send it
Check Email 2-2
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Download Anaconda
Please download the required specifications by yourself
Download link
2-3
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ What is a Variable?
Attach a label “X” to an object with the value of 2.
◼ Variable • The syntax to create a Python variable is: variable name = variable value.
• Variable names can only consist of English letters (A-Z, a-z), numbers (0-9), and underscores
( _ ). The first character must be an English letter or underscore, and spaces are not
allowed.
• Multiple variables can be assigned values simultaneously:
name, score = "Hero", 37
• If a variable is no longer needed, it can be deleted to free memory:
del variable_name
2-4
Introduction to Computer Science (I) 2. Python Basics and Expressions
• Variable names cannot be the same as Python's built-in reserved keywords.
◼ Reserved
• Built-in reserved keywords include operators, simple delimiters, complex delimiters,
Keywords
definitions, etc. These are words that have been assigned specific meanings.
• If you want to check reserved keywords, you can use the following code:
import keyword
[Link]
Type Definition Reserved Keywords
Constants Words with specific meanings False, None, True
Operators Words that represent operators and, del, in, is, lambda, not, or
as, assert, async, await, break, continue, from, glo
Simple Delimiters Single-word delimiters
bal, import, nonlocal, pass, raise, return, yield
Complex Delimiters Multi-word delimiters else, elif, except, finally, for, if, try, while, with
Definitions Words with definition functions class, def
2-5
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Code • Add # in the code. The text following # is a comment and will not be executed.
Comments A = 1 # A is a variable with a value of 1
• The method for writing multi-line comments is to enclose the comment block
with triple single quotes ''' or triple double quotes """.
'''
This is a multi-line comment.
It spans multiple lines.
'''
It's a good habit to add comments when writing code to explain what the code is doing!
2-6
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Data Types
Boolean
Data
string int
Types
float
2-7
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Data Types
1. Number
• Integer: int
• Floating Point: float (includes numbers with decimal points)
• Boolean: bool – This data type only has True and False values (Note: T and F are uppercase). This variable
type is typically used in conditional statements, where the program determines what action to take based
on the Boolean value.
2. String
e.g.
• Python string data type (str) is enclosed by a pair of double quotes " or
str1 = " This is a string "
single quotes ‘.
str2 = ' This is a string '
• For example, str1 = "This is a string" or str1 = 'This is a string' will produce print(str1)
print(str2)
the same result.
2-8
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Data Types
3. Conversion
• If the system cannot automatically convert data types, you must use type conversion commands to force
the conversion.
e.g.
• int(): Forces to an integer data type.
a = 12 c = float(a)
• float(): Forces to a floating-point data type. b = 2.75 d = int(b)
• str(): Forces to a string data type. print(type(a)) …… <class ‘int'>
print(type(b)) …… <class 'float'> print(type(c)) …… <class 'float'>
print(type(d)) …… <class ‘int'>
print(c) …… 12.0
print(d) …… 2
◼ Print Outputs
• The print command can display the contents of the specified items. The syntax is: print().
2-9
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Input
• The syntax for the input command is: variable = input("prompt string")
• The "prompt string" is a message displayed to inform the user what to input.
• When entering data, the user presses the Enter key to end the input. The input command will store the
entered data in the variable.
• The data type of the input is limited to strings!
e.g.1 e.g.2
score = input("Plase enter your test score:") top = float(input("Enter the top length of the trapezoid:"))
print(type(score)) bottom = float(input("Enter the bottom length of the trapezoid:"))
print(f"Your score is: {score}") height = float(input("Enter the height of the trapezoid: "))
area = (top + bottom) * height / 2
print(f"The area of the trapezoid is: {area}")
2 - 10
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Operators
1. Arithmetic Operators 2. Comparison Operators
Operator Definition Example • Comparison operators compare two expressions. If the
+ Addition 9+5 14 comparision is correct, it returns True; if not, it returns False.
- Subtraction 9-5 4 • The designer can use the comparison result to control different
* Multiplication 9*5 45
parts of the program.
/ Division 9/5 1.8
Operator Definition Example
% Remainder 9%5 4
== Equals to (6+9==2+13) True
// Floor Division 9//5 1
!= Not equal to (6+9!=2+13) False
** Exponentiation 9**2 81
> Greater than (6+9>2+13) False
< Less than (5+9<2+13) True
>= Greater than or equal to (3+9>=2+13) False
<= Less than or equal to (3+9<=2+13) True
2 - 11
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Operators
3. Logical Operators
• Logical operators typically combine multiple comparison expressions to derive a final comparison result and are
used for more complex conditions.
Operator Definition Example
e.g.
Returns the opposite of the comparison result. a = 3<5 # True
not(3>5) True
not If the comparison is True, it returns False. If b = 2>4 # False
not(5>3) Flase c = 1!=7 # True
the comparison is False, it returns True.
print(not a)
Only returns True if both comparisons are (5>3)and(9>6) True
and print(a or b)
True; otherwise, it returns False. (5>3)and(9<6) False print(a and b)
print(a and (not b))
Returns True if at least one of the comparisons (5>3)or(9>6) True print((not a or b) and c)
or
is True; otherwise, it returns False. (5<3)or(9<6) False
2 - 12
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Operators
4. Compound Assignment Operators
• Compound assignment operators are used to simplify operations that involve modifying the value of a variable.
• The operator is placed before the = to represent an operation on the original variable:
i += 2 means i = i + 2
i -= 2 means i = i - 2
Operator Meaning i = 10
+= Add and then assign the result to the variable i += 5 15
-= Subtract and then assign the result to the variable i -= 5 5
*= Multiply and then assign the result to the variable i *= 5 50
/= Divide and then assign the result to the variable i /= 5 2.0
%= Modulus and then assign the remainder to the variable i %= 5 0
//= Floor division and then assign the result to the variable i //= 5 2
**= Exponentiate and then assign the result to the variable i **= 3 1000
2 - 13
Introduction to Computer Science (I) 2. Python Basics and Expressions
◼ Operators
5. Operator Precedence
Precedence
Operator
Level
0 () Parentheses
1 ** Exponentiation
2 Unary + and -
3 * Multiplication、/ Division、% Modulus、// Floor Division
4 + Addition、- Subtraction
5 Comparison Operators (==, !=, >, <, >=, <=)
6 not Logical NOT
7 and Logical AND
8 or Logical OR
9 Compound Assignment Operators (+=, -=, *=, /=, %=, //=, **=)
2 - 14
Introduction to Computer Science (I) 2. Python Basics and Expressions
◆ Exercise
Q1: Given a = 13 and b = 7, what is the value of a ** b?
Q2: Given x = 7483, what is the value of x += 375?
Q3: Given num1 = 178 and num2 = 23, what is the result of num1 % num2?
Q4: Given x = 4 and y = 2,please calculate:
x **= y + 3
x /= y * 2
2 - 15