Main Learnings:
- Python, its syntax, modules, ecosystem, libraries and tools
- Error and exception handling
- Object-oriented programming concepts
Table of Contents
- Syntax
- Variables
- Data Types
- Type Casting
- Input/Output
- Operators
- Control Flow
- Functions
- Data Structures
- Args & Kwargs
Introduction:
Python is a popular high-level programming language that has easy-to-use syntax similar to English. It is far more simplistic compared to other lower-level languages, such as C or Java. This allows for developers to focus on solving the problem at hand, instead of worrying about small nuances within their code. Thus, applications can be developed faster and are easier to maintain. To install Python onto your computer, visit the official website at https://www.python.org/downloads/.
Syntax
Whitespace and indentation in Python is crucial to its syntax. Every newline created using the "Enter" key is considered a different line of code. If you are familiar with C, this is equivalent to ";", but in Python it is just implicit with every newline entry. Any additional whitespace in a line of code is ignored, and will execute as if there is only 1 space. Indentation determines the scope of the code, and which block it belongs to, similar to "{" and "}" in C. Comments are supported in Python, and can be used to explain code, write notes or write TODO tasks for later. To write single-line comments, use "#", and anything after it on that line will be commented out. For multiline comments, use 3 apostrophes (''') to start and end your comments.
python
# single line of code
x = 10 + 2
+4
print(x) # prints 12
# indentation example
x = 10
if x == 10:
# executes if x is 10
print("x is 10")
else:
# executes if x is not 10
print("x is not 10")
'''
multi
line
comments!
'''
Variables
Variables are an essential part to any programming language, as it allows you to manipulate data. Python variable declaration is very simple, with the structure of name = value
, where name
is the variable name and value
is the desired value of that variable. It can be updated by using the same syntax. Variable naming must be informative to let you and other programmers know what the variable stores. Common naming conventions for variables in coding are camelCase
and snake_case
. camelCase
has each word joined without spaces, and each word (except the first one) starts with a capital letter. snake_case
has each word joined with an "_" instead of a space, with all lowercase letters. It is important to be consistent with the naming convention you choose, so you don't confuse yourself or other developers.
python
# variable assignment and updating
x = 10
print(x) # prints 10
x = 20
print(x) # prints 20
# camelCase
thisIsCamelCase = True
# snake_case
this_is_snake_case = "All lowercase letters and joined by an underscore"
Data Types
At its core, data types tells the computer how to interpret its value. The 5 main data types in Python are
numeric, sequence, dictionary, boolean, and set
. Some data types can be extended; for example, numeric can extend toint
or float
, sequence can extend to list
or tuple
, etc. For more details on the different data types, visit this reference. To determine the type of a variable, use the type()
function, which accepts a variable and returns its data type.As the name suggests, the numeric type classifies types of numbers. The sequence type allows for indexing based on their order in the sequence. To index into the sequence, use square bracket notation, and keep in mind that indexing is zero-based in Python, meaning the first element is index 0, the second element is index 1, and so on. The dictionary data type is essentially just a hash table, storing an unordered collection of key-value pairs. It is created using "{}", and uses ":" to assign a key to its value, with a comma separating each key-value pair. Each value is accessed by its key, again using square bracket notation. Boolean data types are just the booleans "True" and "False". The set data type is similar to the mathematical set, where it only contains non-duplicated values. It is created using "{}", with ecah value separated by a comma. It is unordered and cannot be indexed into.
python
# numeric types
type(10) # int
type(10.0) # float
type(10+1j) # complex
# sequence types
l = [1,2,3]
type(l) # list
t = (4,5,6)
type(t) # tuple
l[0] # 1
t[2] # 6
# dictionary type
hashTable = {'key': 'value', 'anyTypes': True, 4: False}
type(hashTable) # dict
hashTable['key'] # 'value'
hashTable[4] # False
# boolean type
type(True) # bool
type(False) # bool
# set type
s = {1,4,-6,'unique',True}
type(s) # set
Type Casting
Type casting is when one data type is converted to another data type, if they are compatible. There are explicit and implicit data type conversions. Implicit conversion means it is done automatically by Python, without the programmer doing anything. For example, this can happen in comparisons or addition of int
and float
. Programmers can perform explicit type conversion using Python functions, such as str()
, int()
, list()
, etc. They convert it to its respective data type.
python
x = 10
y = str(x) # the string '10'
a = '100'
b = int(a) # the integer 100
arr = [1,2,2,3]
new_set = set(arr) # the set {1,2,3}
Input/Output
A common method to obtain input from the user is using the input()
function. Any text inside the function will be displayed to the user as a prompt. Note that any input recieved will be treated as a string data type, even if given an integer or float. To convert them, use explicit conversion, mentioned in the previous section. As for output, the print()
function can be used to print information to the console.
python
name = input("Your name: ")
num1 = input("First number: ")
num2 = input("Second number: ")
print(name) # prints value of the name variable
print(num1 + num2) # prints concatenation of both nums
print(int(num1) + int(num2)) # prints addition of both nums
input()
prompts the user for some input, print()
prints its arguments to the screenOperators
Operators are symbols that perform certain actions. There are mathematical and logical operators in Python, which behave differently. Math operators are just like the ones found in elementary school math:
addition, subtraction, multiplication, division
, etc. Logical operators are used to evaluate if a condition isTrue
or False
. Logical operators are used to control the flow of the program; for example, whether or not to execute this block of code. Below is a table of the most frequently used math and logical operators in Python, along with an example.Operator | Meaning | Example | Result |
---|---|---|---|
+ | Addition | 1 + 1 | 2 |
- | Subtraction | 2 - 2 | 0 |
* | Mutliplication | 3 * 3 | 9 |
/ | Division | 4 / 4 | 1 |
and | True if both are True | True and True | True |
or | True if either are True | True or False | True |
not | Opposite Boolean value | not True | False |
Control Flow
Control flow refers to how code in a program are executed. Different decisions in the program need to be made, which ultimately changes how the program performs. The 2 different types of control flow are conditional and iterative. Some examples of a conditional statement is if
, elif
(else if), else
, etc. Some examples of iterative control flow, mostly referring to loops, are the for
and while
loop.
if
checks if the condition is True, and then performs the following code block. elif
(also known as "else if" in other languages) executes if it is True and the previous statements were False. else
is the catch-all statement, and executes if all previous conditions were False.
python
x = 10
y = 9
if x > y:
# this executes since x > y
# nothing else will execute since this has already been executed
print("x is greater than y")
elif x < y:
# this doesn't execute
print("x is less than y")
else:
# this doesn't execute
print("x is equal to y")
The for
loop checks if a condition is met, and then continuously runs as long as the condition is met. The while
loop executes a block of code repeatedly for an unknown number of times until the condition is no longer met. It is important to note that in a while
loop, there needs to be something within the loop that can make the condition evaluate to false; otherwise, you are left with an infinite loop.
python
# for loop
for i in range(0,3):
print(i)
# prints 0, 1, 2
# while loop
j = 0
while j != 3:
print(j)
j += 1
# breaks when j == 3
# prints 0, 1, 2
The match
statement is a more clean and concise way to check multiple conditions. Think of it as an if
, elif
, and else
statements, just using match
and case
. case
can be used to represent theif
, elif
and else
statements. Following the case
is the condition, and underneath is the block of code that is executed if it evaluates to true. It is best visualized, so see the example below.
python
status = 200
match status:
case 200 | 201:
# executes if status == 200 or status == 201
# is executed since status == 200
print("Success")
case 404:
# doesn't execute since status == 200 and an execution already occurred
print("Not found")
case 500:
# doesn't execute since status == 200 and an execution already occurred
print("Server Error")
case _:
# executes if all above conditions are false
# equivalent to "else"
print("Unknown")
Loop control statements change the normal execution flow within the loop. break
stops the loop entirely, essentially "breaking out" of the loop. continue
skips the rest of the code in the current iteration of the loop, but does not break out of the whole loop. For example, if you were on the first iteration, there was a continue
statement, it would skip over the remaining code for the first iteration, but then continue on with the next iteration. pass
performs no operation, so it is used when there is no action but syntactically, there needs to be code there.
python
# break
for i in range(10):
if i == 2:
break # breaks out of for loop if i is 2
# continue
# skips print statement when i == 1, doesn't print anything
for i in range(3):
if i == 1:
continue
print("i is" + i)
# pass
# something is required below the if statement
for i in range(7):
if i == 0:
pass
else:
print("i is not 0")
Functions
A best practice in coding is DRY;
Don't Repeat Yourself
. This means creating clean code that has little redundancy. Functions enable for code reuse; you can call the function as many times as you'd like. It is defined using thedef
keyword, followed by the function name of your choice. Just ensure your function name is not any Python keyword. Followed by the name is its arguments enclosed in parentheses, which can be anything upon function call. Then after a colon is the actual code the function performs.python
# sample function returns the sum of 2 numbers
def add(x, y):
return x + y
print(add(4, 5)) # prints 9
print(add(7, 1)) # prints 10
Data Structures
Data structures are essential to any programming language. There are built-in and user-defined data structures that the programmer can access. Some built-in data structures in Python include lists, dictionaries, tuples, sets. User-defined data structures are ones that the programmer can create, that are not provided by the language. This can be stacks, trees, linked lists, graphs, etc.
Lists are a dynamic array of elements, which can be any data type, with each item separated by a comma. Lists are 0-indexed, meaning the first index is 0, the second index is 1, and so on. The * operator can be used to unpack lists, meaning you can spread the elements out. Lists have numerous methods that can be used; pop()
, append()
, and many more. pop(x)
returns and removes the x-th indexed element in the list, and a no paramter function call defaults to the last element. append(x)
adds the element x to the end of the list.
python
# lists
list1 = [1, "any type", True]
list1.pop() # removes True from the list
print(list1) # [1, "any type"]
list1.pop(0) # removes 1 from the list
print(list1) # ["any type"]
list1.append(18)
print(list1) # ["any type", 18]
Args & Kwargs
Args & kwargs are used to store a variable number of arguments in the function header. This can be denoted as *args
and **kwargs
respectively.
python
def ex1(*args):
total = 0
for x in args:
total += x
return total
print(ex1([1,2,3])) # prints 6
def ex2(**kwargs):
total = 0
for k, v in kwargs.items():
total += v
return round(total, 2)
print(ex2(eggs=5.99, bread=2.99, smoothie=3.97)) # prints 12.95