Python basics
A video
If you’d rather spend a half-hour listening and watching than reading, here’s a video version of (approximately) the content below.
You’ll definitely want to fullscreen it.
How to write and run Python scripts
- Open up your text editor and create a new file:
File > Save
with the nameintro.py
- In the shell,
cd
into the folder where you saved intro.py. - Type
mkvirtualenv introductions
into your shell to create a Python 3 virtual environment calledintroductions
. - You’re automatically inside of the new virtual environment, but type
workon introductions
to practice selecting one anyway. - Now let’s edit
intro.py
in Atom so that our script actually does things!
Note: There is seriously no reason to use a virtual environment here, but when you’re like 65 you’ll find out that they’re actually useful.
In order to run your new Python script
- Open up Terminal
- Use
cd
to move to wherever you save yourintro.py
- Use the
python
command to run the script by typingpython intro.py
Printing
Note: Any lines that start with a
#
are called comments, and they’re just notes for you to read - Python ignores them! Commenting your code is a great way to ensure you remember what different parts do later on.
print("Hello world")
print('Hello world')
# Double-quotes and single-quotes work the same in python
# But don't mix them!
# These print statements won't print a space between "Hello" and "World"
print("Hello" + "world")
print("Hello", "world")
# These will:
print("Hello" + " world")
print("Hello", " world")
Arithmetic & Casting
# This will make your computer mad because it can't add a string to an integer.
print('10' + 10)
# Strings and integers are different data types!
# Cast your string into an int(eger)
print(int('10') + 10)
# Output is 20.
# Or cast your int into a string:
print ('10' + str(10))
# Output is 1010
print('Hello' + str(10))
# This gives you "Hello10" back.
Variables & Taking Input
# Store things in variables!
name = "Dennis"
print("Hello, " + name)
# Don't use spaces in variable names
last_name = Soma # This is okay
last name = Soma # This will not work
lastName = Soma # Works!
# Store user input in a variable!
name = input("What's your name?")
print("Hello, " + name)
If-Statements
year_of_birth = input("What year were you born in? ")
age = 2016 - int(year_of_birth)
print("You are roughly " + str(age) + " years old")
# Sample if-statement
if age == 33 or age > 100:
print("So cool!!!! You get a free beer unit!!!!")
elif age >= 21:
print("Here's your beer unit")
else:
print("Nope, sorry")
print("Goodbye")
# Note that we don't use '=' in comparisons, we use '=='
# Indentation is meaningful! If something is not indented underneath the if/elif/else, it isn't associated with that particular condition.
# Only the first condition that is TRUE will be run -- it doesn't matter if another condition is also true further down the if-statement.
Now, type python intro.py
into your shell to run your very first Python script! If there are errors in your Python script, don’t worry! Your shell will definitely let you know.
deactivate
to shut down your virtual environment when you are done.
Common Errors
TIP: Pay attention to the errors you get when you run your Python script! Terminal will probably tell you exactly where you went wrong (the line number or character nearest to the error).
- Make sure you have spelled and capitalized everything correctly!
- Make sure you’re in the correct folder;
pwd
all the time/pay attention to the folder Terminal says you’re in. - Make sure you saved your Python script where you think you did.
- Make sure you’re running Python 3! Run
python --version
to check- If you’re not running Python 3, you probably forgot to start up your virtual environment
mkvirtualenv [name]
- You can name your virtual environment anything you want.
- When you’re done, close out of your virtual environment using
deactivate
- If you’re not running Python 3, you probably forgot to start up your virtual environment
- When writing code, make sure you don’t call a variable before you tell your code what the variable is! For example:
# This will work:
name = "Soma"
print(name)
# This will not work:
print(name)
name = "Soma"
- In if-statements, make sure you’re ending ALL conditions with
:
if n < 5:
do something
else:
do something different
- In if-statements, make sure you are indenting correctly! If your “do something”’s aren’t indented underneath your condition, the logic of your code may not be what you think it is!
# These two if-statements will print different things!
# If statement #1
if n < 5:
print("n is less than 5.")
else:
print("n is greater than 5.")
print("Pick a smaller number.")
# If statement #2
if n < 5:
print("n is less than 5.")
else:
print("n is greater than 5.")
print("Pick a smaller number.")
You can also chain together multiple if
statements with elif
!
if n < 5:
print("n is less than 5")
elif n < 10:
print("n is between 5-9")
elif n < 100:
print("n is between 10-99")
else:
print("n is 100 or greater")