Python Basics
To install Python, download it from Python Software Foundation and install on your system.
Running Python scripts
To start interactive Python, type python
in a command shell. To exit interactive Python, type quit()
or exit()
. Running Python with the -c
option allows you to execute Python code directly from the command line.
python -c "print('Hello, world!')"
To run a Python script, first save Python code as FirstExample.py
and then run it in a command shell.
python FirstExample.py
If you want to run the script and enter interactive mode, pass the argument -i
before the name of the script.
python -i FirstExample.py
Numbers
Integer numbers have type int
, floating-point numbers have type float
. An equal sign is used to assign a value to a variable. Variables in Python are loosely typed and do not have a special keyword to initialize them. There are no constants in Python. There are no semicolons at the end of the expression, so whitespace could cause an error in Python.
quotient = 17 / 3 # classic division return a float
floored_quotient = 17 // 3 # integer division discards the fractional part
remainder = 17 % 3
dividend = floored_quotient * 3 + remainder
five_squred = 5**2
Strings
Strings are enclosed in either single quotes '...'
or double quotes "..."
. Raw strings are prefixed by r
in string literal. Python strings are immutable.
two_lines = 'First line.\nSecond line.'
raw_string = r'C:\some\name'
Multi-line strings are enclosed in either single triple-quotes '''...'''
or double triple-quotes """..."""
. Use print()
function to display a string to the console.
multi_line = """\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
print(multi_line)
Strings are concatenated with +
operator and repeated with *
operator. String literals next to each other are automatically concatenated.
unununium = 3 * 'un' + 'ium'
text = ('Put several strings within parentheses '
'to have them joined together.')
Strings can be indexed with the first character having index 0. The build-in function len()
returns the length of a string.
word = 'Python'
word[0] # => 'P'
word[-2] # => 'o'
word[:2] # => 'Py'
word[:-2] # => 'Pyth'
word[:2] + word[2:] # => 'Python'
len(word) # => 6
Lists
The list data type groups together comma-separated values between square brackets. Lists might contain items of different types, but usually the items all have the same type.
numbers = [1,2,3,4,5]
numbers[0] # => 1
numbers[-1] # => 5
numbers + [6,7] # => [1, 2, 3, 4, 5, 6, 7]
numbers[4] = 8; # lists are mutable
numbers # => [1, 2, 3, 4, 8]
Lists are reference types. The append()
method adds new items at the end of the list.
numbers_same = numbers
numbers_same.append(9)
numbers # => [1, 2, 3, 4, 8, 9]
numbers_copy = numbers[:]
numbers_copy.append(10)
numbers # => [1, 2, 3, 4, 8, 9]
Assignment to slices is possible, which can change the size of the list. The len()
function returns the size of the list.
letters = ['a', 'b', 'c', 'd', 'e', 'f']
letters[2:5] = ['C', 'D', 'E']
letters # => ['a', 'b', 'C', 'D', 'E', 'f']
letters[2:5] = []
letters # => ['a', 'b', 'f']
len(letters) # => 3
A while
loop in Python is used to repeatedly execute a block of code as long as a specified condition is True
.
a, b = 0, 1
while a < 1000:
print(a, end=',')
a, b = b, a+b
The if/else
statement is used to make a decision based on condition.
x = 1
if x < 0:
print('Negative')
elif x == 0:
print('Zero')
else:
print('Positive')