Python Syntax Base
Python Syntax Base
Python Data Types
Data Type | Examples |
Integers [int] | 1, 2, 3, 432, 12, 98, -2, -1000 |
Floats [float] – Floating point numbers | 1.2, 23.9, 100.2, -199.23, -122, 993.22344 |
Strings [str] – Anything within single or double inverted commas | "Hello World", "John Doe", "test string", "this is a long sentence", "3445" |
Bool [bool] – Boolean values | True, False |
List [list] – ordered sequence of values. Values can be of any data type | [1,2,3,4], ['x', 'y', 'z'], ["Hello World", "My Name"], [True, False, 'hello'], [[1,2,3], [2,3,4,5], True, 45, -1223], [{"first_key": True, "second_key": "Hello World"}] |
Dictionary [dict] – a collection of key:value pairs. Keys can only be strings or integers. But values can be on any data type, including lists and other dictionaries. | {"firstName": "John", "last_name": "Doe"} |
None (None) – a data type that basically means nothing. | None |
Math Operators
Symbol | Operation | Example |
+ | Addition | 1 + 231 + 21 |
- | Subtraction | 100 - 23, 100 - 1231 - 21 |
* | Multiplication | 20 * 10, 43 * 32 * 678 |
/ | Division (result is always a float) | 10 / 3 |
** | Exponentiation (raise to the power of) | 2 ** 4 |
% | Modulo (remainder operator) | 10 % 2 |
// | Integer Division (result is always in int and not a float) | 100 // 33 |
Comments
# Never forget the PEMDAS rule # This is another example of a comment
In Microsoft VSCode, type Ctrl + /
to automatically comment an entire line. To comment a multiple lines, select all the lines with your mouse and then press Ctrl + /
Variables
Variables are always assigned with the variable name on the left and the value on the right of the equal sign. Variables must be assigned before they can be used. Variables can be:
- Assigned to other variables
- Reassigned at any time
- Assigned at the same time as other variables
x = 50 current_year = 2020 full_name = 'jane doe' position = "machine learning engineer" radius = 10 circumference = 2 * pi * radius # variables can be complex math operations as well new_score = 4520 highest_score = new_score # variables can be assigned to other variables linus_torvalds = 'Linus at FOSSConf, "Talk is cheap. Show me the code."'
Strings
String literals can be declared with either single or double quotes. You can have quotes inside your strings, but make sure they are different.
String Concatenation
Sequence | Meaning |
\n | Enter / Return |
\’ | Single quote |
\” | Double quote |
\t | Horizontal Tab |
\v | Vertical Tab |
\\ | Backslash |
String Escape Sequences
message = "Welcome to RST" user = "Guido" greeting = message + ", " + user # 'Welcome to RST, Guido' # You can also use the "+=" operator. (in-place operators) name = "Guido" name += "van Rossum" print(name) # 'Guido van Rossum'
Format Strings (f-strings)
items_in_cart = 8 message = f"You have {items_in_cart} items in your shopping cart." print(message) # You have 8 items in your shopping cart. net_amount = 100 GST_rate = 12 GST_amount = (GST_rate / 100) * net_amount msg = f"Your total is only ₹{net_amount + GST_amount}"
String Indexes
String indexing is zero-based.
"hello" "hello"[0] # 'h' name = "Yukihiro" name[3] # 'i' name[6] # 'r'
Converting Data Types
str(), int(), float(), list(), tuple(), dict(), set()
decimal = 3.141592653589793238 integer = int(decimal) # 3 num_string = "2134" num_int = int(num_string) # 2134 number = 2134 number_string = str(number) # "2134" python_list = [1, 2, 3] python_list_as_strings = str(python_list) # '[1, 2, 3]' my_dictionary = {"name": "John Doe", "age": 22, "address": "123, baker street"} my_dict_string = str(my_dictionary) # {"name": "John Doe", "age": 22, "address": "123, baker street"} tuple(python_list) # (1,2,3) set(python_list) # {1,2,3}
Print function
To print something on the terminal
# Print a string print("Hello World") # "Hello World" # Print number print(22) # 22 print(100 + 50) # 150 # Print the value of some variable some_variable = (20 / 3) + 155 print(some_variable) # 161.66666666666666
Getting User Input
Python has a built-in function called input that will prompt the user and give us back the result, which we can store into a variable.
print("Please enter your full name") name = input() name = input("Please enter your full name: ")
Conditional Statements (if/elif/else)
if name == "Mark Zuckerberg": print("Facebook") elif name == "Jack Dorsey": print("Twitter") elif name == "Sundar Pichai": print("Google") else: print("Someone I don't know")
Truthy and Falsy
All conditional checks resolve to either True
or False
. We can call values that resolve to True as “truthy”, and values that resolve to False as “falsy”. Besides False, other things that are naturally falsy include: empty objects, empty strings, None and zero (0).
x = 1 x is 1 # True x is 0 # False
Comparison Operators
Consider we are comparing two variables, x and y. Ex. x > y
Operator | What it does |
== | Truthy if x has the same value as y |
!= | Truthy if x does NOT have the same value as b |
> | Truthy if x is greater than y |
< | Truthy if x is less than y |
>= | Truthy if x is greater than or equal to y |
<= | Truthy if x is less than or equal to y |
Logical Operators
Operator | What it does |
and | Truthy if both x AND y are true |
or | Truthy if either x OR y are true |
not | Truthy if the opposite of x is true |
IS VS. “==”
In Python, == and is are very similar in functionality, but they are not the same. ==
checks for the content, whereas is
checks if both variables point to the same object in memory.
x = [1, 2, 3] # A list of numbers. y = [1, 2, 3] # Don't worry about these for now x == y # True x is y # False z = y y is z # True
Nested Conditionals
# Ask for age age = input("How old are you? ") if age: if int(age) >= 18 and int(age) < 21: # 18-21 wristband print("Entry permitted, but wristband necessary.") elif int(age) >= 21: # 21+ normal entry print("Entry granted") else: # underage print("Entry denied!") else: print("Please enter your age!")
For Loops
- By convention, for loops are used when you have a block of code which you want to repeat a fixed number of times.
- for loops in Python are used for iterating over a sequence
(range of numbers, strings, lists, dictionaries, etc.)
for item in iterable_object: # do something with item -> (code block)
- An iterable object is some kind of collection of items, for instance, a list of numbers, a string of characters, a range, etc.
- item is a new variable that can be called whatever we wantitem references the current position of our iterator within the iterable.
- It will iterate over every item of the collection and then go away when it has visited all items.
[40, 32, 73] "hello" range(1, 10) # Strings for char in "rstforum": print(char) # Range (1-9) for x in range(1, 10): print(x) print("----") # FizzBuzz Examples for num in range(1, 21): if num == 5 or num == 16: print(f"{num}: FizzBuzz") elif num % 2 == 0: print(f"{num}: Fizz is even") else: print(f"{num}: Fizz is odd")
Ranges
Python ranges come in multiple forms:
- range(7) generates integers from 0 to 6
Count starts at 0 and is exclusive - range(1, 8) generates integers from 1 to 7
Two parameters are (start, end) - range(1, 10, 2) generates integers from 1 to 7
Third parameter is called the “step” -> how many to skip over - range(10, 1, -1) generates integers from 10 to 1
The – here means count up, + is count down
While Loops
while
loops continue to execute while a certain condition is truthy, and will end when they become falsy. while loops require a lot more setup than for loops, since you have to specify the termination conditions manually. If the condition doesn’t become false at some point, the loop will continue forever!
secret_password = None while secret_password != "balony1": secret_password = input("Incorrect! Enter password again: ")
Python’s break
statement will immediately terminate a loop. This helps us exit out of a loop whenever we want.
while True: command = input("Type 'exit' to exit: ") if (command == "exit"): break for num in range(1, 21): print(num) if num == 5: break
List
tasks = ["Install Python", "Install VSCode", "Setup Auto PEP8"] # comma-separated values first_task = "Install Python" second_task = "Install VSCode" third_task = "Setup Auto PEP8" tasks = [first_task, second_task, third_task]
List Length
tasks = ["Install Python", "Install VSCode", "Setup Auto PEP8"] len(tasks) # 3
Another built-in function to create list from a range: list()
tasks = list(range(1, 4)) tasks # [1, 2, 3]
Accessing values in a list
print(tasks[0]) # 'Install Python' print(tasks[1]) # 'Install VSCode' print(tasks[2]) # 'Setup Auto PEP8' print(tasks[-1]) # 'Install Python' print(tasks[-3]) # 'Setup Auto PEP8' print(tasks[-4]) # IndexError
Checking values (in
operator)
langs = ["Python", "JavaScript", "Rust", "Elm", "WASM"] "Python" in langs # true "Rust" in langs # true "C++" in langs # false "python" in langs # false
List Methods
# append() - Add an item to the end of a list. random_numbers = [1, 4, 34, 21, 86] random_numbers.append(9) print(random_numbers) # [1, 4, 34, 21, 86, 9] # extend() - Add several items to the end of a list at the same time. my_list = [1, 2, 3] my_list.append(4, 5, 6, 7) # does not work! my_list.append([4, 5, 6, 7]) # [1, 2, 3, [4, 5, 6, 7]] my_list.extent([4, 5, 6, 7]) print(my_list) # [1, 2, 3, 4, 5, 6, 7] # insert() - Insert an item at a given index position my_list = [1, 2, 3, 4] my_list.insert(2, "What a number!") print(my_list) # [1, 2, "What a number!", 3, 4] my_list.insert(-1, "Last number.") # [1, 2, "What a number!", 3, "Last number", 4] # clear() - Remove all items from a list my_list = [1, 2, 3, 4] my_list.clear() # parenthesis are required print(my_list) # [] # pop() - Remove the items at a given position, and return it. If no index is specified, it removes & returns the last item. my_list = [1, 2, 3, 4] my_list.pop() # 4 my_list.pop(1) # 2 # remove() - Removes the first occurrence of the item we provide. Throws a ValueError if the item we provided is not found. my_list = [1, 2, 3, 4, 4, 4] my_list.remove(2) print(my_list) # [1, 3, 4, 4, 4] my_list.remove(4) print(my_list) # [1, 3, 4, 4] # index() - Returns the index of the specified item in the list my_list = [1, 34, 11, 8, 4, 9, 211, 45, 98, 38, 7] my_list.index(11) # 2 my_list.index(45) # 7 # Can specify start and end my_list = [3, 3, 3, 5, 23, 3, 34, 8, 8, 4, 9, 211] my_list.index(3) # 0 my_list.index(3, 1) # 1 my_list.index(3, 3) # 5 my_list.index(8, 6, 9) # 7 # count() - Receives a value we provide and returns the number of times it appears in the list. my_list = [1, 2, 2, 3, 4, 55, 23, 3, 2, 65, 2] my_list.count(2) # 4 my_list.count(45) # 0 my_list.count(3) # 2 # reverse() - Reverse the elements of the list (in-place) my_list = [1, 2, 3, 4] my_list.reverse() print(my_list) # [4, 3, 2, 1] # sort() - Sort the items of the list (in-place) some_list = [3, 4, 7, 2, 9, 8, 0] some_list.sort() print(some_list) # [0, 2, 3, 4, 7, 8, 9] # join() # Technically a String method that takes an iterable argument. # Concatenates a copy of that base string between each item of the iterable and then returns a new string. # Can be used to make sentences out of a list of words by joining on a space. words = ["wax", "on", "wax", "off"] " ".join(words) # 'wax on wax off' fsociety = ["the", "world", "is", "a", "hoax"] "_".join(fsociety) # 'the_world_is_a_hoax'
Slicing
Make new lists using slices of the old list. some_list[start:end:step]
# start: What index to start slicing from my_list = [1, 2, 3, 4] my_list[1:] # [2, 3, 4] my_list[3:] # [4] # start: Starting with a negative number will slice that many number of times from the end my_list = [1, 2, 3, 4] my_list[-1:] # [4] my_list[-3:] # [2, 3, 4] # end: The index to copy up to (exclusive counting) my_list = [1, 2, 3, 4] my_list[:2] # [1, 2] my_list[:4] # [1, 2, 3, 4] my_list[1:3] # [2, 3] # start index is inclusive # end: With negative numbers, how many items to exclude from the end (indexing by counting backwards) my_list = [1, 2, 3, 4] my_list[:-1] # [1, 2, 3] my_list[1:-1] # [2, 3] # step: the number to count at a time (sane as step in ranges) my_list = [1, 2, 3, 4, 5, 6] my_list[1::2] # [2, 4, 6] my_list[::2] # [1, 3, 5] # step: With negative numbers, reverse the order my_list = [1, 2, 3, 4, 5, 6] my_list[1::-1] # [2, 1] my_list[:1:-1] # [6, 5, 4, 3] my_list[2::-1] # [3, 2, 1] # Reversing lists / strings string = "Hello Python!" string[::-1] # '!nohtyP olleH' # Modifying portions of lists numbers = [1, 2, 3, 4, 5] numbers[1:3] = ['a', 'b', 'c'] # [1, 'a', 'b', 'c', 4, 5] numbers[:4][::-1] # chaining
Swapping List Values
frameworks = ["Django", "Flask"] frameworks[0], frameworks[1] = frameworks[1], frameworks[0] print(frameworks)
List Comprehensions
The rough idea is we take an existing list and output another list with different values based upon the first list.
Syntax: [item logic for item (every) in list]
numbers = [1, 2, 3, 4, 5] [num*10 for num in numbers] # [10, 20, 30, 40, 50] [num/2 for num in numbers] # [0.5, 1.0, 1.5, 2.0, 2.5] # List Comprehensions with conditional logic numbers = [1, 2, 3, 4, 5, 6] evens = [num for num in numbers if num % 2 == 0] odds = [num for num in numbers if num % 2 != 0] [num*2 if num % 2 == 0 else num/2 for num in numbers] # [0.5, 4, 1.5, 8, 2.5, 12]
Nested Lists
Lists inside of other lists. Also referred to as multidimensional lists
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] len(nested_list) # 3 nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] nested_list[0][1] # 2 nested_list[1][-1] # 6 # Iterating throught nested loops for list in nested_list: for val in list: print(val)
Nested List Comprehension
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Would need to write two comprehensions [[print(val) for val in list] for list in nested_list] board = [[num for num in range(1, 4)] for val in range(1, 4)] [[1, 2, 3], [1, 2, 3], [1, 2, 3]] [["X" if num % 2 != 0 else "O" for num in range(1, 4)] for val in range(1, 4)] # [['X', 'O', 'X'], ['X', 'O', 'X'], ['X', 'O', 'X']]