🎁GET 20% OFF Using Code 👉SCHOOL👈 Until End 2024🎁

Comparison Operators

Comparison operators compare two values which can be numbers or strings.

Table : Comparison Operators

ComparisionNameExample
==Equalnum1 == num2
!=Not Equalnum1 != num2
>Greater Thannum1 > num2
<Less Thannum1 < num2
>=Greater Than Or Equal Tonum1 >= num2
<=Less Than Or Equal Tonum1 <= num2

Comparison Operators

Sample Codename1 = “John”
name2 = James”
print(name1 == name2) # Displays False
print(name1 == 10) # Displays False
num1 = 12
num2 = 22
print(num1 > num2) # Displays False
print(num1 == 10) # Displays False
# Type Some Code

Assignment Operators

variables have the same naming convention where the variable is defined. Therefore arithmetic types are scalar types. Arrays (list, tuple and range) are aggregate types.

Table : Assignment Operators

AssignmentEquivalentDescription
num1 = num2num1 = num2Set left operand to same value on right
num1 += num2num1 = num1 + num2Addition
num1 -= num2num1 = num1 – num2Subtraction
num1 *= num2num1 = num1 * num2Multiplication
num1 /= num2num1 = num1 / num2Division
num1 %= num2num1 = num1 % num2Modulus
num1 //= num2num1 = num1 // num2Floor Division
num1 **= num2num1 = num1 ** num2Exponentiation
num1 &= num2num1 = num1 & num2Bitwise AND
num1 |= num2num1 = num1 | num2Bitwise OR
num1 ^= num2num1 = num1 ^ num2Bitwise XOR
num1 >>= num2num1 = num1 >> num2Bitwise Right Shift, Assign Left
num1 <<= num2num1 = num1 << num2Bitwise Left Shift, Assign Right
num1 := num2(num1 = num2)Assign value within expression

Assignment Operators

Sample Codenum1 = 5
num2 = 3
num_equ = num1
num_add += num2
num_equ = num1
num_sub -= num2
num_equ = num1
num_mul *= num2
num_equ = num1
num_div /= num2
num_equ = num1
num_mod %= num2
num_equ = num1
num_flo //= num2
print(num_add) # Displays 8
print(num_sub) # Displays 2
print(num_mul) # Displays 15
print(num_div) # Displays 1.66
print(num_mod) # Displays 2
print(num_exp) # Displays 125
print(num_flo) # Displays 1
# Type Some Code

Arithmetic Operators

The arithmetic operators perform addition, subtraction, multiplication, division, exponentiation, floor division and modulus operations.

Table : Arithmetic Operators

OperatorNameExample
+Addition Or Sumnum1 + num2
Subtraction Or Differencenum1 – num2
*Multiplication Or Productnum1 * num2
/Division Or Quotientnum1 / num2
%Modulus Or Division Remaindernum1 % num2
**Exponentiation Or Raising Powernum1 ** num2
//Floor Divisionnum1 // num2

Arithmetic Operators

Sample Codenum1 = 5
num2 = 3
num_add = num1 + num2
num_sub = num1 – num2
num_mul = num1 * num2
num_div = num1 / num2
num_mod = num1 % num2
num_exp = num1 ** num2
num_flo = num1 // num2
print(num_add) # Displays 8
print(num_sub) # Displays 2
print(num_mul) # Displays 15
print(num_div) # Displays 1.66
print(num_mod) # Displays 2
print(num_exp) # Displays 125
print(num_flo) # Displays 1
# Type Some Code

Chapter 3: Operators

An operator is defined to behave like a function but is restricted to specific operations on variables and values.

Some of the operators in Python are arithmetic, assignment, comparison, increment, decrement and logical.

Strings

Python strings are surrounded by either single or double quotation marks.

String literal can be displayed with the built-in print function.

Stings

Sample Codestr1 = “Hello World!”
str2 = ‘Hello World!’
print (str1, str2)

Quotes can be used inside a string only if they do not match the quotes surrounding the string.

Quotes Inside Strings

Sample Codestr1 = “It’s easy”
str2 = “Call me ‘Johnny'”
str3 = ‘Call me “Johnny”‘
print(str1, str2, str3)

Assign a multiline string to a variable using 3 quotes.

Multiline Strings

Sample Codestr1 = “””This is a double quoted
multiple line string
spanning 3 rows.”””
str1 = ”’This is a single quoted
multiple line string
spanning 3 rows.”’
print(str1, str2)

Return a part of the string using the slice syntax. To slice a string, specify the start index and end index separated by a colon. The first character has index 0.

Slicing

Sample Codestr1 = “Hello, World!”
print (str1[2:5]) # Prints from position 2 to position 5
print(str1[:5]) # Prints  from position 0 to position 5
print(str1[2:]) # Prints from position 2 to the end
print(str1[-5:-2]) # Prints from position -5 to position -2

Table : Common Functions For Manipulating Strings

FunctionDescriptionExample
upper()Returns upper casestr2 = str1.upper()
lower()Returns lower casestr2 = str1.lower()
strip()Removes beginning or ending whitespacestr2 = str1.strip()
replace()Replace a string with anotherstr2 = str1.replace(“Hello”, “Join”)
split()Split string into substrings by specified separatorstr2 = str1.split(“,”)

Strings can be combined using string concatenation via the plus “+” symbol

Concatenate Strings

Sample Codestr1 = “Hello”
str2 = “World”
str3 = str1 + str2
str4 = str1 + ” ” + str2
print(str3) # Displays HelloWorld
print(str4) # Displays Hello World

Strings and numbers can be combined using F-strings.

F-Strings Format Strings

Sample Codeage = 24
name = “John”
combined = f”My name is {name}, and I am {age} years old”
print(combined) 

Strings can be escaped using the backslash character “\”.

Table : Escape Characters

CodeDescriptionExample
\’Single Quotestr1 = ‘It\’s okay.’
\”Double Quotesstr1 = “I am \”John\”.”
\\Backslashstr1 = “Insert one \\ backslash.”
\nNew Linestr1 = “Hello\nWorld!”
\rCarriage Returnstr1 = “Hello\rWorld!”
\tTabstr1 = “Hello\tWorld!”
\bBackspacestr1 = “Hello \bWorld!”
\fForm Feedstr1 = “Hello\fWorld!”
\000Octal valuestr1 = “\110\145\154\154\157\40\127\157\162\154\144\41”
\xhhHex valyestr1 = “\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21”

Escape Characters

Sample Codestr1 = “My name is \”Johnny\” but you can call me \”John\”.”
print(str1)
# Type Some Code

Boolean

Booleans represent only 2 values, True or False. Any expression can be evaluated to get one of the two answers, True of False. Empty and zero values will be evaluated as False.

Boolean Values

Sample Codename = “John”
num1 = 5
num2 = 3
print(bool(name)) # Prints True
print(bool(num1)) # Prints True
print(num1 > num2) # Prints True
print(num1 == num2) # Prints False
print(num1 < num2) # Prints False
print(False) # Prints False
print(bool(None)) # Prints False
print(bool(0)) # Prints False
print(bool(“”)) # Prints False
print(bool(())) # Prints False
print(bool([])) # Prints False
print({}) # Prints False
# Type Some Code

Numbers

Python has 3 numeric types; int, float and complex.

An int is an integer or whole number that can be positive or negative.

Integer Numbers

Sample Codeint1 = 5
int2 = 3
int3 = -9
print(int1, int2, int3) # Prints 5 3 -9

A float of floating point number can be positive or negative, containing one or more decimals. Scientific numbers with the letter “e” can be used to indicate the power of 10.

Float Numbers

Sample Codefloat1 = 5.0
float2 = 3.0
float3 = -9.0
float4 = -27.1e10
print(float1, float2, float3, float4) # Prints 5.0 3.0 -9.0

Complex numbers are written with the letter “j” as the imaginary part.

Complex Numbers

Sample Codecomplex1 = 3+5j
complex2 = 5j
complex3 = -9j
print(complex1, complex2, complex3) # Prints (3+5j) 5j (-00-09j)
# Type Some Code

Basic Data Types

The str type is a sequence of characters inside double or single quotes.

The int type is a non-decimal whole number and can be either positive or negative.

The float type is for floating point numbers also called double with a decimal point.

The bool type can only be True or False.

Arrays are created using list and tuple or set types to store multiple values in a single variable.

NoneType has no assigned value.

You can get the data type of any object by using the built-in type function.

Data Type

Sample Codemy_string = “Hello world!”
print(my_String) # Prints Hello world!
print(type(my_string)) /# Prints str

Casting allows the variable type to be changed for the int, float and str data types.

Casting Integers

Sample Codeint1 = int(5) # Will be 5
int2 = int(3.0) # Will be 3
int3 = int(“9”) # Will be 9

Casting Floats

Sample Codefloat1 = float(5) # Will be 5.0
float2 = int(3.0) # Will be 3.0
float3 = int(“9.0”) # Will be 9.0

Casting Strings

Sample Codestr1 = str(“s5”) # Will be ‘s5’
str2 = str(“3”) # Will be ‘3’
str3 = str(“9.0”) # Will be ‘9.0’

# Type Some Code

Chapter 2: Data Types

A data type is a grouping of data values. Variables are created to store a data type. In Python, the assigning of a value will indicate the data type. PHP does not require a specific format in order to display the value.

Table : Data Types

TypeDescriptionExample
strStores a sequence of charactersname = “Jake”
intStores a non-decimal numberage = 24
floatStores a decimal point numberamount = 10.25
complexStores a complex numbercomplex_num = 2 + 4j
boolStores either True or Falseis_available = True;
listStores collection of valuesnames = [“Roy”, “Joe”, “Ben”]
tupleStores collection of valuesnames = (“Roy”, “Joe”, “Ben”)
rangeStores sequence of numbersnums = range(-1,2)
dictAssociative array or dictionaryperson = {“name”: “Jake”, “age”: 24}
setUnordered mutable set with no duplicatesno_dups = set(((“Roy”, “Joe”, “Ben”))
frozensetUnordered immutable set with no duplicatesno_dups = frozenset(((“Roy”, “Joe”, “Ben”))
bytesStores immutable sequence of bytesmy_byte = b”Some Text”
bytearrayStores mutable sequence of bytesmy_byte = bytearray([11, 22, 33])
NoneTypeStores only NoneType valuename = None
typeReturns type of objectresult = type(name)

Variables

Variables store information such as values or other variables.

Python variables do not need to be declared with any type and the type can be changed after been set.

Variables cannot start with a number because they must start with an underscore or letter. The second character can contain only alphanumeric characters or underscores.

Variable names are case-sensitive.

A variable name cannot be any of the Python keywords.

Variable Names

Sample Codename = ‘John’ #name is type str
age = 18 # age is type int
height = 5.3 # height is type float
myVarName = ‘Johnny’ # Camel Case is where each word, except the first, starts with a capital letter
MyVarName = ‘Johnny’ # Pascal Case is where each word starts with a capital letter
my_var_name = ‘Johnny’ # Snake Case is where each word is separated by an underscore
car = fruit = color = ‘red’ # Assign the same value to multiple variables on one line

Output Variables

Sample Code
print(name) # Outputs a single variable
print(name, age, height) # Outputs multiple variables, separated by a comma
print(name + myVarName + car) # Outputs multiple non numeric variables, separated by a plus symbol

# Type Some Code