Python
What command can you use to capitalize a string?
"string".capitalize()
What is a shebang?
#!/usr/bin/env python3 Tells program loader to identify which interpreter to use
from words import (fetch_words, print_words) vs from words import *
* is not recommended due to namespace clashes and importing unnecessary items.
String methods
.capitalize() == "hello".replace("e", "a") == "hallo" isalpha isdigit "some,csv,values".split(",") == ["some", "csv", "values"]
What files are needed to create a virtual machine?
.vmx - contains all config of VM vmdk - holds all the data
/ vs // math operators
/ = float // = int
If Statements
if number == 5: print("number is 5") else: print("number is NOT 5") if number: print("number is defined and truthy") if number != 5: ..... if number == 3 and number !=3: if number == 3 or number !=3: a=1 b=2 "bigger" if a > b else "smaller"
from urllib.request import urlopen with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() #line.split() for word in line_words: story_words.append(word) print(story_words)
with aliases a method into 'story' str to byte = encode byte to str = decode
While Loops
x = 0 while True: if num == 42: break print("Blah") While statement variables have to be manually incremented
Other Data Types
complex bytes 0 - 255 bytearray tuple - like lists, but cannot be changed set - Gets rid of duplicates and sets them in order
How to comment multiple sections
"""
What are docstrings?
"""
Ways to Execute Python Code
1.) Interpreter - Execute python file using python exe 2.) REPL [Read Evaluate Print Loop] - Call out to Python code within interactive REPL 3.) Natively - Compile and Run (py2exe, pyinstaller)
Nested Functions
Able to define functions within a function so that the nested function can only be exclusively used by that function. The nested function will also be able to reference variables that are defined outside of its nested function.
from math import factorial as fac
Allows you to change how factorial def in math is called. math.factorial(n) # No import vs factorial(n) vs fac(n)
High-level vs interpreted language
High-level = uses English words
if(__name__ == "__main__")
If true, then the module is being executed. Prevents module from running automatically when imported by other modules
Rest-API GET will always return...
JSON files
Scripting Langauge
Language used to interact and communicate with other programming languages [JS, PHP, Perl, Ruby, Python]
Python Module Python Script Python Program
Module - Convenient import w/ API Script - Convenient execution from command line Program - Perhaps composed of many modules
If you have a module that is set to display a text when imported, will the text display a second time when importing the module again?
No, it's already imported and thus, the code won't run again
What is a module?
Similar to a class that can be imported. .py files
What are modules?
Packages
What's pip? pypi?
Pypi [Python Package Index] - repo for python scripts Pip - Package manager that install/uninstall. pip install packagename
Python 2 vs 3
Python 2 - pip / python / ipython Python 3 - pip3 / python3 / ipython3 Not backwards compatible
Interpretive Language
Python technically compiles, but happens in the background. When running, it feels as though there is no compilation time.
REPL
Read Evaluate Print Loop
Possible values for a boolean?
True False None
float + integer doable?
Yes
Functions
def get_students_titlecase(): blah return variable # Functions don't need to end in return, can just print if you don't want the function to pass a variable def add_student(name, student_id=332): # if no value for student_id, assign 332 as default ################## def var_args(name, *args): print(name) print(args) var_args("mark", "Loves stuff", None, "hello", True) # Will print Mark on its own line, and then the rest of the args in a list on its own line #Key word arguments########### def var_args(name, **kwargs): print(name) print(kwargs["description"], kwargs["feedback"]) var_args("Mark", description="Loves Python", feedback=None, pluralsight_subscriber=True) #Returns Mark Loves Python None
For Loops
for name in student_names: print("student name is {0}".format(name)) x = 0 for index in range(10): X += 10 print("The value of X is {0}'.format(x)) # prints 10,20...100 range(5, 10) # Returns 5, 6, 7, 8, 9 range(5, 10, 2) # Returns 5, 7, 9 break continue # Skips directly to next iteration before finishing current iteration
Using variables in Python
name = "Blah" machine = "HAL" "Nice to meet ya {0}. I am {1}".format(name, machine)
How to place variables in text?
name = "Bleh" machine = "Blah" "Nice to meet ya {0}. I am {1}".format(name, machine) f"Nice to meet you {name}. I am {machine}"
Dictionaries
student = { "name": "Mark", "student_id": 1111, "feedback": None } # Dictionaries can be easily converted to JSON student["name"] # Returns Mark student.get("last_name", "Unknown") # Returns Unknown instead of KeyError since last_name was never defined student.keys() # Returns all key names student.values() # Returns all values of keys student["name"] = "James" # Changes name key value del student["name"] # Removes name key value
Lists
student_names = ["Mark", "Katarina", "Jessica"] student_names[0] #returns Mark student_names[-1] #returns last char Jessica student_names.append("Homer") "Mark" in student_name # returns True # Can store different types of variables in lists len(student_list) del student_names[2] # Removes user and shortens list student_names[1:] # Skips first user student_names[1:-1] # Skips first and last user
Exceptions
try: last_name = student["last_name"] except KeyError: print("Error finding last_name") except TypeError: print("I can't add these 2 together") except Exception: print("Unknown error") print("This code executes!") # When accounting for exceptions, program will not crash when it runs into the error
import sys url = sys.argv[1]
url variable is set to first argument