CS50 Week 6: Python
Introduction to Python.
Syntax permalink
print("hello, world")
- No semicolons!
- No need to declare variable types
- you don't even have to declare them in advance with a
var
or similar keyword - file extension is
.py
- to execute:
python program.py
- for importing libraries:
from CS50 import get_string
- no
main
function! or
instead of||
- you can use single or double quotes around characters (only single in C)
- in python everything that is character-based is a string; it doesn't matter which quotes you use as long as you're consistent
# this is a comment
elif
(instead ofelse if
)not
instead of!=
- ternary operator:
letter_only = True if input().isalpha() else False
🤯 - no
do while
loops - there's no
i++
ori--
print()
adds a new line by default (so you don't need to add\n
yourself)append()
vspush()
for lists (they're not arrays)None
instead ofNULL
from cs50 import get_string
answer = get_string("What's your name? ")
# no need to deal with separate placeholders
print("hello, " + answer)
# OR
print(f"hello, {answer}"
# you can use formatted string with any string function not just printf 💡
counter++
doesn't exist in Python (counter += 1
)
# no curly braces, no semi-colons, no extra lines
# but yes, indentation!
# pay attention, : instead of {
if x < y:
print("x is less than y")
# instead of else if
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")
Loops permalink
# capitalizing the booleans
while True:
print("hello, world")
i = 0
while i < 3:
print("hello, world")
i += 1
for i in [0, 1, 2]:
print("cough")
# or
for i in range(3):
Data types permalink
- Loosely typed language - variable type is inferred from its value (as opposed to C that is a strongly-typed language)
bool
,float
,int
,str
but alsorange
,list
(an array that automatically re-sizes itself),tuple
,dict
,set
(a collection of values without duplicates)- no
double
orlong
Speller in Python permalink
words = set()
# this is how you define a function in python
def load(dictionary):
file = open(dictionary, "r")
for line in file:
words.add(line.rstrip())
file.close()
return True
def check(word):
if word.lower() in words:
return True
else:
return False
def size():
return len(words)
def unload():
return True
🤔 Why is Python slower than C?
- because Python has to do more work for us with general-purpose solutions, like for memory management
- you are also incurring some overhead by running the Python interpreter, which reads our source code and translates it to code that our CPU can understand, line by line.
More Python Code permalink
Getting user input permalink
answer = input("What's your name? ")
print(f"hello, {answer}")
Check if a string is in a list permalink
# this is pretty neat
if s.lower() in ["y", "yes"]:
No function prototype, but permalink
# you still need to define something before calling it
def main():
meow(3)
def meow(n):
for i in range(n):
print("meow")
main()
Looping over characters of a string permalink
for c in s:
# the second argument overrides the default \n
print(c.upper(), end="")
Working with command-line arguments permalink
from sys import argv
if len(argv) == 2:
print(f"hello, {argv[1]}")
else:
print("hello, world")
Exit errors permalink
# importing the entire library here
import sys
if len(sys.argv) != 2:
print("missing command-line argument")
sys.exit(1)
print(f"hello, {sys.argv[1]}")
sys.exit(0)
Lists permalink
nums = [1, 2, 3, 4]
# insert 5 at position 4
nums.insert(4, 5)
Dictionary permalink
- aka associative array
- under the hood, they are implemented like a hash table
from cs50 import get_string
people = {
"Brian": "+1-617-495-1000",
"David": "+1-949-468-2750"
}
name = get_string("Name: ")
if name in people:
print(f"Number: {people[name]}")
🤔 How do you run python locally?
- always in a virtual environment (to make sure you are using the right version of Python when working on any specific project)
- A Virtual Environment in Python is a self-contained directory that holds a Python installation for a particular language version.
cd
mkdir pyworkshop
cd pyworkshop
python3.7 -m venv env
source env/bin/activate
# and to kill it write deactivate
Some more nifty Python functions
type
for checking out the type of the variabledir
for listing all the methods on the data typehelp
- pep8 for python style guide