
When you’re working with Python, you’ll often see examples that start with >>>
or ...
. These are just prompts from the Python interpreter. If you’re trying out the examples yourself, just type in what comes after the >>>
. The stuff without prompts is Python’s output.
Fun tip: In many editors or tutorials online, you can click on the prompt symbols (like >>>
) to hide them, making it easier to copy and paste code.
Also, you’ll notice comments in many examples. In Python, comments start with a #
. They’re just there to explain things to humans—Python ignores them. You can add them at the start of a line or after some code, just not inside a string.
Here’s what that looks like:
pythonCopyEdit# This is a comment
spam = 1 # Another comment next to code
text = "# This isn't a comment because it's in quotes"
Using Python Like a Calculator
Let’s try doing some math!
pythonCopyEdit2 + 2
# Output: 4
50 - 5*6
# Output: 20
(50 - 5*6) / 4
# Output: 5.0
8 / 5 # Always returns a float
# Output: 1.6
Python can handle integers (int
) and floating point numbers (float
). To do floor division (where the result is just the whole number), use //
. For the remainder, use %
.
pythonCopyEdit17 / 3
# Output: 5.666...
17 // 3
# Output: 5
17 % 3
# Output: 2
Want to do powers? Use **
.
pythonCopyEdit5 ** 2 # 5 squared
# Output: 25
2 ** 7
# Output: 128
Assign values to variables with =
:
pythonCopyEditwidth = 20
height = 5 * 9
width * height
# Output: 900
Trying to use a variable before defining it gives an error:
pythonCopyEditn
# NameError: name 'n' is not defined
Python also supports floating point math:
pythonCopyEdit4 * 3.75 - 1
# Output: 14.0
In the interactive shell, the last result is stored in _
:
pythonCopyEdittax = 12.5 / 100
price = 100.50
price * tax
# Output: 12.5625
price + _
# Output: 113.0625
round(_, 2)
# Output: 113.06
Other number types include Decimal
, Fraction
, and even complex numbers using j
(like 3+5j
).
Working with Text (Strings)
Python can also work with text—these are called “strings” and are created using quotes:
pythonCopyEdit'spam eggs' # Single quotes
"Hello world!" # Double quotes
'1975' # Numbers inside quotes = strings
To include quotes in strings, you can escape them with \
or use the other type of quote:
pythonCopyEdit'doesn\'t'
"doesn't"
'"Yes," they said.'
"\"Yes,\" they said."
Multiline text? Use triple quotes:
pythonCopyEditprint("""\
Usage: thingy [OPTIONS]
-h Show this message
-H host Set host
""")
If your string has special characters like \n
(new line), they’ll behave differently in print()
:
pythonCopyEdits = 'First line.\nSecond line.'
print(s)
# Output:
# First line.
# Second line.
Use r
for raw strings (they keep the backslashes):
pythonCopyEditprint(r'C:\some\name')
# Output: C:\some\name
Playing Around with Strings
Strings can be combined using +
, and repeated with *
:
pythonCopyEdit3 * 'un' + 'ium'
# Output: 'unununium'
Just placing two strings next to each other also works (as long as they’re both string literals):
pythonCopyEdit'Py' 'thon'
# Output: 'Python'
But that doesn’t work with variables:
pythonCopyEditprefix = 'Py'
prefix + 'thon'
# Output: 'Python'
Strings are sequences, so you can grab parts of them:
pythonCopyEditword = 'Python'
word[0] # First letter
# Output: 'P'
word[-1] # Last letter
# Output: 'n'
word[0:2] # Characters 0 to 1
# Output: 'Py'
word[:4] # First 4 characters
# Output: 'Pyth'
Strings are immutable—once created, you can’t change them. You’ll have to create a new one:
pythonCopyEdit'J' + word[1:]
# Output: 'Jython'
Want to know how long a string is?
pythonCopyEditlen('supercalifragilisticexpialidocious')
# Output: 34
Lists: Python’s Favorite Collection
Lists are like boxes that hold other things—numbers, strings, even other lists!
pythonCopyEditsquares = [1, 4, 9, 16, 25]
squares[0]
# Output: 1
squares[-3:]
# Output: [9, 16, 25]
You can glue lists together too:
pythonCopyEditsquares + [36, 49]
# Output: [1, 4, 9, 16, 25, 36, 49]
Lists can be changed (they’re mutable!):
pythonCopyEditcubes = [1, 8, 27, 65, 125]
cubes[3] = 64 # Fix the mistake
cubes.append(216) # Add 6 cubed
Be careful: assigning a list to another variable just creates a reference—not a new copy.
pythonCopyEditrgb = ["Red", "Green", "Blue"]
rgba = rgb
rgba.append("Alpha")
print(rgb)
# Output: ['Red', 'Green', 'Blue', 'Alpha']
To make a real copy, use slicing:
pythonCopyEditcopy = rgba[:]
copy[-1] = "Transparent"
Lists can be updated or cleared entirely:
pythonCopyEditletters = ['a', 'b', 'c', 'd']
letters[2:4] = ['X', 'Y'] # Replace
letters[2:4] = [] # Remove
letters[:] = [] # Clear all
Yes, len()
works for lists too:
pythonCopyEditlen(['a', 'b', 'c'])
# Output: 3
And lists can even hold other lists:
pythonCopyEditnested = [['a', 'b'], [1, 2, 3]]
nested[0][1]
# Output: 'b'
Writing Your First Simple Program
Let’s build a mini Fibonacci sequence generator:
pythonCopyEdita, b = 0, 1
while a < 10:
print(a)
a, b = b, a + b
Here’s what’s going on:
- We assign
a
andb
to0
and1
. - The
while
loop runs as long asa
is less than10
. - Inside the loop, we print
a
, then update both variables.
Notice the indentation? That’s how Python knows which lines belong inside the loop.
Comparison operators work just like in other languages: <
, >
, ==
, !=
, etc.