Skip to content

Latest commit

 

History

History
394 lines (285 loc) · 6.98 KB

File metadata and controls

394 lines (285 loc) · 6.98 KB

Data types and variables

  • Strings
name = "Test"
  • Lists
groceries =["Milk", "Eggs", "Ice cream"]
  • Dictionaries
person ={
        'key': 'value',
        'name': 'Kalob',
        'language': 'Python'
}

person['name']
  • tuples -> Lists that cannot be changed
kids = ('Nathan', 'Daniel')
  • sets

A unique list. In example below if we print foods it will show only {'Ice Cream', 'Pizza', 'Tacos'}

 foods = {'Pizza', 'Tacos', 'Ice Cream', 'Pizza', 'Pizza', 'Tacos'}

Elements can be added with add() method.

Multuple elements are added with update(x, x, x, ...) method.

Removing elements from a set is done with remove() or discard() method. discard() doesn't trhour a KeyError exception if the element is not in the set.

  • boolean
is _adult = True
  • assign the same value to multiple variables a = b = 100
  • assign multiple values to multiple variables a, b = 100, 200

Indexing

  • Strings -> Individual items can be accessed with name[x] or name[start:end]. start or end can be skipped, but the : must be kept.
  • Lists -> Individual items can be accessed with name[x] or name[start:end]. start or end can be skipped, but the : must be kept.

Comments

  • Simple comments in code must be marked by #
# This is a simple comment
  • Docstrings
def things():
        """
        Hello
        """

String Formatting

  • Format strings with .format starting with Python 3.5 and up
name = "Python"
course = "{} for Everybody".format(name)
  • F Strings starting with Python 3.6 and up
name = "Python"
print(f"The crash course language is {name}")
  • Older way of string formatting
print("Hello %s" % "World")

name = "Python"
print("Hello %s" % name)

Files

  • Create new file
with open("try_me.py", "w") as file_handler:
        file_handler.write("print('Hello World lolololololo')")
        file_handler.close()
  • Open an existing file
with open(try_me.py","r") as file_handler:
        content = file_handler.read()
        file_handler.close()

print(content)
  • Append to an existing file
with open(try_me.py","a") as file_handler:
        file_handler.write("\nTesting line #2")
        file_handler.close()

Operators

  • Overview of basic operators can be found here

  • Conditional branches

lang = "Python 3"

if lang == "Ruby":
        print("You are using Ruby")
elif lang == "Python 2":
        print("Zomg please upgrade k thx baiii")
else:
        print(f"Anything else the value was {lang}")
  • Comparison operators

    • == equals
    • >= greater then or equal
    • <= less then or equal
    • > greater
    • < less
    • != is not equal
  • Assignment operators

    • = - c = a + b assigns value of a + b into c
    • += - c += a is equivalent to c = c + a
    • -= - c -= a is equivalent to c = c - a
    • *= - c *= a is equivalent to c = c * a
    • /= - c /= a is equivalent to c = c / a
    • %= - Modulus of two operands and assign the result to left operand
    • **= - Exponential (power) on two operands and assign value to the left
    • //= - Floor division on operators and assign value to the left operand
  • Bitwise operators

    • & - Binary AND
    • | - Binary OR
    • ^ - Binary XOR
    • ~ - Binary Ones Complement
    • << - Binary Left Shift
    • >> - Binary Right shift
  • Logical operators

    • and
    • or
    • not
  • Membership operators

    • in
    • not in
  • Identity operators

    • is
    • is not
  total = None
  type(total)
  if total is None:
        print("Is None")

For loops

  • general synthax
for x in range(0, 3):
        print('%d * %d = %d' % (x, x, x*x))
  • in operator goes to iterables like: set, tuple, string, list
groceries = ["Milk", "Eggs", "Ice cream"]

for item in groceries:
        print(f"The item is {item}")
  • break
  • continue
name = "Python 3 Crash Course"
for letter in name:
        l = letter.lower()
        if l in 'aeiouy':
                print(f"Vowel is: {l}")
                continue
        if l == "3":
                print("Breaking on 3")
                break
  • Access the index with the element
for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

While loops

num = 0
while num < 10:
        print(num)
        num = num + 1

List Comprehensions

Examples of ist multiplication

nums = [1, 2, 3, 4, 5, 7, 8, 9, 10]
times_ten = [num*10 for num in nums]
times_ten2 = [num*10 for num in nums if num % 2 == 0]

Functions

  • function without parameters
def name():
        return "A thing"

name()
  • function with parameter
def greeting(name):
        print(f"{name}, Hello to you good sir!")
  • function with parameters with default value
def greeting(name, greeting="Hello):
        return(f"{name}, {greeting} to you good sir!")
  • function that returns another function
import math
def make_cylinder_volume_func(r):
    def volume(h):
        return math.pi * r * r * h
    return volume
  • Function annotations(starting with Python 3.5) which are dictionaries. Detailed explanation can be found here
def main () -> None:
def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': 
    return 1/2*m*v**2
 
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

Classes

  • simple class definition
class Person:
        pass

adi = Person()

adi

type(adi)
  • every method in the class receives as parameter self
class Person:
        name = "Adi"
        def speak(self):
  • class with constructor
class Person:
        def __init__(self, name, age, food)
        self.name = name
        self.age = age
        self.food = food
        def speak(self):
                print(f"Feed me more {self.food}")
        def get_name(self):
                print("The name of this person is", self.name)
        def __str__(Self):
                return self.name

adi = Person('Adi', 30, 'Pizza')
adi.speak()
adi.get_name()
print(adi) -> results in Adi

Packages

  • version of pip
pip -V
  • Install new package
pip install <package_name>
  • Uninstall a package
pip uninstall <package_name>
  • Show details of a package
pip show <package_name>
  • List all packages installed in the system
pip freeze
  • A much better interactive editor then the standard shell is ipython which cab be installed with
sudo pip install ipython

Try and Except

try:
        1/0
except Exception as e: # except ZeroDivisionError:
        print(e)
        print(type(e))

print("It still runs!")