Python Syntax Base

PythonDa ta Types

Math Operators

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

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("P**lease 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

Logical Operators

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 want_item_ 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

t**asks = \["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'\]\]