greends-ipython

Introduction to Python 2023/2024

Masters in Data Science applied to agricultural and food sciences, environment, and forestry engineering.

Instructor: Manuel Campagnolo (mlc@isa.ulisboa.pt)

Class contents:

Class 1 (September 15, 2023): Install Python and VSCode; first examples; strings
  1. CS50P, Section on “Functions, Variables”
  2. Some useful keyworks for the command line interface in terminal:
    • code filename.py to create a new file
    • ls to list files in folder
    • cp filename newfilename to copy a file, e.g. cp ..\hello.py farewell.py (.. represents parent folder)
    • mv filename newfilename to rename or move file, e.g. my farewell.py goodbye.py or mv farewell.py .. (move one folder up)
    • rm filename to delete (remove) file
    • mkdir foldername to create new folder
    • cd foldername change directory, e.g. cd ..
    • rmdir foldername to delete folder
    • clear to clear terminal window
  3. CS50P, Section on “Functions, Variables”
    • Notes: Lecture 0 Creating Code with Python; Functions; Bugs; Improving Your First Python Program: Variables, Comments, Pseudocode; Further Improving Your First Python Program; Strings and Parameters; A small problem with quotation marks; Formatting Strings; More on Strings.

    • Do before next class. Video on CS50 Video Player or YouTube: follow video and recreate exercises on VS Code up to 59’ approximately (up to the section on integers ‘int’).

Class 2 (September 22, 2023): Floats; Conditionals; ...
  1. Questionnaire Q0 (test) on the topics of the previous class;
  2. Work on Problem set 0: “indoor voice”, “playback speed”, and “making faces”. For this last one, check the emoji chart and follow the instructions: Every emoji has a unique Unicode assigned to it. When using Unicode with Python, replace “+” with “000” from the Unicode. And then prefix the Unicode with “\”. For example, “U+1F605” will be used as “\U0001F605”. But there are alternative ways to encode emojis in your Python code: check this link
  3. Do before next class. Complete Lecture 0 and video CS50 Video Player until the end, on the following topics: Integers or int; Readability Wins; Float Basics; More on Floats; Def; Returning Values
  4. Do before next class. Study Lecture 1 up to “Modulo” and watch video CS50 Video Player: Lecture 1 up to approximately 34’ on the topics: Conditionals, if Statements, Control Flow, or, and.

All topics to prepare before next class: Integers or int; Readability Wins; Float Basics; More on Floats; Def; Returning Values; Conditionals, if Statements, Control Flow, or, and, How to organize a program with main() and auxiliary functions.

Class 3 (September 29, 2023): Loops; Lists; ...
  1. Questionnaire Q1 on the topics of the homework;
  2. Work on Problem set 0: Einstein. Work on Problem set 1: The Hitchhiker’s Guide to the Galaxy’s Deep Thought, Home Federal Savings Bank, File Extensions.
  3. Do before next class. Study the remainder of Lecture 1 starting at “Modulo” and watch video CS50 Video Player: Lecture 1 after 34’.
  4. Do before next class. Study Lecture 2 up to “More about lists” and “Length” and watch video CS50 Video Player: Lecture 2 up to approximately 45’.
  5. Do before next class. Try solving problems from Problem Set 2: Camel; Coke Machine; Just setting up my twttr

Topics to prepare before next class: Modulo; Creating Our Own Parity Function; Pythonic; match, Loops; While Loops; For Loops; Improving with User Input; More About Lists; Length

Class 4 (October 6, 2023): Dictionaries; Functions; ...
  1. Questionnaire Q2 on the topics of the homework;
  2. Work on problems from Problem Set 2: Camel; Coke Machine; Just setting up my twttr (P1: submit in Fenix one of those problems to be indicated in class)
  3. Do before next class. Study remainder of Lecture 2 watch video CS50 Video Player: Lecture 2 starting at Dictionaries (~45’).
  4. Do before next class. Lecture 3 and video CS50 Video Player: Lecture 3
  5. Do before next class. Try solving problems from Problem Set 3. Note: for the “Taqueria” problem: EOFError is the error raised by “CRTL-D” in Mac and “CTRL-Z” in Windows.

Topics to prepare before next class: Dictionaries, More on code modularity (Mario example), Exceptions, Runtime Errors, try, else, Creating a Function to Get an Integer, pass

Class 5 (October 13, 2023): Libraries; …
  1. Questionnaire Q3 on the topics of the homework
  2. Work on problems from Problem Set 3.
  3. Do before next class. Lecture 4 and video CS50 Video Player: Lecture 4
  4. Do before next class. Try solving problems from Problem Set 4. Try problem “Guessing Game” (not hard) and “Little Professor” (group assignment). For the group assigment, the goal is to fill the missing code in professor_incomplete.py. The completed code should pass the correctness test in https://cs50.dev/.

Topics to prepare before next class: Libraries, Random, Statistics, Command-Line Arguments, slice, Packages, APIs, Making Your Own Libraries

Class 6 (October 20, 2023): Organizing and testing code; Unit tests
  1. Questionnaire Q4 on the topics of the homework
  2. Evaluated group assignment (“Little Professor”) in class
  3. Discussed references in Python with examples from Part 5 of PP.fi and made experiments with PythonTutor: Visualize code.
  4. Do before next class. Some groups still have to improve the previous assignment. All groups should solve Problem P3 (also a group assigment):
Class 7 (October 27, 2023): File I/O
  1. Questionnaire Q5 on recent topics
  2. Evaluate group assignment P3 (“Distances”) in class
  3. Unit tests with pytest: examples
  4. Do before next class (November, 11).
Class 8 (November 10, 2023): Pandas
  1. Questionnaire Q6 on recent topics.
  2. Evaluate group assignment on Unit Tests in class (P4 “Haversine”).
  3. Pandas: series and dataframes; I/O; first examples.
  4. Do before next class (November 17).
Class 9 (November 17, 2023): Regular expressions
  1. Questions about Pandas.
  2. Questionnaire Q7 on recent topics.
  3. Finish to evaluate group assignment P4 on Unit Tests (“Haverside”) in class (remaining groups)
  4. Regular expressions (regex)
  5. Do before next class (November 24).
Class 10 (November 24, 2023): Object-oriented programming
  1. Questions about regular expressions and problems “NUMB3RS” and “Regular, um, Expressions”. Indication on how to submit the assignment.
  2. Questionnaire Q8 on recent topics.
  3. Presentation of the semester project.
  4. Object-oriented programming: see script mage_v1.py
  5. Do before next class (December 15).
Class 11 (December 15, 2023): Object-oriented programming; sets, global, unpacking, args and kwargs
  1. Solve Cookie jar problem and submit code in Fenix (P6)
  2. Questionnaire Q9 on object-oriented programming;
  3. Presentation of some additional Python topics with examples
  4. Do before next class (December 22).
  5. Example of use of *argsand **kwargs. Check examples scripts in the ETC folder.
Class 12 (December 22, 2023): Args and kwargs, list comprehension, dictionary comprehension, lambda, map, filter
  1. Discussion of assigments P5 (numb3rs and um)
  2. Discussion of guidelines for final project
  3. Presentation of some topics from Lecture 9: args (*) and kwargs (**), list comprehensions, lambda functions, map, filter, dictionary comprehensions. Check examples scripts in the ETC folder.

    Example: distinct possible ways of creating a list with all the cubes of even numbers up to N. In the last cases, map applies a given function to each element of a list. Likewise, filter applies a boolean function to filter elements of a list. Both function can be executed in parallel over the elements of the list since each output is independent of the outputs for the remainder elements of the list.

    • With list comprehension:
      def cube(x):
          return x*x*x
      L=[cube(x) for x in range(N) if x%2==0]
      
    • With filter to select even numbers and mapto compute cubes:
      def even(x):
          return x%2==0
      numbers=list(range(N))
      even_numbers=list(filter(even, numbers))
      cubes=list(map(cube,even_numbers))
      
    • Also with filter and map but defining implicitly the cube and even functions with lambda instead of def:
      numbers=list(range(N))
      even_numbers=list(filter(lambda x: x%2==0, numbers))
      cubes=list(map(lambda x: x*x*x,even_numbers))
      
    • The most compact way of solving the problem involves lambda and list comprehension. In the example below, if one would just write lambda x: x*x*x instead pf (lambda x: x*x*x)(x) the output list would be a list of lambda functions.
      L=[(lambda x: x*x*x)(x) for x in range(N) if x%2==0]
      
  4. Observations about using vectorization to speed-up computations.

    A conditional can be replaced by arithmetic and logical operations. For example, let L=[x/5 for x in range(-10,10)] be a list of equally spaced numbers between -2 and 2, and say we want to apply the stepwise linear sigmoid function to the elements of the list. One could define sigma as below and then apply it to L with map.

    def sigma(x):
        if x>1:
            return 1
        elif x<-1:
            return -1
        else:
            return x
    list(map(sigma,L))
    

    However, instead of using the conditional if once can define sigma in a simpler way with logical and arithmetic operations.

    def sigma(x):
        return (x>=1)*1+(-1<x<1)*x+(x<=-1)*-1
    list(map(sigma,L))
    

    Note that we don’t need to define explicitly sigma: it could be encapsulated in a lambda function lambda x: (x>=1)*1+(-1<x<1)*x+(x<=-1)*-1 as the first argument of map. One advantage of using arithmetic and logical operations is that computations can then be easily vectorized, which allows to speed them up, since the processing time for a pair of vectors is similar to the processing time for a pair of numbers.

    Similarly to list comprehension, Python provides dictionary comprehension which allows to create dictionaries. The example below uses ordwhich is a function that returns the ascii index of a character, to create a dictionary of vowels, where the key is the vowel in uppercase and the value is the rank of the letter starting at 0 for a.

    {x.upper(): ord(x.lower())-97 for x in 'aeiou'} # returns {'A': 0, 'E': 4, 'I': 8, 'O': 14, 'U': 20}
    

Install Python 3 and Visual Studio Code (VS Code)

Steps to install Python 3 and Visual Studio Code

Python in VS Code:

Python documentation and tutorials

CS50P

The main tutorial for the class is CS50P. The table below compares the contents of that course with another well-known free online Python Programming course at PP.fi. The CS50P course problem sets tend to be difficult, while you can find at PP.fi a set of problems with a larger range of difficulty, from very easy to advanced. Both online courses provide a platform for coding and testing the corretness of the solutions. Both courses provide recorded lectures: CS50P and PP.fi.

Comparison of CS50P and PP.fi
CS50P Contents PP.fi Contents
Lecture 0 Creating Code with Python; Functions; Bugs; Strings and Parameters; Formatting Strings; More on Strings; Integers or int; Readability Wins; Float Basics; More on Floats; Def; Returning Values Part 1 Information from the user; More about variables; Arithmetic operations; Conditional statements
Lecture 1 Conditionals, if Statements, Control FlowModulo; Creating Our Own Parity Function; Pythonic; match Part 2 Programming terminology; More conditionals; Combining conditions; Simple loops
Lecture 2 Loops; While Loops; For Loops; Improving with User Input; More About Lists; Length; Dictionaries, More on code modularity Part 3 Loops with conditions; Working with strings; More loops; Defining functions
    Part 4 The Visual Studio Code editor, Python interpreter and built-in debugging tool; More functions; Lists; Definite iteration; Print statement formatting; More strings and lists
    Part 5 More lists; References; Dictionary; Tuple
Lecture 3 Exceptions, Runtime Errors, try, else, Creating a Function to Get an Integer, pass Part 6 Reading files; Writing files; Handling errors; Local and global variables
Lecture 4 Libraries, Random, Statistics, Command-Line Arguments, slice, Packages, APIs, Making Your Own Libraries Part 7 Modules; Randomness; Times and dates; Data processing; Creating your own modules; More Python features
Lecture 5 Unit Tests; assert; pytest; Testing Strings; Organizing Tests into Folders    
Lecture 6 File I/O; open; with; CSV; Binary Files and PIL    
Lecture 7 Regular Expressions; Case Sensitivity; Cleaning Up User Input; Extracting User Input    
Lecture 8 Object-Oriented Programming; Classes; raise; Decorators; Class Methods; Static Methods; Inheritance; Inheritance and Exceptions; Operator Overloading Part 8 Objects and methods; Classes and objects; Defining classes; Defining methods; More examples of classes
    Part 9 Objects and references; Objects as attributes; Encapsulation; Scope of methods; Class attributes; More examples with classes
    Part 10 Class hierarchies; Access modifiers; Object oriented programming techniques; Developing a larger application
Lecture 9 set; Global Variables; Constants; Type Hints; Docstrings; argparse; Unpacking; args and kwargs; map; List Comprehensions; filter; Dictionary Comprehensions; enumerate; Generators and Iterators Part 11 List comprehensions; More comprehensions; Recursion; More recursion examples
    Part 12 Functions as arguments; Generators; Functional programming; Regular expressions

Documentation

You can find information on basic concepts and features of the Python language and system at The Python Tutorial at python.org.

Other tutorials

w3schools, etc
  1. A nice interactive site is W3schools’ Python Tutorial where you can find in particular an easy to use Python reference documentation.

  2. Another nice and very clear series of videos on Python are available in this Youtube channel: Python Tutorials by Corey Schafer. In particular, you might be interested in the following specific topics discussed in class:

Problem sets

  1. List of both simple and more advanced programming exercises that you can run and test online: programming-23.mooc.fi. Sign-in to have access to code editor and testing.

  2. Compiled list of CS50P proposed problems (to be completed)

  1. PythonTutor, that show how Python manages variables in memory: Visualize code
  2. Regular expressions: https://regex101.com/

Student projects

Project repositories
  1. Calculation of the Enteric Fermentation Methane Emission Factor of Cows

  2. Scrabble Training

  3. Forecast Hunter: A toolbox for assessing seasonal weather forecast data usability on ETo estimation

  4. Customized and fast downloading of satellite images

  5. Pest Tracker: simular uma aplicação para a previsão da praga da mosca da azeitona no olival

  6. Pokemon_battle_simulator

  7. Forest roads under the influence of heavy rain events

  8. Weather Report

  9. As suas receitas na palma da mão

  10. Word Wizardry

  11. Calculation of Urban Density with QGIS and Python

  12. Avaliação do risco de tempestades

  13. Fertilização: auxiliar a fertilização com base em resultados de análises de solo