9.2 PythonCoBan B9.2
9.2 PythonCoBan B9.2
1. Python Syntax
2. Python Variables
3
Python Statements
Stateme
nt
Execution
result
5
Multiple Statements in Single Line
Stateme
nt
Execution
result
6
Comments in Python
7
Keywords
• Keywords = words that • Python is a growing and
have special meanings in evolving language. So, its
Python. keywords will keep
• List of keywords in Python: increasing and changing.
• Python provides a special
module for listing its
keywords called keyword.
• To find the current keyword
list, use the following code:
8
Identifiers
• The Python program can contain variables, functions,
classes, modules, packages, etc.
• Identifier is the name given to these programming
elements.
• An identifier should start with either an alphabet letter
(lower or upper case) or an underscore (_).
• An identifier contains alphabet letters, digits, or
underscores. No other characters are allowed.
• Identifiers in Python are case sensitive.
• Cannot use Python keywords for naming identifiers.
9
Python Naming Conventions
• Class names should use the TitleCase convention.
• It should begin with an uppercase alphabet letter e.g. MyClass, Employee,
Person.
• Function names should be in lowercase.
• Multiple words should be separated by underscores, e.g. add(num),
calculate_tax(amount).
• Variable names in the function should be in lowercase e.g., x, num, salary.
• Module and package names should be in lowercase e.g., mymodule,
tax_calculation.
• Use underscores to improve readability.
• Constant variable names should be in uppercase e.g., RATE, TAX_RATE.
• Use of one or two underscore characters when naming the instance
attributes of a class.
• Two leading and trailing underscores are used in Python itself for a special
10
String Literals
• Python uses single quotes ('), double quotes ("), triple
single quotes (''') and triple-double quotes (""") to denote a
string literal.
• The string literal need to be surrounding with the same type
of quotes.
• Examples of string literals:
11
Summary
• A Python statement ends with a newline character.
• Python uses spaces and indentation to organize its code
structure.
• Identifiers are names that identify variables, functions,
modules, classes, etc. in Python.
• Keywords are words that have special meanings in Python.
• Comments describe why the code works. They are ignored
by the Python interpreter.
• Use the single quote, double-quotes, triple-quotes, or triple
double-quotes to denote a string literal.
12
Python Variables
13
What is a variable in Python?
• Variables are used to store values in a program.
• In Python, a variable is a label that you can assign a value
to it.
• A variable is always associated with a value.
• In the following example, message is a variable.
Inpu Outp
t ut
Creating Variables
• Python has no command for • Variables do not need to be
declaring a variable. declared with any type.
• A variable is created at the first • Variables can even change
time a value is assigned to it. type after they have been set.
• Assignment syntax:
variable_name = value
• The value can be a number, a
string, etc.
• Examples:
15
Object's Identity
• Each object in Python has an id.
• It is the object's address in memory represented by an integer
value.
• The id() function returns the id of the specified object where it
is stored, as shown below.
16
Multiple Assignment
• Assign a single value to several variables simultaneously.
• Examples: a = b = c = 1
17
Naming Variables
Rules (should keep in mind): Guidelines (t0 define good
• Variable names can contain names):
only letters, numbers, and • Variable names should be
underscores (_). concise and descriptive.
• They can start with a letter or • Use underscores to separate
an underscore (_), not with a multiple words in the variable
number. names.
• Variable names cannot the • Be careful when using the
same as keywords, reserved letter l and the uppercase
words, and built-in functions in letter O because they look like
Python. the number 1 and 0.
• Variable names in Python are
18
Python Constants
• Constants like variables but their values do not change
during the program executes.
• Python does not support constants.
• Use all capital letters to name a variable to indicate that
the variable should be treated as a constant.
• For example:
• FILE_SIZE_LIMIT = 2000
• MAX = 100
• When encountering variables like these, do not change
their values.
• These variables are constant by convention, not by rules. 19
Python Data Types
20
Built-in Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different
types can do different things.
• Python has the following data types built-in by default:
Getting the Data Type
• You can get the data type of any object by using the type()
function:
Inpu Outp
t ut
22
Setting the Data Type
• In Python, the data type is set when you assign a value to a
variable:
23
Setting the Specific Data Type
• If you want to specify the
data type, you can use the
following constructor
functions:
24
Python Numbers – Int
• Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.
• Examples:
26
Python Numbers – Float
• Floats can be separated by the underscore _
• For example: 123_42.222_013
• Floats has the maximum size depends on the system.
• The float beyond its maximum size referred as "inf", "Inf",
"INFINITY", or "infinity".
• Float 2e400 will be considered as infinity for most systems.
27
Python Numbers – Complex
• A complex number is a number with real and imaginary
components.
• Use j or J as imaginary component.
• Examples:
28
Python Numbers – Type Conversion
• To convert from one type to another, the int(), float(),
and complex() methods are used.
• Examples:
29
Python Booleans
• Booleans represent one of • The bool() function:
two values: True or False. • To find out if a value is True
• Example of defining two or False, you use the bool()
boolean variables: function.
30
Python Strings
• A string is a series of characters.
• In Python, anything inside quotes is a string.
• You can use either single quotes or double quotes.
31
Python Strings
• To span a string multiple lines, you use triple-quotes """ …
""" or '''…’’’.
• Example:
32
Python Operators
33
Python Operators
• Operators are used to perform operations on variables and
values.
• Python divides the operators in the following groups:
• Arithmetic operators (Phép toán số học)
• Assignment operators (Phép gán)
• Comparison operators (Phép so sánh)
• Logical operators (Phép toán logic)
• Identity operators (Toán tử xác thực)
• Membership operators (Toán tử thành viên)
• Bitwise operators (Toán tử trên bit)
Arithmetic Operators
• Arithmetic operators perform the common mathematical
operation on the numeric operands.
• The arithmetic operators return the type of result depends
on the type of operands.
• If either operand is a complex number, the result is converted
to complex;
• If either operand is a floating-point number, the result is
converted to floating point;
• If both operands are integers, then the result is an integer,
and no conversion is needed.
35
List of all arithmetic operators in Python
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
36
Bitwise Operators
Operator Name Description Example
Sets each bit to 1 if both bits are
& AND 1000 & 1010 = 1000
1
Sets each bit to 1 if one of two 1000 | 1010 = 1010
| OR
bits is 1
Sets each bit to 1 if only one of
^ XOR 1000 ^ 1010 = 0010
two bits is 1
Inverts all the bits. 9 (base 10) = 00001001 (base 2)
~ NOT Bitwise NOTing any number x ~9 (base 10) = 11110110 (base 2) = -10 (base
yields -(x + 1). 10)
Shift left by pushing zeros in from 1011 << 1 = 10110
Zero fill left
<< the right and let the leftmost bits 1011 << 2 = 101100
shift
fall off. 1011 << 3 = 1011000
Shift right by pushing copies of 11001 >> 1 = 1100
Signed right
>> the leftmost bit in from the left, 11001 >> 2 = 110
shift
and let the rightmost bits fall off 11001 >> 3 = 11
37
Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
38
Comparison Operators
• The comparison operators compare two operands and
return a boolean either True or False.
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
Greater than
>= x >= y
or equal to
Less than or
<= x <= y
equal to
39
Logical Operators
• Logical operators are used to combine conditional
statements.
Operato
Description Example
r
Returns True if both
and x < 5 and x < 10
statements are true
Returns True if one of the
or x < 5 or x < 4
statements is true
Reverse the result, returns not(x < 5 and x <
not
False if the result is true 10)
40
Identity Operators
• Identity operators are used to compare the objects, not if
they are equal, but if they are actually the same object,
with the same memory location.
Operator Description Example
Returns True if
both variables
is x is y
are the same
object
Returns True if
both variables
is not x is not y
are not the same
object
41
Membership Operators
• Membership operators are used to test if a sequence is
presented in an object.
Operator Description Example
in Returns True if a x in y
sequence with the
specified value is present
in the object
not in Returns True if a x not in y
sequence with the
specified value is not
present in the object
42
Display Output
& User Input
43
Display Output
• The print() function prints the specified message to the screen,
or other standard output device.
• The message can be a string, or any other object, the object will
be converted into a string before written to the screen.
Print function syntax
print(object(s), sep=separator, end=end, file=file,
flush=flush)
Parameter Description
Any object, and as many as you like. Will be converted to string
object(s)
before printed
47
Exercises
48
•
50
CÂU HỎI ÔN TẬP
51