You are on page 1of 8

Python’s Crash Course Notes

Chapter 02 - Variables and Simple Data Types 2


Variables 2
Strings 2
Numbers 2
Operators 2
Comments 3

Chapter 03 - Introducing Lists 3


Indexes 3
Manipulating a list 3
Organizing a list 3

Chapter 04 - Working with Lists 4


Looping 4
Special functions 4
Slicing a list 4
Copying a list 4
Tuples 4

Chapter 05 - If Statements 5
if Statements 5

Chapter 06 - Dictionaries 5
Looping 6
Nesting 6

Chapter 07 - User Input and While Loops 6


While Loops 6

Chapter 08 - Functions 7
Type of arguments 7
Optional arguments 7
Passing a list 7
Functions in Modules 7

Chapter 09 - Classes 8
Inheritance 8
Chapter 02 - Variables and Simple Data Types

Variables
● Names can be letters, numbers and underscore
● Can’t start with a number
● Remember, variables are like ‘labels’ (memory references) not as box containers
● B.p.: lowercase
● global allows you to modify the variable outside of the current scope

Strings
● String: series of characters
● Can use “ or ‘, doesn’t matter.
● Special functions:
○ title() - capitalize every initial word letter
○ capitalize() - capitalize first letter of first word
○ upper() - uppercase for all letters
○ lower() - lowercase for all letters
○ lstrip(), rstrip(), strip() - remove left, right or both ‘white spaces’
● Format strings using letter f as prefix (i.e. f”hello world”)
○ Works for python 3.6 and above
○ Before it was used “{}”.format(variable_name)
● Special escape values:
○ \t - tab
○ \n - new line

Numbers
● They can be integers & floats
● Python defaults to a float in any operation that use a float
● Dividing two integers results always in a float
● You can use ‘_’ underscore in numbers to make them more readable
○ Works for python 3.6 and above
● You can assign values to more than one variable in a single line
○ a, b, c = 1, 2, 3
● Constants variables use all capital letters.

Operators
● / classic division
○ >>> 5/2
○ 2.5
● // floor division
○ >>> 5//2
○ 2
● % modulo (division)
○ >>> 5 % 2
○ 1
● The order of operations (precedence) is similar to that of mathematics:
○ the ** operator is evaluated first;
○ the *, /, //, and % operators are evaluated next, from left to right;
○ and the + and - operators are evaluated last (also from left to right).
○ You can use parentheses to override the usual precedence if you need to

Booleans
● when used in conditions,
○ 0 (int), 0.0 (float), and '' (empty string) are considered False
○ all other values are considered True

Comments
● Use # for a comment in one line

Chapter 03 - Introducing Lists


● In python, a list is defined by square brackets []
○ It can be created empty (list_name = [])
● You can create lists using the list() function

Indexes
● positions starts at 0
● Negative index positions starts at the end of the list

Manipulating a list
● .append(new_element) - Add element at the end of a list
● .extend(list_element) - Add a list of elements (list_element) to the list
● .insert(i, new_element) - inserts element at index i
● Removing items
○ del list[i] - removes item at index i
○ list.remove(xxx) - removes item with value xxx
● item = list.pop() - removes last item and assigns it to a variable
Organizing a list
● .sort() - from A to Z
● .sort(reverse=True) - from Z to A
● sorted(list) - sort temporarily a list without modifying it
● .reverse() - reverse a list
● len(list) - returns number of items in the list
● sorted(list,reverse=True) - reverse a list temporarly

Chapter 04 - Working with Lists

Looping
for item in list:
code
else:
code

Special functions
● range(start, end, step) - generate a series of numbers
○ Remember that range stops when reach ‘end’ (doesn’t process it)
○ Step size - value to bypass numbers when generating them
● Maths
○ min()
○ max()
○ sum()

Slicing a list
● List[start:end]
○ start is inclusive, end is excluded
○ If start is empty, starts at the beginning of the list
○ If end is empty, finish at the end of the list
○ If using a negative index, starts at the end of the list
● [::n]
○ nothing for the first argument, nothing for the second, and jump by n
○ i.e.
■ nums = [1, 2, 3, 4, 5, 6, 7]
■ print(nums[::-3])
■ >> [7, 4, 1]
Copying a list
● We can use an empty slice like list[:] and assign to a variable
○ i.e. newlist = oldlist[:]
○ If dont slicing -> var1 will link to var2 instead of copying.

Tuples
● They are immutable lists (can’t change)
○ Can’t change but we can assign to the variable a new tuple
● Use parentheses () instead of square brackets []
● For a one item tuple you need to add a comma
○ i.e. new_tuple = (4,)

Chapter 05 - If Statements
● == to check equality
● != to check inequality
● and
● or
● item in list - check if an item is in a list
● item not in list - check if an item is not in a list

if Statements
if conditional_test:
do something
elif conditional_test:
do something
else:
do something

● elif - use as much as you need


● else - it’s optional

You can use ternary operation as:


value_when_true if condition else value_when_false

Chapter 06 - Dictionaries
● Dictionaries are wrapped in braces {}
● Collection of key-value pairs.
● Creating a dictionary like:
○ ndict = {‘keya’: 1, ‘keyb’: 2}
○ or
○ ndict = {}
○ ndict[‘keya’] = 1
○ ndict[‘keyb’] = 2
● Accessing values
○ through the key
■ ndict[‘keya’]
○ through .get() function
■ ndict.get(‘keyz’,’value if key doesn’t exist’)
● Removing a key-value pair
○ del ndict[‘keya’]

Looping
for k, v in ndict.items():
print(‘Key is {k}’)
print(‘Value is {v}’)

● ndict.items() - returns key-value pair


● ndict.keys() - returns a list with all keys
● ndict.values() - returns a list with all values
● Special functions
○ Use sorted() to order a list result
■ i.e. sorted(ndict.keys())
○ Use set() to have a list of unique values
■ i.e. set(ndict.values())

Nesting
● A list of dictionaries
● A dictionary with lists
● A dictionary with dictionaries

Chapter 07 - User Input and While Loops


var_name = input(message_to_show)

● Use int() to accept numerical input


● % modulo operator (divides two numbers and returns the remainder)
While Loops
while condition:
action(s)

● the condition is called a flag


○ An empty string is considered False
○ None is considered False
● with continue word, you start the loop again regardless on where you are inside the loop
● with break word, you exit from the loop

● Use while loops with lists / dictionaries when you need to modify them (instead of for
loops)
○ Specially when removing items

Chapter 08 - Functions
def function_name(arguments):
code

● When calling a function, you pass parameters


● When you use those variables inside the function, they are called arguments

Type of arguments
● Positional arguments: maintains the order of arguments
● Keyword arguments: name-value pair passed to a function.
● Undefined arguments (Must be placed the last in the function definition)
○ Tuple: *args
○ Dictionary: **kwargs (key-word args)

Optional arguments
● Use default value to make an argument optional
● Must go at the end of the arguments

Passing a list
● Inside the function, the list can be updated
● If you want to not update the list, pass a copy of the list
○ i.e. function_name(list[:])
Functions in Modules
● import module_name
○ python opens the file and copy all functions into the program
○ use module_name.function_name()
● import module_name as alias
○ similar to the previous one but giving an alias
○ use alias.function_name()

● from module_name import function_name_01, function_name_02


○ python copies only the functions specified
○ you can call the function directly
● from module_name import function_name_01 as alias
○ similar to the previous one but giving an alias
○ use alias.function_name()

● from module_name import *


○ python imports ALL the functions
○ Not recommended

Chapter 09 - Classes
class Name_class:
def __init__(self):
code

● Class names are capitalized


● __init__ function is to initialize the instance

Inheritance
class Name_class(MasterClass):
def __init__(self):
super().__init__(self)
code

You might also like