Python - Intro
To launch the Python interpreter you can type the following:
python
Depending on how Python was installed on your system, the name may include the version number and you would launch it like this:
python3.11
Some systems still include Python 2 for legacy purposes. Often times the binary for the interpreter will include the version in the name to avoid a conflict between Python 2 and 3.
Here is an example showing a typical path for the interpreter:
/usr/local/bin/python3.11
Interactive Mode
You can launch the Python interpreter in interactive mode like this:
python
You can exit from interactive mode with the following:
Ctrl-D Linux/Unix
Ctrl-Z Windows
exit()
quit()
Interactive mode is great for testing with out having to create a script. It allows you to just run commands and expressions interactively.
Scripts
Python code can be placed into text files with the “.py” extension to create scripts.
This is hello world in Python. The most basic script that you could create that actually does something.
hello.pyprint("Hello World")
You can run the script using the interpreter like this:
python hello.py
This is a slightly more elaborate example showing how variables can be used:
x = "test"
print("The value is:", x)
You can use arguments to a script like this. We will have more on this in a later section.
import sys
print(sys.argv[0]) # script name
print(sys.argv[1]) # first arg
print(sys.argv[2]) # second arg
- Scripts use UTF-8 by default
Python Comments
Anything after a # is a comment ( unless it is quoted as a string ). You can put comments at the end of a line or on a new line.
Here is an example:
# this is a comment
data1 = 1 # this is also a comment
# this line another comment
data2 = "# This is a string, not a comment.."
Multiline comments
To create a multi line comment in Python you really just need to create a multi line string. You can do this by using triple quotes ( either double or single ). See these examples.
"""
This can be used as a multi line comment.
This is another line.
"""
Another example:
'''
This is also a multi line comment.
This is another line.
More documentation here.
'''
Variables
Multiple assignment:
a, b = 0, 1
a, b, c = 245, 54, 3
Directly Run Commands and Modules
You can directly pass a command to the interpreter on a single line like this:
python -c 'print("test")'
You can execute a module like this:
python -m module [arg]
Numbers / Arithmetic
Here are some basic arithmetic examples:
2 + 2
5 - 3
2 * 5
9 / 4
25 - 3*5
(25 - 3*5) / 2
- Division always returns a floating point number
10 / 3 # divide, return float
10 // 3 # floor division discard remainder
10 % 3 # modulus, remainder after division
You can do exponents like this:
5 ** 2
4 ** 9
You can use variables like this:
x = 25
y = 5 * 12
z = x * y
print(z)
You can mix integers with floating points:
5 * 3.24 - 4
_ variable contains the results of the last printed expression ( interactive mode )
x = 123.5 / 10
y = 225.5
y * x
y + _
5 * _
_ - 2
print(_)
Text / Strings
Strings can use double quotes and single quotes.
"The text that you crave." # double quotes
'More text here.' # single quotes
'2023' # quoted numbers as a string
Escaping quotes - If you want to actually use quotes within a string you have a few options:
- You can escape them using a backslash as shown below.
- If you place single quotes inside double quotes or double quotes inside single quotes, you won’t have to escape them.
'I am \'working\' right now.' # use escape
'I am "working" right now.' # no escape needed
"I am \"working\" right now." # use escape
"I am 'working' right now." # no escape needed
'"I\'m," working right now.' # combined
\n - can be used to place a newline inside a string. These display differently if you just type the variable in interactive mode versus using print().
This will print a single line in interactive mode. The \n will not show up as a newline character but be printed literally.
s = 'Line of text.\nAnother line of text.'
s
This will print two lines in either a script or interactive mode.
s = 'Line of text.\nAnother line of text.'
print(s)
You can create a raw string by preceeding it with the letter ‘r’. Raw string won’t use escape characters. Sometimes you don’t want escape characters.
print('C:\Windows\System32')
print(r'C:\Windows\System32')
Multi line string literal:
- Triple-quotes ( single or double )
- Avoid including end of lines with “". This is useful for the first line because it makes it easier to align text.
a = """\
This is a part of the string.
More of the string here.
Don't need to indent but we can.
"""
b = '''\
This another string.
More lines of text.
Even more of the string here.
'''
print(a, b)
Concatenate strings like this:
'abc' + 'def' + 'xyz'
Multiply or print the same string more than once:
5 * "test"
Multiply and concatenate strings:
3 * 'ab' + 'cde'
Also concatenate with a space for string literals:
'abc' 'xyz'
Another example:
x = ('The first string. '
'Another string.')
- Concatenating with a space doesn’t work with variables.
Concatenate with variables:
x + 'xyz'
Indexing / Subscripting Strings
You can access characters in a string like this.
x = 'Sandy Beach'
x[0] # char in position 0
x[3] # char in position 3
NOTE - You can’t assign a value to a string index because strings are immutable. You would need to create a new string.
Negative values will start counting from the right:
x[-1] # last character
x[-2] # second to last character
x[-5]
Slicing strings:
The first character is included and the last character is excluded. This makes it easier to combine slices. For example 2:5 means characters at position 2, 3, and 4.
- start index always included
- end index always excluded
x = 'Sandy Beach'
x[0:2] # 0 to 2
x[3:8] # 3 to 8
x[:3] # begining to 3
x[3:] # 3 to end
x[-4:] # -4 to end
Example concatenating for original string:
x[:2] + x[2:]
x[:4] + x[4:]
Length of string:
x = 'Sandy Beach'
len(x)
Lists
A list is basically an array.
We are going to cover the absolute basics of lists here. We have an entire section on lists later on. See that for more detail. Feel free to skip ahead and check that section first.
a = ["pizza", "noodle", "burger"] # define list
a[2] = "taco" # assign list element
print(a) # print entire list
print(a[2]) # print one element
Syntax and Indentation
Spacing and indentation is important in Python. Code blocks ( loops, conditionals, functions, etc. ) use indentation to define what code belongs to the block. Indentation needs to be consistent within a block. Either spaces or tabs can be used but it is important to choose one and be consistent. I would recommend spaces. I would also recommend indenting four spaces per block.
Note the indentation for this loop. It forms a block.
for i in range(5):
j = i * 2
print(i)
Blocks can be nested. Notice how we use two levels of indentation here to achieve that.
for i in range(3):
for j in range(2):
print(i, j)