0% found this document useful (0 votes)
5 views

B11 02 Python Fundamentals

Uploaded by

nthang0987
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

B11 02 Python Fundamentals

Uploaded by

nthang0987
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Python Fundamentals

Lê Ngọc Hiếu
[email protected]
1. Python Syntax

2. Python Variables

Lecture 3. Python Data Types

Contents 4. Python Operators

5. Display Output & User


Input
6. Exercises
2
Python Syntax

3
Python Statements

Python statement ends with


the token NEWLINE
character.

Each line in a Python script


is a statement.
A statement can span over multiple
lines

Statement

Execution
result

5
Multiple Statements in Single Line
Statement

Execution
result

6
Indentation in Python
Python uses indentation (a space or a
tab) to denote a block of
statements.

Indentation Rules
• Use the colon : to start a block
• All the lines in a block must use the
same indentation, either space or a
tab.
• Python recommends four spaces as
indentation to make the code more
readable.
• Do not mix space and tab in the same
7
Comments in Python

The symbol # indicates the


start of a comment line.

It is effective till the end of the


line in the editor.

8
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:

9
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.
10
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
11
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:

12
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.
13
Python Variables

14
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.

Input Output
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:

16
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.

17
Multiple Assignment
• Assign a single value to several variables simultaneously.
• Examples: a = b = c = 1

• Assign multiple objects to multiple variables.


• Examples:a, b, c = 10, 20, 30
x, y, z = 10, 'Hello', True

18
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
19
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. 20
Python Data Types

21
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:

Input Output

23
Setting the Data Type
• In Python, the data type is set when you assign a value to a
variable:

24
Setting the Specific Data Type
• If you want to specify the
data type, you can use the
following constructor
functions:

Check your understanding:


https://www.w3schools.com/python/
exercise.asp?filename=exercise_dat
atypes1

25
Python Numbers – Int
• Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.
• Examples:

• Leading zeros in non-zero integers are not allowed.


• For example: 000123 is invalid number, 0000 is 0.
• Python use underscore _ as a delimiter.
• For example: x = 1_234_567_890
26
Python Numbers – Float
• Float, or "floating point number" is a number, positive or
negative, containing one or more decimals.
• Examples:

• Float can also be scientific numbers with an "e" to indicate


the power of 10.
• Examples:

27
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.

28
Python Numbers – Complex
• A complex number is a number with real and imaginary
components.
• Use j or J as imaginary component.
• Examples:

29
Python Numbers – Type Conversion
• To convert from one type to another, the int(), float(),
and complex() methods are used.
• Examples:

30
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.

• When comparing two


numbers, Python returns
the result as a boolean
value.

31
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.

• If a string contains a single quote, place it in double-quotes.


• When a string contains double quotes, place it in single
quotes.

32
Python Strings
• To span a string multiple lines, you use triple-quotes """ …
""" or '''…'‘’.
• Example:

33
Python Operators

34
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.

36
List of all arithmetic operators in
Python
Operat Exampl
Name
or e
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
Exponentiatio
** x ** y
n
// Floor division x // y 37
Bitwise Operators
Operat
Name Description Example
or
Sets each bit to 1 if both bits
& AND 1000 & 1010 = 1000
are 1
Sets each bit to 1 if one of 1000 | 1010 = 1010
| OR
two bits is 1
Sets each bit to 1 if only one
^ XOR 1000 ^ 1010 = 0010
of two bits is 1
Inverts all the bits. 9 (base 10) = 00001001 (base 2)
~ NOT Bitwise NOTing any number ~9 (base 10) = 11110110 (base 2) = -
x yields -(x + 1). 10 (base 10)
Shift left by pushing zeros in 1011 << 1 = 10110
Zero fill
<< from the right and let the 1011 << 2 = 101100
left shift
leftmost bits fall off. 1011 << 3 = 1011000
Shift right by pushing copies
11001 >> 1 = 1100
Signed of the leftmost bit in from
>> 11001 >> 2 = 110
right shift the left, and let the 38
11001 >> 3 = 11
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
39
Comparison Operators
• The comparison operators compare two operands and
return a boolean either True or False.
Operat
Name Example
or
== 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 40
Logical Operators
• Logical operators are used to combine conditional
statements.
Operat
Description Example
or
Returns True if both x < 5 and x <
and
statements are true 10
Returns True if one of
or x < 5 or x < 4
the statements is true
Reverse the result,
not(x < 5 and x
not returns False if the
< 10)
result is true

41
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.
Operato Exampl
Description
r e
Returns True if
both variables
is x is y
are the same
object
Returns True if
both variables x is not
is not
are not the y
same object
42
Membership Operators
• Membership operators are used to test if a sequence is
presented in an object.
Operato Description Example
r
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
sequence with the y
specified value is not
present in the object

43
Display Output
& User Input

44
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
object(s)
string before printed

sep='separat Optional. Specify how to separate the objects, if there is


or' more than one. Default is ' '
Optional. Specify what to print at the end. Default is '\n'
end='end'
(line feed)
Optional. An object with a write method. Default is
file
sys.stdout
Optional. A Boolean, specifying if the output is flushed
flush
(True) or buffered (False). Default is False
Statement
Execution
result

47
Getting User's Input
• Python allows for user input.
• That means we are able to ask the user for input.
• Python uses the input() function method to get user’s
input.
• Python stops executing when it comes to the input()
function and continues when the user has given some
input.

48
Exercises

49
•Input two integers. Find the addition, subtraction, multiplication, and division of them.

1. Input two integers. Find the addition, subtraction,


multiplication, and division of them.
2. Compute the perimeter and area of a circle, given its
radius.
3. Compute the surface area and volume of a sphere,
given its radius (Area = , Volume =
4. Input two numbers. Swap the values of them.
5. Input a 3-digit number. Reverse the input number.
51
52

You might also like