Skip to content

Instantly share code, notes, and snippets.

@caseyanderson
Last active September 3, 2018 21:09
Show Gist options
  • Save caseyanderson/28f9b38b8c4166cf4d0266daa2a3eab3 to your computer and use it in GitHub Desktop.
Save caseyanderson/28f9b38b8c4166cf4d0266daa2a3eab3 to your computer and use it in GitHub Desktop.
Intro to Python 3

Introduction to Python 3

Materials

  • laptop
  • Python3 development environment with Jupyter (see here for instructions)

Python is a general-purpose, interpreted, high-level programming language. The syntax of the language has been optimized to emphasize code readability, as well as brevity.

Strings

Any character surrounded by quotes. Quotes must be balanced.

For example

a = 'test'
a = "test"

but not

a = 'test

In order to declare a variable as a string, one has to use quotes.

a = test

Python allows for numerous manipulations to strings. Returning to the first example

a = 'test'

One can perform various operations with a to get information regarding the string 'test'.

For example

In [4]: len(a)
Out[4]: 4

Or

In [5]: type(a)
Out[5]: str

str is short for string, by the way.

Return a part of the string (referred to as "string slicing") with the following

In [6]: a[:3]
Out[6]: 'tes'

One can see what other operations are possible with a by typing a.[TAB].

From this list, one can type out any of the functions followed by a ? to see a brief description of what it does.

Convert the string, contained in the variable a, to a capitalized version of itself

In [8]: a.upper()
Out[8]: 'TEST'

To permanently change a

In [10]: a = a.upper()

In [11]: a
Out[11]: 'TEST'

Integers/Floats

There are two basic types of numbers: integers and floating point numbers (floats for short). Integers are any whole number (positive or negative), floats are any number with a decimal point.

For example

In [12]: a = 5

In [13]: type(a)
Out[13]: int

Whereas

In [14]: a = 4.0

In [15]: type(a)
Out[15]: float

a.[TAB] shows what other methods a (the variable that now stores a floating point number [4.0]) has.

Assignment operator, more variables

In Python, = has a unique meaning. The previous example

In [16]: a = 4.0

means “assign 4.0” to the variable named a. The following returns an error

In [17]: 5 = 6
  File "<ipython-input-17-6d9c0c29354b>", line 1
    5 = 6
SyntaxError: can't assign to literal

A 6 can never be assigned (or put inside) to a 5, so the previous line of code will always throw an error.

Variables must be assigned prior to their use, otherwise Python throws an error because it does not understand what you want it to do.

For example

In [18]: x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-401b30e3b8b5> in <module>()
----> 1 x

NameError: name 'x' is not defined

Nonetheless, variables, once assigned (and therefore established as a particular type), can be converted to other data types.

For example

In [21]: a = 5

In [22]: float(a)
Out[22]: 5.0

Or

In [23]: a = 4.9

In [24]: int(a)
Out[24]: 4

Lists

A compound data type used to group together other values. A list is written as a series of comma-separated values (or items) between square brackets. They do not need to be of uniform type.

For example

In [25]: a = ['spam', 'eggs', 100, 1234]

In [26]: a
Out[26]: ['spam', 'eggs', 100, 1234]

Individual items in a list are referenced by their index, or location in the list. We can reference individual items by entering the variable and the position (counting from 0).

For example

In [27]: a[0]
Out[27]: 'spam'
In [28]: a[3]
Out[28]: 1234
In [29]: a[:2]
Out[29]: ['spam', 'eggs']

Individual items/elements in a string can be modified (or updated) as follows

In [30]: a[1] = 2

In [31]: a
Out[31]: ['spam', 2, 100, 1234]

One can make Python determine the length (or size) of list by calling len() on it.

For example

In [32]: len(a)
Out[32]: 4

append and insert are the two most common ways to add an element to a list

Insert Example

In [20]: h = [ 'this', 'is', 'a', 'list' ]

In [21]: h
Out[21]: ['this', 'is', 'a', 'list']

In [22]: h.insert(3, 'great')

In [23]: h
Out[23]: ['this', 'is', 'a', 'great', 'list']

Append Example

In [30]: h.append('certainly')

In [31]: h
Out[31]: ['this', 'is', 'a', 'great', 'list', 'certainly']

insert adds an element to a list at index, append simply adds an element to the end of a list.

extend concatenates two lists and returns a new one.

For Example

In [31]: h
Out[31]: ['this', 'is', 'a', 'great', 'list', 'certainly']

In [32]: i = [ 'the', 'best', 'list']

In [33]: h.extend(i)

In [34]: h
Out[34]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

index allows one to search a list by value

For Example

In [36]: h.index('certainly')
Out[36]: 5

Removing Elements from a list

There are two basic ways to remove an element from a list: pop and remove.

Using pop

In [8]: h = ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [9]: h
Out[9]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [10]: h.pop()
Out[10]: 'list'

In [11]: h
Out[11]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best']

pop removes and returns an item from a list at index. If no index is specified pop removes and returns the last item of a list.

Using remove

In [37]: h
Out[37]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [38]: h.insert(2, 'is')

In [39]: h
Out[39]: ['this', 'is', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

In [40]: h.remove('is')

In [41]: h
Out[41]: ['this', 'is', 'a', 'great', 'list', 'certainly', 'the', 'best', 'list']

remove gets rid of the first occurrence of value. In the above example, the value 'is' was removed at index 1. In order to remove the second occurrence of 'is' one would have to run h.remove('is') again.

if statements

x = int(input('please enter an integer: ') )

if x < 0:
    x = 0
    print( 'negative changed to zero')
elif x == 0:
    print( 'Zero')
elif x == 1:
    print('single')
else:
    print('more')

Quite a bit to talk about here. Let's break it down line by line:

  1. We called a statement that takes any input at the command line, converts it to an int, and assigns it to the variable x.
  2. After that, we start our test. If x is less than 0, set x to 0 and print the statement 'negative changed to zero'.
  3. Elif (means else if) x RETURNS 0, print zero. Else if x returns 1, print single. If none of those things are the case (the final else), print the string more.

Before you try to type this in, notice the whitespace. Python groups statements together (in functions like this one, or otherwise) via whitespace. The normal Python protocol is to use four spaces to denote the first line belonging to a previous one (the line under the first if statement).

Try to enter this into your interpreter with a different input value (not 42).

for statements

words = ['cat', 'widow', 'defenestrate']

for w in words:
    print(w, len(w))

Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. The above function declares a list called words with three items: cat, widow, and defenestrate (all strings). Then, it says for w (used as an index here) in the list words print w (the item at that position and the length of that particular item). This is why we get the sequence of words with their string length returned. Upon completion of the for loop (when the loop has iterated over each item in the list) the loop terminates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment