Basics Flashcards
1
Q
Python
A
- popular OOP language
- used for :
- web development
- scripting (sorta)
- software development
- mathematical operations (such as data science)
- it can be used on lots of platforms (windows, linux, mac, raspberry, pi, etc)
- its syntax is similar to english
- uses new line to execute codes
- uses indentiation
- interpreted language (no compiler needed)
2
Q
Comments
A
- used to explain code
- use to prevent line of code from executing
- # - to comment single line of code
- ””” used to comment
bolck of codes””” - multiline string
3
Q
Variables
A
- placeholders/containers for storing data values
- no variable decleration in python
- variable is created when a value is assigned to it
- can only be alpha-numeric
- cannot start with number
- is case-sensitive
- cnoot use space or ‘-‘
-
GLOBAL variables
- create outside of functions and can be access anywhere in the file
- to create a global variable inside a function, use keyword global
- example:
- def myfunc():
global x
x = “fantastic”
- def myfunc():
-
LOCAL variables
- created inside a function and can only be accessed inside that function
4
Q
Data Types
A
- Text Type: str
- Numeric Types: int, float, complex
- Sequence Types: list, tuple, range
- Mapping Type: dict
- Set Types: set, frozenset
- Boolean Type: bool
- Binary Types: bytes, bytearray, memoryview
5
Q
Numbers
A
- 3 types of number:
-
int
- whole number without decimals, can be + or -
- convert to interger using int(x)
-
float
- decimal number, can be + or - or scientific (number with ‘e’ for power of 10)
- convert to float using float(x)
-
complex
- number with imaginary part written with a ‘j’
- x = 3+5j
- convert to complex using complex(x)
- cannot convert from complex to other number type
-
int
- random numbers a randomely generated using functions from python random library such as random.randrange
6
Q
Casting
A
- converting one data type to another
- int() - converts variable to integer
- float() - converts variable to float
- str() - converts variable to string
7
Q
String
A
- assign string to a variable using either single quote or double quotes
- strings are arrays which mean they can be filtered via index
- string[index_number]
- uses methods such as .lower(), .strip()
- can be concacted: string1 + string2
- use escape character to include insert illegal characters (")
- or block of string using triple single quotes or triple double quotes
- explame:
- x = ‘string’
- x = “string”
- x = ‘'’block
- of
- string’’’
- x = “"”block
- of
- string”””
8
Q
Boolean
A
- True or False values
- bool(x) to evaluate values
- most values are true except for 0 (or any empty collections such as list dict set etc)
9
Q
Operators
A
- performs operations on variables/values
- Arithmetic operators:
- used on numbers to do mathematical operations:
- Addition x + y
- Subtraction x - y
- * Multiplication x * y
- / Division x / y
- % Modulus x % y
- ** Exponentiation x ** y
- // Floor division x // y
- used on numbers to do mathematical operations:
- Assignment operators:
- used to assign values to variables:
- = x = 5 / x = 5
- += x += 3 / x = x + 3
- -= x -= 3 / x = x - 3
- *= x *= 3 / x = x * 3
- /= x /= 3 / x = x / 3
- %= x %= 3 / x = x % 3
- //= x //= 3 / x = x // 3
- **= x **= 3 / x = x ** 3
- &= x &= 3 / x = x & 3
- |= x |= 3 / x = x | 3
- ^= x ^= 3 / x = x ^ 3
- >>= x >>= 3 / x = x >> 3
- <<= x <<= 3 / x = x << 3
- used to assign values to variables:
- Comparison operators:
- used to compare 2 values/variables:
- == Equal x == y
- != Not equal x != y
- > Greater than x > y
- < Less than x < y
- >= Greater than or equal to x >= y
- <= Less than or equal to x <= y
- used to compare 2 values/variables:
- Logical operators:
- used to combine conditional statements:
- and Returns True if both statements are true - x < 5 and x < 10
- or Returns True if one of the statements is true - x < 5 or x < 4
- not Reverse the result, returns False if the result is true - not(x < 5 and x < 10)
- used to combine conditional statements:
- Identity operators:
- used to compare object values (if they are the same or not):
- is Returns True if both variables are the same object - x is y
- is not Returns True if both variables are not the same object - x is not y
- used to compare object values (if they are the same or not):
- Membership operators:
- used to test if values are present or absent:
- in Returns True if a sequence with the specified value is present in the object - x in y
- not in Returns True if a sequence with the specified value is not present in the object - x not in y
- used to test if values are present or absent:
- Bitwise operators:
- used to compare binary numbers:
- & AND - Sets each bit to 1 if both bits are 1
- | OR - Sets each bit to 1 if one of two bits is 1
- ^ XOR - Sets each bit to 1 if only one of two bits is 1
- ~ NOT - Inverts all the bits
- << Zero fill left shift - Shift left by pushing zeros in from the right and let the leftmost bits fall off
- >> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
- used to compare binary numbers:
10
Q
Lists
A
collection that is:
- mutable (can be changed/edited)
- list_name.append() - to add item
- list_name[position_number] - to edit
- list_name.insert(indiex, object) - add object at specified position
- list_name.remove(item_to_remove)
- del list_name[index]
- list_name.clear() - remove all items
- list_name.pop() - move last or psecified index
- allows duplicate
- written with squarish brackets []
- indexed
- to make a copy of list, use .copy() metod or list will onl be referenced
11
Q
Tuples
A
collection that is:
- unmutable (cannot be changed/edited)
- written with round brackets ()
- allows duplicate
- indexed
- to create tuple with 1 item: (item, )
- tuple() - constructor to make a tuple
- tuple methods:
- count()
- index()
12
Q
Sets
A
collection that is:
- written with curly brackets
- unordered and unindexed
- no duplicates allowed
- cannot change/edit items but can add new items
- .add() - add 1 item
- .update() - add more than 1 items
- can remove items:
- .remove() - will raise error is item doesn’t exist
- .discard() - won’t error out if item doesn’t exist
- .pop() - to remove last item
- combine 2 sets into a 3rd one using set3 = set1.union(set2) or .update()
- this will remove duplicates
13
Q
Dictionaries
A
collection that is:
- key/value pair
- mutable
- indexed and unordered
- written with curly brackets
- access values by referring to key name or call .get(key_name) method
- loop through a dict:
- for x in thisdict: - loop though keys in dict
- for x in thisdict.values(): - loop through values
- for x, y in thisdict.items(): - loop through both keys and values
- add/edit item to dict: dict_name[“key”] = “value”
- remove item: dict_name.pop(‘key’) or del dic_name[‘key’]
- duplicate dict using .copy() method
14
Q
If Else
A
If:
- if conditions are met then execute the following codes
- uses python operators (logical, comparison, etc)
ElIf
- if previous if or elif statement is not met, try this 1
Else
- if none of the previous conditions are met then execute this
example:
if a == b:
print(‘a equal b’)
elif a < b:
print(‘a less than b’)
else:
print(‘a greater than b’)
- conditional expression:
- print(“A”) if a > b else print(“B”)
15
Q
While Loops
A
- execute code(s) until looping codition is no longer true
- use break to stop loop early
- use continue to stop/skip current iteration and move on to next one
- use else to execute code when while loop is done, treats the while loop like an if else statement
- use pass to replace code(s) in loop block
- example:
while a < b:
# code here
else:
# code here