Introduction to Python

An introduction to Python for middle and high school students using Python 3 syntax.

Getting started

We're assuming that you already have Python 3.6 or higher installed. If not, go to Python.org to download the latest for your operating system. Verify that you have the correct version by opening a terminal or command prompt and running

$ python --version
Python 3.6.0

Your First Program: Hello, World!

Open the Interactive DeveLopment Environment (IDLE) and write the famous Hello World program. Open IDLE and you'll be in an interactive shell.


In [ ]:
print('Hello, World!')

Choose File > New Window. An empty window will appear with Untitled in the menu bar. Enter the following code into the new shell window. Choose File > Save. Save as hello.py, which is known as a python module. Choose Run > Run module to run the file

Calculating with Python

Mathematical operators:

  • Addition: +
  • Subtraction: -
  • Multiplication: *

Try these

  • 3 * 4

In [ ]:
3*4

Division:

* Floating point `/`
* Integer `//`

Try these:

  • 5/4
  • 1/0
  • 3//4
  • 5//4

In [15]:
3//4


Out[15]:
0

In [16]:
# Exponents
2**3


Out[16]:
8

In [17]:
# Modulus
5%4


Out[17]:
1

Type function

Theres lots more available via the standard library and third party packages. To see the type of the result, use the type function. For example type(3//4)) returns int

Order of Operations

Python reads left to right. Higher precedence operators are applied before lower precedence operators. Operators below are listed lowest precedence at the top.

Operator Description
or Boolean OR
and Boolean AND
not Boolean NOT
in, not in, is, is not, <, <=, >, >=, !=, == Comparison, including membership tests and identity tests
+, - Addition and Subtraction
*, /, //, % Multiplication, division, integer division, remainder
** Exponentiation

Calculate the result of 5 + 1 * 4.

We override the precendence using parenthesis which are evaluated from the innermost out.

Calculate the result of (5+1) * 4.

Remember that multiplication and division always go before addition and subtraction, unless parentheses are used to control the order of operations.


In [19]:
(2 + 2) ** 3


Out[19]:
64

Variables

Variables are like labels so that we can refer to things by a recognizable name.


In [25]:
fred = 10 + 5

type(fred)


Out[25]:
int

In [26]:
fred = 10 / 5
type(fred)


Out[26]:
float

In [28]:
fred * 55 + fred


Out[28]:
112.0

In [29]:
joe = fred * 55
joe


Out[29]:
110.0

In [33]:
joe


Out[33]:
2.0

In [34]:
fred


Out[34]:
2.0

In [32]:
joe = fred
fred = joe

Valid varible names

Variables begin with a letter followed by container letters, numbers and underscores

  • jim
  • other_jim
  • other_jim99

Invalid variable names: don't meet requiremenets

  • symbol$notallowed
  • 5startswithnumber

Invalid variable names: reserved words

Reserved words
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
break except in raise

Referring to a previous result

You can use the _ variable to refer to the result of a previous calculation when working in the shell.


In [39]:
ends_with_9 = 9

a = 6
b = 4

In [35]:
my_var = 7

In [ ]:


In [ ]:
num_apples * 65

In [40]:
doesntexist


-----------------------------------------------------------------------
NameError                             Traceback (most recent call last)
<ipython-input-40-b69cc5c52304> in <module>()
----> 1 doesntexist

NameError: name 'doesntexist' is not defined

User Input

We can get keyboard input using the input function


In [ ]:
name = input("What's your name? ")
print("Hi ", name)

Strings

  • Strings are immutable objects in python, meaning they can't be modified once created, but they can be used to create new strings.
  • Strings should be surrounded with a single quote ' or double quote ". The general rule is to use the single quote unless you plan to use something called interpolation

Formatting

Strings support templating and formatting.


In [47]:
id("bar")


Out[47]:
4527334824

In [48]:
fred = "bar"
id(fred)


Out[48]:
4527334824

In [ ]:
"this string is %s" % ('formatted')

In [ ]:
"this string is also {message}. The message='{message}' can be used more than once".format(message='formatted')

In [ ]:
# Called string concatenation
"this string is "+ 'concatenated'

In [ ]:
## Conditionals

`if (condition):`

`elif (condition):`
    
`else (optional condition):`

In [ ]:
aa = False

if aa:
    print('a is true')
else:
    print ('aa is not true')

In [ ]:
aa = 'wasdf'

if aa == 'aa':
    print('first condition')
elif aa == 'bb':
    print('second condition')
else:
    print('default condition')

Data Structures

  • Lists []

Lists are orderings of things where each thing corresponds to an index starting at 0.

Example [1, 2, 3] where 1 is at index 0, 2 is at index 1 and 3 is at index 2.

  • Tuples ()

Tuples are like lists, only you can't

  • Dictionaries {}

key value pairs

Comprehension

Lists can be constructed using comprehension logic


In [ ]:
[(a, a*2) for a in range(10)]

We can use conditionals as well


In [ ]:
[(a, a*2) for a in range(10) if a < 8]

Additional topics

  • python modules and packages
  • functions
  • classes and methods
  • generators
  • pip and the python packaging land
  • virtualenvs

In [ ]: