Expression
A combination of values (E.g. 5) and operators (E.g. +), which will be evaluated to a value
Example
9 * 98 # multiplies the numbers (result = 882)
/ 1 # divides by 1 (so the value stays 882)
print() # displays the result in the console
print(9*98/1)
Result
882.0
Operators Precedence
Is the order of operations (PEMDAS) – If you have multiple operations, E.g. (+ and /) in the same expression, the division will be evaluated first, then the addition because of the PEMDAS rule
The order is:
()Parentheses**Exponentiation*Multiplication/Division+Addition-Subtraction
Statement
An instruction that gets executed by the Python interpreter
- Simple Statement is written in one line (It does simple operation)
break– Terminates the closest for or while looppass– Used as placeholderdel– Deletes objectimport– Finds, loads and initializes a modulereturn– Sends the result of a function to a callercontinue– Ends the current iteration of a loop
- Compound Statement
if– Executes a block of code based on a conditionwhile– An uncontrolled loop (Number of iterations is unknown)for– A controlled loop (Number of iterations is known)try– Used for exception handling
Value
The actual data, and Python has a few data types. We can store those data types in variables.
Variable
A container that stores values, it must start with a letter or the underscore symbol and contains alpha-numeric-underscore only (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012456789_).
Some Data Types
Data Type is an attribute that tells the computer system how to interpret its value. Computer systems use different data types and each data type has a fixed or not-fixed length. E.g, an Integer (int) is a common data type that represents numbers data without fractions, the size of int is fixed (4 bytes) in many systems. Some data types like Text (string) are not-fixed, but it has a max size like 65,535 bytes (Sometimes, data types with fixed sizes like Integer (int) can change based on the implementation)
int(Number)
- 5
- 61111
- 7988787
float(Number)
- 0.5
- 0.841
- 9.20000008884
bool- True
- False
list(Ordered collection of items – mutable)- [1,2,3,4,’hello’]
tuple(Ordered collection of items – immutable)- (1,2,3,4,’hello’)
set(Unordered collection of items – no duplicates)- {1,2,3,4,’hello’}
dict(Collection of sequence key:value – no key duplicates)- {1:”test”,2:”test”}
string- ‘Hello’
- “Hello”
Mutable
Something is changeable, whereas immutable is something we cannot change.
Assign value to variable
The assignment operator in Python is = symbol; Usually, the variable is on the left side, and the value is on the right side.
Example
var = 1 # Integer variable storing the number 1
var20 = ‘python’ # String variable storing the text ‘python’
var_99 = [1,2,3,4] # List variable containing four numbers
VaR = {1,2,4,5} # Set variable containing unique numbers (unordered collection)print(var) # Print the value stored in variable ‘var’
print(var20) # Print the string stored in ‘var20’
print(var_99) # Print the list stored in ‘var_99’
print(VaR) # Print the set stored in ‘VaR’
var = 1
var20 = 'python'
var_99 = [1,2,3,4]
VaR = {1,2,4,5}
print(var)
print(var20)
print(var_99)
print(VaR)
Result
1
python
[1,2,3,4]
{1,2,4,5}
Output & Input
You can output data using the print function, and you can get the user’s data using the input function.
Example
temp_name = input(“Enter your name: “) # Prompt the user to type their name and store it in the variable temp_name
print(“Your name is: ” + temp_name) # Concatenate the text “Your name is: ” with the value of temp_name and print it
temp_name = input("Enter your name: ")
print("Your name is: " + temp_name)
Result
Enter your name: Sara
Your name is Sara
Function
A reusable block of code, you can define a function using the def statement, followed by the name of the function, then (): and the body has to be indented (spaces or tabs). To call the function, use the function name + ().
Example
def temp_function(): # Define a function named temp_function
print(“Hello World”) # Print the message “Hello World”temp_function() # Call the function to execute its code
def temp_function():
print("Hello World")
temp_function()
Result
Hello World
Also, you can define a function that takes arguments using the def statement, followed by the name of the function, then add your parameters inside (): and the body has to be indented (spaces or tabs). To call the function, use the function name + the arguments inside ().
Example
def temp_function(param1): # Define a function named temp_function with one parameter called param1
print(param1) # Print the value passed into param1temp_function(“Hello World!”) # Call the function and pass the string “Hello World!” as the argument
def temp_function(param1):
print(param1)
temp_function("Hello World!")
Result
Hello World!
Argument
A value that are passed to a function when it is called.
Example
def temp_function(param_in): # Define a function with one parameter called param_in
print(param_in) # Output the value stored in param_intemp_function(“Hello Jim”) # Call the function and pass “Hello Jim” as the argument
def temp_function(param_in):
print(param_in)
temp_function("Hello Jim")
Result
Hello Jim
Parameter
The names of the data declared in the function’s parenthesis.
Example
def temp_function(param_in): # Define a function called temp_function with one parameter named param_in
print(param_in) # Print the value passed into the parameter param_intemp_function(“Hello world”) # Call the function and pass the string “Hello world” as the argument
def temp_function(param_in):
print(param_in)
temp_function("Hello world")
Result
Hello world
Indentation
This refers to the leading white-space (Spaces and tabs) at the beginning of the code.
Example
if 1 == 1: # Check if the value 1 is equal to 1 using the equality operator ==
print(“True”) # If the condition is True, print the text “True”
if 1 == 1:
print("True")
Result
True
Pass By Value
Mutable objects are passed by values to function
Example
def change_value(param_in): # Define a function that takes one parameter called param_in
param_in = param_in * 10 # Multiply param_in by 10 and store the result in the local variable param_invar = 10 # Create a variable var and assign it the value 10
print(“Value before passing: “, var) # Print the value of var before calling the function
change_value(var) # Call the function and pass var as an argument
print(“Value after passing: “, var) # Print the value of var again (it remains unchanged)
def change_value(param_in):
param_in = param_in * 10
var = 10
print("Value before passing: ", var)
change_value(var)
print("Value after passing: ", var)
Output
Value before passing: 10
Value after passing: 10
Pass By Reference
Immutable objects are passed by reference to function
Example
def change_value(param_in): # Define a function that takes one parameter called param_in
param_in.append(99) # Append the number 99 to the list param_in (modifies the original list)var = [0, 1, 2, 3, 4, 5] # Create a list variable var with initial values
print(“Value before passing: “, var) # Print the list before calling the function
change_value(var) # Call the function and pass var; list is modified inside the function
print(“Value after passing: “, var) # Print the list after function call; shows the updated list
def change_value(param_in):
param_in.append(99)
var = [0,1,2,3,4,5]
print("Value before passing: ", var)
change_value(var)
print("Value after passing: ", var)
Output
Value before passing: [0, 1, 2, 3, 4, 5]
Value after passing: [0, 1, 2, 3, 4, 5, 99]
Print function()
The print function outputs a string representation of the object to the standard output. If the object contains __str__ method, it will be called by the print function
Example
class string: # Define a class named string
def __init__(self, var): # Constructor that initializes the object with a value var
self.var = var # Store the value in the instance variable self.vardef __str__(self): # Define string representation for printing
return f'{self.var}’ # Return the value of self.var as a stringdef __eq__(self, other): # Define equality comparison between two string objects
if isinstance(other, string): # Check if ‘other’ is an instance of string
return self.var == other.var # Compare their stored var values
return False # If other is not a string object, return False
print(string(“test”) == string(“test”)) # Create two string objects, compare them and output the result
class string:
def __init__(self, var):
self.var = var
def __str__(self):
return f'{self.self.var}'
def __eq__(self, other):
if isinstance(other, string):
return self.var == other.var
return False
print(string("test") == string("test"))
Output
True