Manual - Python Basics
Objective
The objective of this session is to provide a comprehensive overview of Python basics, focusing
on data types. By the end of this session, you will have a solid understanding of Python's history,
features, and advantages, as well as how to work with expressions, operators, data types, and
basic data structures.
Table of Contents
1. Introduction to Python
o History of Python
o Features of Python
o Advantages of Python
2. Expressions and Operators
o Arithmetic Operators
o Assignment Operators
o Comparison Operators
o Logical Operators
3. Understanding the type() Function and Type Inference
4. Exploring Data Types
o Strings
o Lists
o Tuple
o Sets
o Dictionary
1. Introduction to Python
History of Python
Python was created by Guido van Rossum and first released in 1991. It was designed with an
emphasis on code readability and simplicity, making it accessible for beginners while being
powerful enough for advanced tasks.
Features of Python
• Easy to Read, Learn, and Write: Python's syntax is designed to be intuitive and its code
easy to read, which makes it a great choice for beginners.
• Interpreted Language: Python is executed line-by-line, which makes debugging easier.
• Dynamically Typed: Variables in Python do not need explicit declaration to reserve
memory space. The declaration happens automatically when a value is assigned to a
variable.
• Vast Standard Library: Python's standard library supports many common programming
tasks such as connecting to web servers, searching text with regular expressions, and
reading and modifying files.
• Extensible: Python can be extended with modules written in C or C++.
• Large Community and Ecosystem: Python has a large, active community and a vast
ecosystem of libraries and frameworks.
Advantages of Python
• Productivity and Speed: Python enhances productivity by offering simplicity in coding,
which allows developers to write code faster.
• Open Source: Python is free to use and distribute, including for commercial purposes.
• Cross-Platform Compatibility: Python can run on various operating systems such as
Windows, MacOS, and Linux.
• Third-Party Modules: The Python Package Index (PyPI) hosts thousands of third-party
modules, making Python highly versatile.
Variables and Data Types
• Variables: Containers for storing data values. Python variables do not need explicit
declaration to reserve memory space. The declaration happens automatically when a
value is assigned to a variable.
o Example:
x = 5
y = "Hello, World!"
• Data Types: Python has various standard data types including:
o Numeric Types: int, float, complex
▪ Example:
int_var = 10
float_var = 20.5
complex_var = 1 + 2j
o Sequence Types: list, tuple, range
▪ Example:
list_var = [1, 2, 3, 4]
tuple_var = (1, 2, 3, 4)
range_var = range(5) # generates numbers from 0 to 4
o Mapping Type: dict
▪ dict_var = {"key1": "value1", "key2": "value2"}
o Set Types: set, frozenset
▪ Example:
set_var = {1, 2, 3, 4}
frozenset_var = frozenset([1, 2, 3, 4])
o Boolean Type: bool
▪ Example: bool_var = True
o Text Type: str
▪ Example:string_var = "Hello, Python!"
2. Expressions and Operators
• Working with Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between numeric values.
These operators are used to perform mathematical operations:
• + : Addition
• - : Subtraction
• * : Multiplication
• / : Division
• // : Floor Division
• % : Modulus
• ** : Exponentiation
Addition (+)
• Usage: Adds two numbers.
• Example:
result = 10 + 5 # result is 15
Subtraction (-)
• Usage: Subtracts the right operand from the left operand.
• Example:result = 10 - 5 # result is 5
Multiplication (*)
• Usage: Multiplies two numbers.
• Example:
result = 10 * 5 # result is 50
Division (/ and //)
• Usage: Divides the left operand by the right operand.
o / performs floating-point division.
o // performs integer (floor) division.
• Example:
result = 10 / 3 # result is 3.3333...
result = 10 // 3 # result is 3
Modulus (%)
• Usage: Returns the remainder of the division.
• Example:result = 10 % 3 # result is 1
Exponentiation (**)
• Usage: Raises the left operand to the power of the right operand.
• Example:result = 2 ** 3 # result is 8
• Assignment Operators
These operators are used to assign values to variables:
• = : Assign
• += : Add and assign
• -= : Subtract and assign
• *= : Multiply and assign
• /= : Divide and assign
• //= : Floor divide and assign
• %= : Modulus and assign
• **= : Exponentiate and assign
Examples:
x=5
x += 3 # x is now 8
x -= 2 # x is now 6
x *= 4 # x is now 24
x /= 3 # x is now 8.0
x //= 2 # x is now 4.0
x %= 3 # x is now 1.0
x **= 3 # x is now 1.0
• Comparison Operators
Comparison operators compare the values on either side of the operator and return a boolean
result (True or False).
These operators are used to compare two values:
• == : Equal to
• != : Not equal to
• > : Greater than
• < : Less than
• >= : Greater than or equal to
• <= : Less than or equal to
Equal to (==)
• Usage: Checks if two values are equal.
• Example:
result = (10 == 10) # result is True
Not equal to (!=)
• Usage: Checks if two values are not equal.
• Example:result = (10 != 5) # result is True
Greater than (>)
• Usage: Checks if the left operand is greater than the right operand.
• Example:result = (10 > 5) # result is True
Less than (<)
• Usage: Checks if the left operand is less than the right operand.
• Example:result = (5 < 10) # result is True
Greater than or equal to (>=)
• Usage: Checks if the left operand is greater than or equal to the right operand.
• Example:result = (10 >= 5) # result is True
Less than or equal to (<=)
• Usage: Checks if the left operand is less than or equal to the right operand.
• Example:
result = (5 <= 10) # result is True
• Logical Operators
Logical operators are used to combine conditional statements. These operators are used to
combine conditional statements:
• and : Returns True if both statements are true
• or : Returns True if one of the statements is true
• not : Reverses the result, returns False if the result is true
and
• Usage: Returns True if both statements are True.
• Example:
result = (10 > 5) and (5 < 10) # result is True
or
• Usage: Returns True if at least one of the statements is True.
• Example:
result = (10 > 5) or (5 > 10) # result is True
not
• Usage: Reverses the result of the condition.
• Example:
result = not (10 > 5) # result is False
3. Understanding the type() Function and Type Inference
The type () Function
The type () function is used to determine the type of a variable or value.
Examples:
print (type (5)) # <class 'int'>
print (type (5.0) # <class 'float'>
print(type("Hello")) # <class 'str'>
print (type ([1, 2, 3])) # <class 'list'>
print (type ((1, 2, 3))) # <class 'tuple'>
print (type ({1: 'a', 2: 'b'})) # <class 'dict'> → Dict means dictionary
Type Inference
Python automatically infers the type of variable based on the value assigned to it. You don't need
to explicitly declare the type.
Examples:
x=5 # x is inferred as an int
y = 3.14 # y is inferred as a float
z = "hi" # z is inferred as a str
4. Data Type in Python
There are five data types in the Python programming language:
• String: A string is a collection of one or more characters put in a single, double, or triple
quote. In python there is no character data type, a character is a string of length one.
• List: List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple: Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set: Set is a collection which is unordered, unchangeable, and unindexed. No duplicate
members.
• Dictionary: Dictionary is a collection which is ordered and changeable. No duplicate
members.
I. String Data Type
A string is a collection of one or more characters put in a single quote, double-quote, or triple-
quote. In python there is no character data type, a character is a string of length one. It is
represented by str class.
Strings Manipulation
Strings are sequences of characters and are one of the most commonly used data types in Python.
Creating a String
• Usage: Define a string using single, double, or triple quotes.
• Example:
my_string = "Hello, World!"
another_string = 'Hello, Python!'
multiline_string = """This is a
multiline string."""
String Methods:
Upper and Lower Case
• Usage: Converts a string to uppercase or lowercase.
• Example:
upper_string = my_string.upper() # result is "HELLO, WORLD!"
lower_string = my_string.lower() # result is "hello, world!"
Strip
• Usage: Removes whitespace from the beginning and end of a string.
• Example:
stripped_string = " Hello, World! ".strip()
# result is "Hello, World!"
Split
• Usage: Splits a string into a list of substrings based on a specified delimiter.
• Example:
split_string = my_string.split(",")
# result is ['Hello', ' World!']
Join
• Usage: Joins elements of a list into a single string, separated by a specified delimiter.
• Example:
joined_string = "-".join(["Hello", "World"])
# result is "Hello-World"
Find
• Usage: Returns the index of the first occurrence of a substring.
• Example:
index = my_string.find("World") # result is 7
Replace
• Usage: Replaces a substring with another substring.
• Example:
replaced_string = my_string.replace("World", "Python")
# result is "Hello, Python!"
II. List
A list is an ordered, mutable collection of items. Lists are just like arrays, which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the same type. Lists
are defined using square brackets [].
Examples:
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1
my_list.append(6) # Adds 6 to the end of the list
print(my_list) # [1, 2, 3, 4, 5, 6]
my_list[2] = 10 # Changes the third element to 10
print(my_list) # [1, 2, 10, 4, 5, 6]
Python has a set of built-in methods that you can use on lists/arrays.
III. Tuples
Tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception that
tuples cannot be changed once declared. Tuples are usually faster than lists. Tuples are defined
using parentheses ().
Examples:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # 1
# my_tuple[2] = 10 # This would raise an error since tuples
are immutable
print(my_tuple) # (1, 2, 3, 4, 5)
• Tuples are Ordered:
When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.
• Tuples are Unchangeable:
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
has been created.
Note: To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.
IV. Sets
Sets are unordered collections of unique elements. They are useful for performing mathematical
set operations like union, intersection, difference, and symmetric difference.
Creating a Set
• Usage: Define a set using curly braces {} or the set() function.
• Example:
my_set = {1, 2, 3, 4, 5}
another_set = set([1, 2, 3, 4, 5])
Set Operations
Union (|)
• Usage: Combines elements from both sets, removing duplicates.
• Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1 | set2 # result is {1, 2, 3, 4, 5}
Intersection (&)
• Usage: Returns elements present in both sets.
• Example:
result = set1 & set2 # result is {3}
Difference (-)
• Usage: Returns elements present in the first set but not in the second set.
• Example:
result = set1 - set2 # result is {1, 2}
Symmetric Difference (^)
• Usage: Returns elements present in either set but not in both.
• Example:
result = set1 ^ set2 # result is {1, 2, 4, 5}
V. Dictionaries
A dictionary is an unordered collection of key-value pairs. Dictionaries are defined using curly
braces {}. Dictionary holds pairs of values, one being the Key and the other corresponding pair
element being its Key:value. Values in a dictionary can be of any data type and can be
duplicated, whereas keys can’t be repeated.
Examples:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['a']) # 1
my_dict['d'] = 4 # Adds a new key-value pair 'd': 4
print(my_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
del my_dict['b'] # Deletes the key 'b' and its value
print(my_dict) # {'a': 1, 'c': 3, 'd': 4}