Python
What you should know about it!

What is Python?

  • Interpreted: Do not need to compile your program before executing
  • Interactive: Can sit at a prompt and interact with the interpreter directly
  • Object-Oriented: Style of programming that encapsulates code within objects

About Python

  • Developed by Guido van Rossum in 1989
  • It is FREE!!
  • Designed to be fun to use and easy to learn
  • Named after Monty Python's Flying Circus
monty_python

Installing Python

Installing Python

The best way (in my opinion) to install Python is through Anaconda

https://www.anaconda.com/download/#macos

anaconda_logo

Installing Python

  1. Go to https://www.anaconda.com/download/#macos
  2. Download the corresponding installation file for Python 3.6
  3. Read the documentation in "How to Install ANACONDA" and follow instructions
  4. For command-line, use:
    
                                bash /path/to/file/Anaconda3-5.2.0-Linux-x86_64.sh
                                
  5. And now follow the instructions.

Installing Python

Once you've installed Python correctly, you shold be able to

  • Open up the Terminal app
  • Type ipython
  • And begin with an interactive Python session

                        victor2@Victors-MBP-3:~ ipython
                        Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 12:04:33)
                        Type 'copyright', 'credits' or 'license' for more information
                        IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

                        In [1]:
                        

Installing Python

For more information on how to install Python
see:

https://vanderbilt-astro-starting-grad-school.readthedocs.io/en/latest/python_intro.html#installing-anaconda

Interactive Session

  • To begin an interactive Python session, type python or ipythonon the command line:

                        victor2@Victors-MBP-3:~ ipython
                        Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 12:04:33)
                        Type 'copyright', 'credits' or 'license' for more information
                        IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

                        In [1]:
                        

Interactive Session

  • To exit an interactive Python session, type: Ctrl-d, exit() or quit()

                        victor2@Victors-MBP-3:~ ipython
                        Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 12:04:33)
                        Type 'copyright', 'credits' or 'license' for more information
                        IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

                        In [1]: exit
                        victor2@Victors-MBP-3:~
                        

Assignment

  • You can assing values to variables with
  • 
                                <var> = <expression>
                                
  • For example:
  • 
                                victor2@Victors-MBP-3:~ ipython
                                nuPython 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 12:04:33)
                                Type 'copyright', 'credits' or 'license' for more information
                                IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
    
                                In [1]: number = 5
    
                                In [2]: number
                                Out[2]: 5
                                

Assignment

  • Variables can be reassigned. Python will retain the most recent assignment.
  • For example: swap values of x and y
  • 
                                In [1]: x = 5
                                In [2]: x
                                Out[2]: 5
    
                                In [3]: y = 12
                                In [4]: y
                                Out[4]: 12
    
                                In [5]: x = y
                                In [6]: y = x
    
                                In [7]: x, y
                                Out[7]: (12, 12)
                                

Assignment

  • Variables can be reassigned. Python will retain the most recent assignment.
  • For example: swap values of x and y
  • 
                                In [1]: x = 5
                                In [2]: x
                                Out[2]: 5
    
                                In [3]: y = 12
                                In [4]: y
                                Out[4]: 12
    
                                In [5]: temp = x
                                In [6]: x = y
                                In [7]: y = temp
    
                                In [8]: x, y
                                Out[7]: (12, 5)
                                

Multiple assignment

  • You can assing values to multiple variables with
  • 
                                <var1>, <var2>, ... = <expr1>, <expr2>, ...
                                
  • For example:
  • 
                                In [1]: x, y = 5, 12
    
                                In [2]: x
                                Out[2]: 5
    
                                In [3]: y
                                Out[3]: 12
                                

Multiple Assignment

  • Variables can be reassigned. Python will retain the most recent assignment.
  • For example: swap values of x and y
  • 
                                In [1]: x, y = 5, 12
    
                                In [2]: x, y = y, x
    
                                In [3]: x,y
                                Out[3]: (12, 5)
                                

Input & Output

  • Ask for input from command-line with input:
  • 
                                In [1]: name = input("What is your name?")
                                What is your name?"Victor"
    
                                In [2]: print("Hello", name)
                                Hello "Victor"
                                
  • The user gets asked for the input and then gets assigned to name.

Operators

Mathematical

+ Additon
- Subtraction
* Multiplicaiton
/ Divison
** Exponents
% Remainder
abs() Absolute value

Operators

Relational

== Equal to
!= Not equal to
> Greater than
< Less than
Greather than or equal to
Less than or equal to

Operators

Logical

and Logical 'and'
or Logical 'or'

Operators

Examples


                        In [1]: 2 + 2 * 3
                        Out[1]: 8

                        In [2]: (2 + 2) * 3
                        Out[2]: 12

                        In [3]: 3.1415 * 2
                        Out[3]: 6.283

                        In [4]: 5/2
                        Out[4]: 2.5

                        In [5]: 2**100
                        Out[5]: 1267650600228229401496703205376
                        

Data Types

Data Types - String

  • Immutable sequence of characters
  • Examples: Spam, eggs, and spam and eggs

                        In [1]: S = "Spam"
                        

Data Types - String

  • To get the length f a string, use: len(string_name)

                        In [1]: S = "Spam"

                        In [2]: len(S)
                        Out[2]: 4
                        

Data Types - String

  • Indexing: items are ordered left-to-right, beginning with 0
  • string_name[index]

                        In [1]: S = "Spam"

                        In [2]: len(S)
                        Out[2]: 4
                        
                        In [3]: S[0]
                        Out[3]: 'S'

                        In [4]: S[2]
                        Out[4]: 'a'

                        In [5]: S[-1]
                        Out[5]: 'm'
                        

Data Types - String

  • Slicing: Extracts whole sections
  • string_name[begin:end]

Try: S[1:3]


                        In [1]: S = "Spam"

                        In [2]: len(S)
                        Out[2]: 4
                        
                        In [3]: S[1:3]
                        Out[3]: 'pa'
                        

Data Types - String

  • Concatenation: join two string with "+"
  • Repetition: repeat a string with "*"

Try: S[1:3]


                        In [1]: S = "Spam"

                        In [2]: len(S)
                        Out[2]: 4

                        In [3]: S + 'Eggs'
                        Out[3]: 'SpamEggs'

                        In [4]: S * 4
                        Out[4]: 'SpamSpamSpamSpam'
                        

Data Types - Lists

  • Indexing and slicing - Just like strings
  • Try: L[1] and L[0:-1]

                        In [1]: L = [1, 'spam', 4.0, 'U']

                        In [2]: L
                        Out[2]: [1, 'spam', 4.0, 'U']

                        In [3]: L[1]
                        Out[3]: 'spam'

                        In [4]: L[0:-1]
                        Out[4]: [1, 'spam', 4.0]
                        

Data Types - Lists

  • Can grow and shrink on command
  • Try: L.append('eggs') and L[3]

                        In [1]: L = [1, 'spam', 4.0, 'U']

                        In [2]: L
                        Out[2]: [1, 'spam', 4.0, 'U']

                        In [5]: L.append('eggs')

                        In [6]: L
                        Out[6]: [1, 'spam', 4.0, 'U', 'eggs']

                        In [7]: del L[3]

                        In [8]: L
                        Out[8]: [1, 'spam', 4.0, 'eggs']
                        

Data Types - Lists

  • Can create multidimensional lists
  • Start with an empty list

                        In [1]: M = []
                        

Data Types - Lists

  • Can create multidimensional lists
  • Add a new list: [1, 2, 3]

                        In [1]: M = []

                        In [2]: M.append([1, 2, 3])

                        In [3]: M
                        Out[3]: [[1, 2, 3]]
                        

Data Types - Lists

  • Can create multidimensional lists
  • Add another list: [4, 5, 6]

                        In [1]: M = []

                        In [2]: M.append([1,2,3])

                        In [3]: M
                        Out[3]: [[1, 2, 3]]

                        In [4]: M.append([4, 5, 6])

                        In [5]: M
                        Out[5]: [[1, 2, 3], [4, 5, 6]]
                        

Data Types - Lists

  • Can create multidimensional lists
  • Index the list. Try extracting the 3

                        In [1]: M = []

                        In [2]: M.append([1,2,3])

                        In [3]: M
                        Out[3]: [[1, 2, 3]]

                        In [4]: M.append([4, 5, 6])

                        In [5]: M
                        Out[5]: [[1, 2, 3], [4, 5, 6]]

                        In [6]: M[0][2]
                        Out[6]: 3
                        
                        

Data Types - Lists

  • Lists are dynamic and heterogeneous.
  • Don't need to allocate space, and can mix types!

                        In [1]: A = []
                        In [2]: A.append([1, 2, 3])

                        In [3]: A
                        Out[3]: [[1, 2, 3]]

                        In [4]: A.append(['spam', 'eggs'])

                        In [5]: A
                        Out[5]: [[1, 2, 3], ['spam', 'eggs']]

                        In [6]: A.append([4.0, 'spam', [1, 2, 'string'], 5])

                        In [7]: A
                        Out[7]: [[1, 2, 3], ['spam', 'eggs'], [4.0, 'spam', [1, 2, 'string'], 5]]
                        
                        

Data Types - Tuples

  • Like lists, but immutable!
  • Example: (1, 'spam', 4.0, 'U')

                        In [1]: T = (1, 'spam', 4.0, 'U')
                        

Data Types - Tuples

  • Length, concatenation, Indexing
  • Try: len(T); T + (5,6); T[1]

                        In [1]: T = (1, 'spam', 4.0, 'U')

                        In [2]: len(T)
                        Out[2]: 4

                        In [3]: T + (5,6)
                        Out[3]: (1, 'spam', 4.0, 'U', 5, 6)

                        In [4]: T[1]
                        Out[4]: 'spam'
                        

Data Types - Tuples

  • Change or remove elements
  • Try: del T[2]

                        In [1]: T = (1, 'spam', 4.0, 'U')
                        In [2]: len(T)
                        Out[2]: 4

                        In [3]: T + (5,6)
                        Out[3]: (1, 'spam', 4.0, 'U', 5, 6)

                        In [4]: T[1]
                        Out[4]: 'spam'
                        
                        In [5]: del T[2]
                        ---------------------------------------------------------------------------
                        TypeError                                 Traceback (most recent call last)
                        <ipython-input-5-9678804ef101> in <module>()
                        ----> 1 del T[2]
                        TypeError: 'tuple' object doesn't support item deletion
                        

Data Types - Dictionaries

  • Mutable key-value pairs
  • Example: {'food': 'spam, 'color': 'pink', 'quantity': 4}

                        In [1]: D = {'food': 'spam', 'color': 'pink', 'quantity': 4}
                        

Data Types - Dictionaries

  • Index with keyword
  • Try: D['food']

                        In [1]: D = {'food': 'spam', 'color': 'pink', 'quantity': 4}

                        In [2]: D['food']
                        Out[2]: 'spam'
                        

Data Types - Dictionaries

  • Change values
  • Try: D['quantity'] += 1

                        In [1]: D = {'food': 'spam', 'color': 'pink', 'quantity': 4}

                        In [2]: D['food']
                        Out[2]: 'spam'

                        In [3]: D['quantity'] += 1

                        In [4]: D
                        Out[4]: {'color': 'pink', 'food': 'spam', 'quantity': 5}
                        

Conditional Statements


                        if conditon_1
                            do something
                        elif conditon_2:
                            do something else
                        else:
                            do thing number 3
                        

Example of a script


                        >>> spam = input(“2 letter word for (and rhymes with) you & me: “) >>> guido = [spam, ‘eggs’]
                        
                        >>> if guido[1] == ‘eggs’:
                                guido[1] = ‘are the’ >>> x = guido
                        
                        >>> sausage = input(“Like a time of day, but begins with ‘k’: “)
                        >>> y = sausage + ‘s’
                        
                        >>> bacon = input(“Fill in the blank in this children’s game: Simon ____: “) >>> z = [‘who’, bacon[0:-1]]
                        
                        >>> print( x, y, z, “Ni!”)
                        

Back to main website:

https://tinyurl.com/bcb18