Dec 03, 2024 | 1555 words | 16 min read
5.1.1. Materials#
Here is the link to the Python Official Documentation
HELLO WORLD#
OPERATORS#
Math Operators#
used to perform basic operations
Addition
+
: returns the sum of two numbersSubtraction
-
: returns the difference of two numbersMultiplication
*
: returns the product of two numbersDivision
/
: returns the quotient of two numbersModulus
%
: returns the remainder of the divisionExponentiation
**
: raises the first number to the power of the second numberFloor division
//
: returns the integer part of the division result
Operands - Operands are the values that the operator acts on.
Order of operations is determined by precedence:
Parentheses
()
Exponents
**
Multiplication and Division
*
,/
,%
,//
Addition and Subtraction
+
,-
If two operators have the same precedence, they are applied from left to right
Boolean Operators#
used to combine conditional statements
not
: returnsTrue
if the statement is false and vice versaand
: returnsTrue
if both statements are trueor
: returnsTrue
if one of the statements is true
Comparison Operators#
used to compare two values, returns a boolean value.
greater than
>
: returnsTrue
if the left operand is greater than the right operandless than
<
: returnsTrue
if the left operand is less than the right operandgreater than or equal to
>=
: returnsTrue
if the left operand is greater than or equal to the right operandless than or equal to
<=
: returnsTrue
if the left operand is less than or equal to the right operandequal to
==
: returnsTrue
if the operands are equalnot equal to
!=
: returnsTrue
if the operands are not equal
Assignment Operators#
=
is used to assign values to variables.
See Variables
Bitwise Operators#
used to perform bitwise operations
&
: Bitwise AND|
: Bitwise OR^
: Bitwise XOR~
: Bitwise NOT<<
: Bitwise left shift>>
: Bitwise right shift
Identity Operators#
used to compare the memory location of two objects
is
: returnsTrue
if both variables are the same objectis not
: returnsTrue
if both variables are not the same object
Membership Operators#
used to test if a sequence is present in an object
in
: returnsTrue
if a sequence is present in the objectnot in
: returnsTrue
if a sequence is not present in the object
VARIABLES#
A variable is a name that refers to a value. Variables are used to store data that can be referenced and manipulated in a program.
Assignment operator#
=
is used to assign a value to a variable
The value on the right side of the assignment operator is assigned to the variable on the left side.
Variable names can contain letters, numbers, and underscores.
They must start with a letter or an underscore.
Variable names are case-sensitive.
Variables can be reassigned to new values at any time.
Variables can point to any data type.
Expressions are anything that can be evaluated to a value.
For example: 1+2
Literals are fixed values that are written directly into the code.
For example: 1
or "Hello World!"
Assignment statements#
used to create variables and assign values to them.
Syntax: variable = expression or literal
a = 1+2
b = "Hello World!"
Compound Assignment Operators#
a+=3
equates toa = a + 3
(Add and assign)a-=3
equates toa = a - 3
(Subtract and assign)a*=3
equates toa = a * 3
(Multiply and assign)a/=3
equates toa = a / 3
(Divide and assign)a%=3
equates toa = a % 3
(Modulus and assign)a**=3
equates toa = a ** 3
(Exponentiate and assign)a//=3
equates toa = a // 3
(Floor divide and assign)
Python does not have increment ++
and decrement --
operators.
DATA TYPES#
You can use the type()
function to get the datatype of a variable or a literal.
Basic Data Types#
Integer
int
- whole numbersFloat
float
- numbers with decimal pointsString
str
- sequence of charactersBoolean
bool
- True or FalseNone
NoneType
- represents the absence of a value
Sequence Data Types#
List - comma separated values enclosed in square brackets,
[1, 2, 3]
,list()
Tuple - comma separated values enclosed in parentheses,
(1, 2, 3)
,tuple()
Set - comma separated values enclosed in curly braces,
{1, 2, 3}
,set()
Dictionary - key-value pairs enclosed in curly braces,
{"name": "John", "age": 20}
,dict()
Range -
range()
returns a sequence of numbersSyntax:
range(start, stop, step)
start - optional, an integer number specifying at which position to start.
stop - required, an integer number specifying at which position to stop (not included)
step - optional, an integer number specifying the incrementation.
Default values: start=0, stop - no default values as it is required, step=1
Basic indexing and slicing#
Indexing - accessing a single element of a sequence
Slicing - accessing multiple elements of a sequence
Indexing starts from 0
Negative indexing starts from -1 (last element)
Slicing syntax:
[start:stop:step]
start - starting index
stop - stopping index
step - incrementation
Default values: start=0, stop=len(sequence), step=1
Sequence |
Mutability |
Order |
Unique Elements |
Editablity |
---|---|---|---|---|
List |
Mutable |
Ordered |
allows duplicates |
replaced or changed or added or removed |
Tuple |
Immutable |
Ordered |
allows duplicates |
cannot be replaced or changed or added or removed |
Set |
Mutable |
Unordered |
no duplicates |
cannot be replaced or changed, only added or removed |
Dictionary |
Mutable |
Unordered |
no duplicate keys |
replaced or changed or added or removed |
Mixed Type Operations#
Adding two integers results in an integer:
int
+int
=int
Adding an integer and a float results in a float:
int
+float
=float
Adding a string and a number, results in an error:
str
+int
=TypeError
Adding two strings concatenates them and results in a string:
str
+str
=str
Multiplying a string by an integer repeats the string and results in a string:
str
*int
=str
Division always results in a float:
int
/int
=float
Floor division always results in an integer:
float
//float
=int
Data Type Conversion#
int()
- converts a value to an integerfloat()
- converts a value to a floatstr()
- converts a value to a stringbool()
- converts a value to a booleanlist()
- converts a value to a listtuple()
- converts a value to a tupledict()
- converts a value to a dictionaryset()
- converts a value to a set
Strings#
Single quotes '
, double quotes "
, or triple quotes '''
or """
can be used
to define strings You can add backward-slash \
before the quote to escape it.
Example:
print('Pete') # Output: Pete
print("Pete's hammer") # Output: Pete's
print("""Pete's "hammer" """) # Output: Pete's "hammer"
print('Pete\'s "hammer"') # Output: Pete's "hammer"
INPUT FUNCTION - input()#
Example:
user_name = input("Enter your name: ")
Note
Python input()
function always returns a str
as its datatype.
Converting user input
age = input("Enter your age: ")
age = int(age)
Nested functions in Python
age = int(input("Enter your age: "))
age = float(input("Enter your age: "))
For the purpose of this course, you will not worry about validating and sanitizing user input. If you are interested in learning more about it, you can check out exception handling in Python.
OUTPUTS#
print() function#
print()
function - prints the given object to the standard output device (screen)
Examples:
world = 616
print("Hello World")
print("Hello", "World")
print("Hello", "World", world)
print("Hello", "World", 616, sep="***", end="!")
print("There are",120,"students in the class", sep=" ", end=".\n")
format() function#
format()
function - accepts a number and a format specifier and returns as a string
Syntax: format(number, format_specifier)
format_specifier syntax - "[width][grouping_option][.precision][type]"
width - minimum number of characters to be printed (default is 0)
grouping_option - comma (,) to use comma as a thousand separator
precision - number of decimal places to be printed
type - d for integer, f for float, s for string
Examples:
format(123.4567, ".2f") # Output is "123.46"
format(1234.56789, "10,.2f") # Output is " 1,234.57"
format(1234, "10_d") # Output is " 1_234"
format(0.2, "0.0%") # Output is "20.0%"
format(12345.6789, "e") # Output is "1.234568e+04" which is 1.234568 x 10^4
format(12345.6789, "E") # Output is "1.234568E+04" which is 1.234568 x 10^4
format(12345.6789, ".2e") # Output is "1.23e+04" which is 1.23 x 10^4
format(0.00000012345, ".4E") # Output is "1.2345E-07" which is 1.2345 x 10^-7
Formatted print statements (f-print)#
Here is the Python Official Documentation link to formatted string literals
Syntax: f"string {variable}"
Example:
item = "apple"
cost = 1234.56789
f"{item} costs ${cost}" # Output is "apple costs $1234.56789"
print(f"{item} costs ${cost:,.2f}") # Output is "apple costs $1,234.57"
MATH MODULE#
Syntax:
import math
math.<function name>()
Python has a built-in module called
math
that contains a collection of mathematical functionsTo use the
math
module, you must import it using theimport
keywordTo access functions in the
math
module, you must use the module name followed by a period (.
) and then thefunction name
Examples:
math.sqrt() # square root of a number
math.ceil() # ceiling of a number (round up to the next integer)
math.floor() # floor of a number (round down to the previous integer)
math.factorial() # factorial of a number
More details on the math
module can be found in the official documentation.
IMPORT METHODS#
There are several ways to import a module or a function from a module
import a module#
import math
print(math.sqrt(25)) # Output: 5.0
import a module using an alias#
import math as m
print(20 * m.cos(m.pi)) # Output: -20.0 , (cos(pi) = -1)
import specific functions from a module#
from math import cos, pi
print(20 * cos(pi)) # Output: -20.0
import specific functions from a module using an alias#
from math import sqrt as s
print(s(25)) # Output: 5.0
import all functions from a module using the * operator#
from math import *
print(sqrt(25)) # Output: 5.0
Warning
To import all functions (using the * method) from a module is NOT recommended.
This is because it can overwrite functions that already exist in the program and/or It can be difficult to determine where a function came from.
RANDOM MODULE#
The random
module provides a number of functions that can be used to
generate random numbers. Random numbers are used in various applications such as
games, simulations, cryptography, and statistical analysis.
True Random Number Generator (TRNG)
Generates random numbers based on physical processes such as atmospheric noise, radioactive decay, or thermal noise.
The random numbers generated by a TRNG are truly random.
They are completely unpredictable and uniformly distributed.
They are slow and expensive to implement.
Pseudo-Random Number Generator (PRNG)
Generates random numbers using a deterministic algorithm.
The random numbers generated by a PRNG are not truly random.
They are predictable and reproducible.
They can be initialized with a seed value, which determines the sequence of random numbers generated.
They are fast and efficient.
Some commonly used functions in the random module are:
random() # generates a random float number between 0 and 1.
randint() # generates a random integer number between two specified integers.
uniform() # generates a random float number within a specified range.
seed() # initializes the random number generator.
randrange() # generates a random integer number within a specified range with a step.
# Syntax: random.randrange(start, stop, step)
choice() # returns a random element from a sequence.
choices() # returns a random sample of elements from a sequence with replacement.
sample() # returns a random sample of elements from a sequence without replacement.
shuffle() # shuffles the elements of a sequence.
Example:
# import the random module
import random
# generate a random float number between 0 and 1
print(random.random()) # Output: 0.6394267984578837
# generate a random integer number between 1 and 10
print(random.randint(1, 10)) # Output: 7
# generate a random float number between 1 and 10
print(random.uniform(1, 10)) # Output: 5.123456789012345
# initialize the random number generator with a seed value
random.seed(10)
# generate a random integer number between 1 and 10
print(random.randint(1, 10)) # Output: 10
# generate a random integer number between 1 and 10 with a step of 2
print(random.randrange(1, 10, 2)) # Output: 7
# generate a random element from a sequence
print(random.choice([1, 2, 3, 4, 5])) # Output: 3
# generate a random sample of elements from a sequence with replacement
print(random.choices([1, 2, 3, 4, 5], k=3)) # Output: [3, 1, 5]
# generate a random sample of elements from a sequence without replacement
print(random.sample([1, 2, 3, 4, 5], k=3)) # Output: [3, 1, 5]
# shuffle the elements of a sequence
arr = [1, 2, 3, 4, 5]
random.shuffle(arr)
print(arr) # Output: [3, 1, 5, 2, 4]
Help function#
To access the help function, follow these steps:
Enter the python interpreter by typing
python3
in the terminal.Type
help()
in the python interpreter.For example, type
help(random)
to get help on the random module. This will display the help information for the random module.To quit the help function, type
quit()
.To quit the python interpreter, type
exit()
orquit()
.
PYTHON LIBRARIES#
Python libraries are collections of functions and methods that allow you to perform many actions without writing your code.
Python modules are files that contain Python code. They can define functions, classes, and variables.
Python has a vast collection of libraries and modules that can be used to perform various tasks.
Installing a library#
To install a library, you can use the
pip
command (Python package manager)For example, to install the
numpy
library, you can use the following command in the terminal:python3 -m pip install numpy
To install
pip
, you can use the following command in the terminal:python3 -m pip --version # Check if pip is installed python3 -m ensurepip --user # Install pip python3 -m pip install --upgrade pip # Upgrade pip
math
#
Provides mathematical functions.
# import the math module
import math
print(math.sqrt(16)) # Output: 4.0
numpy
#
Provides support for large, multidimensional arrays and matrices.
python3 -m pip install numpy
# import the numpy module
import numpy as np
# Create a simple array
arr = np.array([1, 2, 3, 4, 5])
# Multiply each element by 2
result = arr * 2
# Print the result
print(result) # Output: [ 2 4 6 8 10]
matplotlib
#
Provides plotting functions.
# import the matplotlib module
import matplotlib.pyplot as plt
# Create a simple plot
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title("Simple Plot")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
pandas
#
Provides data structures and data analysis tools.
import pandas as pd
# Create a simple DataFrame
data = {
"Name": ["John", "Anna", "Peter", "Linda"],
"Age": [25, 36, 29, 42],
"City": ["New York", "Paris", "Berlin", "London"],
}
df = pd.DataFrame(data)
# Display the DataFrame
print(
df
) # Output: Name Age City 0 John 25 New York 1 Anna 36 Paris 2 Peter 29 Berlin 3 Linda 42 London
# Accessing a specific column
ages = df["Age"] # Access the 'Age' column
print(ages) # Output: 0 25, 1 36, 2 29, 3 42, Name: Age, dtype: int64
KEYWORDS#
Reserved words#
Keywords are reserved words in Python that have special meaning and cannot be used as variable names.
Keywords are case-sensitive.
Python has 35 keywords.
You can get a list of keywords using the
keyword
module.You can check if a word is a keyword using the
iskeyword()
function.You can get a list of built-in functions and variables using the
builtins
module.You can check if a word is a built-in function or variable using the
dir()
function.You can check if a word is a built-in function or variable using the
is
identity operator.
Example:
# import the keyword module
import keyword
print(keyword.kwlist) # List of reserved words
print(keyword.iskeyword("break")) # Output: True
# import the builtins module
import builtins
print(dir(builtins)) # List of built-in functions and variables
print(ArithmeticError is builtins.ArithmeticError) # Output: True