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

01-Python1

The document provides an overview of Python basics, covering syntax, variables, operators, and fundamental data types such as integers, floats, strings, lists, tuples, sets, and dictionaries. It includes explanations of how to initialize and manipulate these data structures, along with examples of operations and methods associated with each type. The content is aimed at beginners looking to understand the foundational elements of Python programming.

Uploaded by

Nguyễn Lê Vy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

01-Python1

The document provides an overview of Python basics, covering syntax, variables, operators, and fundamental data types such as integers, floats, strings, lists, tuples, sets, and dictionaries. It includes explanations of how to initialize and manipulate these data structures, along with examples of operations and methods associated with each type. The content is aimed at beginners looking to understand the foundational elements of Python programming.

Uploaded by

Nguyễn Lê Vy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Python Basics 1

Nguyen Ngoc Thao, B.SE


In Charge of Deep Medicine,
Phan Chau Trinh Medical University
[email protected]
0935192556
Content
➢ Syntax
➢ Variables - Operators
➢ Fundamental Data types
Syntax
➔ Keywords in Python
Syntax
➔ Indentation which refers to the spaces at the beginning of
a code line is obligated to use to indicate a block of code in
control flows, classes or functions
Indentation if 6 > 3 :
print("Six is greater than three!")

➔ Indentations are theifsame


True for
: all statements in a block of
code print("Hello")
print("True")
else:
print("False")
Syntax
➔ Comments for a line starts with a #, and Python will
ignore them #This is a comment
print("Hello, World!")

"""
➔#This
Comments for a paragraph useThis
is a comment """ is a comment
#written in written in
#more than just one line more than just one line
print("Hello, World!") """
print("Hello, World!")
Variables
➔ Many values can be assigned to multiple variables
x, y, z = "Orange", "Banana", "Cherry"

➔ Rules for variable name in Python:


★ Must start with a letter or the underscore character
★ Cannot start with a number
★ Can only contain alpha- numeric characters and
underscores (A-z, 0-9, and _ )
★ Are case-sensitive (age, Age and AGE are three different
variables)
Operators
➔ Arithmetic Operators: +, -, *, /, %, **, //
➔ Assignment Operators: =, +=, -=, *=, /=, %=, **=, //=, |=,
&=, >>=, <<=
➔ Comparison Operators: ==, !=, >=, <=, >, <
➔ Logical Operators: and, or, not
➔ Identity Operators: is, is not
➔ Membership Operators: in, not in
➔ Bitwise Operators: &, |, ^, ~, >>, <<
Numeric Types
➔ Int (integer) is a whole number, positive or negative,
without decimals, of unlimited length
➔ Float is a number, positive or negative, containing one or
more decimals. It can also be scientific numbers with an
"e" to indicate the power of 10. x = 1 # int
➔ Complex numbers are written y = 2.8 # float
with a "j" as the imaginary part. z = 1j # complex

➔ Convert from one type to another with the int(), float(), and
complex() methods
String
➔ are surrounded by either single quotation marks, or double
quotation marks.
Ex: 'hello' is the same as "hello"
➔ Convert from one type to another with the int(),
float(), and complex() methods.
➔ Assign a multiline string to a variable by using three
quotes.
longer = " " " This string has
multiple lines " " "
+
String
Concatenation operator >>> str1+ str2
➔ String operators >>> “Hello world”

* Repetition operator >>> str1* 3


>>> str1= “Hello” >>> “Hello Hello
>>> str2= “world” Hello”

[] Slice operator >>> str1[4]


‘o’

[:] Range Slice operator >>> str1[6:10]


‘world’

in Membership operator (in) >>> ‘w’ in str2


True

not Membership operator(not >>> ‘e’ not in str1


in in) False
Boolean
➔ represents one of two values: True or False.
➔ The bool() function is used to evaluate any value, and return True or
False in the result.
➔ Almost any value is evaluated to True if it has some sort of content;
any string is True, except empty strings; any number is True, except 0;
any list, tuple, set, and dictionary are True, except empty ones.
➔ Not many values are evaluated to False, except empty values, such as
(), [], {}, "", the number 0, and the value None. And of course the value
False evaluates to False.
➢ Lists
Data Structures
➢ Sets
➢ Tuples
➢ List
○ List Initialization
○ Operations on Lists
○ List methods
➢ Dictionary
Lists
➔ are like dynamically sized arrays used to store multiple
items
➔ Properties of a list: mutable, ordered, heterogeneous,
duplicates.

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [['tiger', 'cat'], ['fish']]
list4 = ["abc", 34, True, 40, "abc"]
List Initialization
➔ Using square brackets []
➔ Using list multiplication
# an empty list
L1= list[] # a list of 10 items of ' '
# a list of 3 items L1= list[' ' ]*10
L2= list['banana','apple', 'kiwi']
➔ Using list comprehension
➔ Using list() constructor
# an empty list # a list of 10 items of ' '
L1 =list() L2 = [' ' for i in range(10)]
# a list of 3 items
L2= list((banana','apple', 'kiwi'))
➢ Lists
Data Structures
➢ Tuples
○ Tuples Initialization
○ Operations on Tuples
○ Tuples methods
➢ Dictionary
➢ Sets
Tuples
➔ Tuples are used to store multiple items in a single variable.
➔ A tuple is a collection which is ordered and unchangeable
➔ are written with round brackets.
➔ Example:
thistuple =
("apple", "banana", "cherry")
print(thistuple)
Tuple Initialization
➔ One item tuple, remember the comma:
Ex:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Operations on
➔ Access Tuples
Tuple
➔ Unpacked Tuples
➔ Loop Tuples
➔ Join Tuples
Operations on
Tuple
➔ Access Tuple: can access tuple items by referring to the index
number, inside square brackets:
➔ Ex1: thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
➔ Ex2: thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
➔ Ex3: thistuple =
("apple", "banana", "cherry", "orange")
print(thistuple[2:3])
Operations on
➔ Join Tuples: Tuple
➔ Ex 1: # use “+” operator
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
🡪 Ex 2: # use “*” operator
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
⮚ Lists
Data Structures
⮚ Tuples
⮚ Sets
○ Sets Initialization
○ Operations on Sets
○ Sets methods
⮚ Dictionary
Sets
➔ used to store multiple items in a single variable.
➔ is a collection which is unordered, unchangeable, and
unindexed.
➔ Sets are written with curly brackets.
Sets Initialization
Ex1:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Ex2: Sets cannot have two items with the same value.
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Operations on
➔ Access Sets Items
Sets
➔ Add Sets Items
➔ Remove Sets Items
➔ Loop Sets Items
➔ Join
Operations on
Sets
➔ Loop: through the set items by using a for loop:
o Ex: thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Operations on
Sets
🡪 Join: using union() method or update() method.
o Ex:

set1 = {"a", "b" , "c"} set1 = {"a", "b" , "c"}


set2 = {1, 2, 3} set2 = {1, 2, 3}

set3 = set1.union(set2) set1.update(set2)


print(set3) print(set1)
Sets Methods
Method Description
add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another,
specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update Removes the items in this set that are not present in other, specified
() set(s)
Sets Methods
Method Description
isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update inserts the symmetric differences from this set and another
()
union() Return a set containing the union of sets

update() Update the set with the union of this set and others
➢ Lists
Data Structures
➢ Tuples
➢ Sets
➢ Dictionary
○ Dictionary Initialization
○ Operations on Dictionary
○ Dictionary methods
Dictionaries
➔ Are used to store data values in key : value pairs.
➔ A dictionary is a collection which is ordered*, changeable
and do not allow duplicates.
➔ written with curly brackets, and have keys and values:
Dictionaries
Initialization
➔ Ex1: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionaries
Ex2:
Initialization
# Duplicate values will overwrite existing
values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Operations on
➔ Access Items
Dictionaries
➔ Change Items
➔ Add Items
➔ Remove Items
➔ Loop Items
➔ Copy Dictionaries
Operations on
Dictionaries
➔ Access Items: access the items of a dictionary by
referring to its key name, inside square brackets:
➔ Ex: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Operations on
Dictionaries
➔ Loop dictionaries: the return value are the keys of the
dictionary, but there are methods to return the values as
well.
o Ex1: Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

o Ex2: Print all values in the dictionary, one by one:

for x in thisdict:
print(thisdict[x])
Operations on
Dictionaries
➔ Loop dictionaries: the return value are the keys of the
dictionary, but there are methods to return the values as
well.
o Ex3: values() method to return values of a dictionary:
for x in thisdict.values():
print(x)
o Ex4: use the keys() method to return the keys of a
dictionary:
for x in thisdict.keys():
print(x)
o Ex5: items() method to through both keys and values
for x, y in thisdict.items():
print(x, y)

You might also like