PYTHON CRASH COURSE -
A COMPARISON WITH JAVA
    CS 334: Machine Learning
                      COURSE REMINDERS
•   In-Class exercise #1 due 1/31
    •   Read the syllabus
•   Python workshops running for the
    first 3 weeks with 2 offerings
•   You need a functional Python 3
    environment for today’s class
                                         2
                          PYTHON USES
•   Web Development (e.g., Django, Flask)
•   Data Analysis (e.g., NumPy, Pandas, Matplotlib, Seaborn)
•   Internet of Things (e.g., Raspberry Pi + Python)
•   Web Scraping
•   Machine Learning + Computer Vision (e.g., scikit-learn, nltk,
    tensorflow, OpenCV)
                                                                    3
PYTHON VS JAVA
           https://data-flair.training/blogs/python-vs-java/
                                                               4
         PYTHON VS JAVA KEY DIFFERENCES
•   Designed to be used interpretively (i.e., no need for explicit
    compilation)
    •   Statement can be entered at the interpreter prompt (>>>>)
    •   Execution is immediate
•   Line-oriented: End of line is completion of a statement (unless
    explicitly escaped with \)
                                                                      5
           VARIABLES / BASIC DATA TYPES
•   Python is dynamic typed
    which means you can              Basic Data     Java        Python   Example
    introduce a variable by            Types
    assigning some value to it         Integer    int/Integer     int      a=1
    without explicitly declaring        Float     float/Float    float    a=1.5
                                        String      String        str    a=“Hello”
    type
                                       Boolean     boolean       bool     a=True
•   Variable type can change later
                                                                                     6
                           COMMENTS
•   Single line comments begin with #
    (// in Java)
•   Multi-line comments can begin with """ and end with """
    (/* and */ in Java)
•   Example:
    # initialize foo to 1
    foo = 1
                                                              7
                       CODING EXAMPLE
•   Declare a variable foo with your
    favorite number
•   Print the variable (i.e., print(foo))
•   Assign foo with a string (Use “ or ‘)
•   Print the variable again
                           COMMON OPERATORS
          Operator                  Java     Python   Python Example
            Addition                  +        +            1+2
             Minus                    -        -            2-1
            Division                  /        /            4/2
          Multiplication              *        *            2*4
            Modulo                    %        %           4%3
              Equal                  ==       ==           2 == 3
   Less Than / Less Than Equal      < / <=   < / <=        2<3
Greater Than / Greater than Equal   > / >=   > / >=        2>3
              And                    &&       and      x < 5 and x > 2
               Or                     ||       or      x < 5 or x > 2
              Not                     !       not        not (x < 5)
                                                                         9
            COMMON DATA STRUCTURES
        Type                   Java        Python   Python Declaration
        Tuple                   ---         tuple            x=(1,2,3,3)
(immutable ordered list)
          List                List<V>        list              x = []
                                                           x = [1, 2, 3, 3]
      Dictionary           HashMap<K, V>    dict                 x={}
                                                    x = {‘a’:1, ‘b’:2, ‘c’:3, ‘d’: 3}
          Set                 Set<V>         set              x=set()
                                                            x = {1,2,3,3}
                                                                                        10
                       CODING EXAMPLE
•   Create a list foo with 4 floats
•   Print the 3rd element of the list (i.e.,
    print(foo[2]))
•   Create a dict food with 4 keys (‘a’, ‘b’,
    ‘c’, ‘d’) and 4 values (of your choice)
                              IF/ELSE
                       Java                          Python
if (x < 5) {                      if x < 5:
    // call do1                       # call do1
    do1();
} else if (x < 10) {
                                      do1()
                                  elif x < 10:
                                                   Indentation matters
    // call do2                       # call do2    - it determines the
    do2();                            do2()
} else {                          else:                    scope!
    // call do3                       # call do3
    do3();                            do3()
}
                                                                          12
                               FOR
                      Java                            Python
for (foo in bar) {              for foo in bar:
   // call do1                     # call do1
   do1(foo);                       do1(foo)
}
for (int i=0; i < 10; i++) {    for i in range(10):
   // call do1                     # call do1
   do1(foo[i]);                    do1(foo[i])
}
                               range creates a sequence between 0
                                    to 9 with increments of 1
                                                                13
                      CODING EXAMPLE
•   Loop through each element of the list
    and only print out the elements that
    are greater than a value of your
    choosing. This value should be chosen
    such that you print out at least 1
    element of your list
•   Print the key and values associated with
    food by looping through dictionary
    items using food.items()
                            WHILE
                     Java                      Python
while (foo < 10) {           while foo < 10:
  // call do1                  # call do1
  do1();                       do1()
}
                                                        15
                 METHODS / FUNCTIONS
                   Java                      Python
double square(double x) {   def square(x):
  return x*x;                 return x*x
}
        Major differences:
        • Function DOES NOT need to occur in class
        • Return type and input types are not declared
        • Indentation defines body of function
                                                         16
                                           CLASSES
                       Java (Foo.java)                                Python (Foo.py)
public class Foo {                             class Foo:
  double a; // class attribute                    a = None # class attribute
    // Constructor                               # Constructor
    public Foo(double a) {                       def __init__(self, a):
        this.a = a;                                  self.a = a
    }
                                                 # Method called bar
    // Method called bar                         def bar(self, b):
    double bar(double b) {                           return self.a * b
        return a * b;
    }                                          def main():
}                                                  foo = new Foo(5.0)
                                                   print(foo.bar(2.4))
public static void main(String[] args) {
   Foo foo = new Foo(5.0);                     if __name__ == “__main__”:
   System.out.println(foo.bar(2.4));               main()
}
                                                                                        17
                     IN-CLASS EXERCISE #2
•   Download exercise2.py from Canvas ->
    Files -> Exercises -> Ex2
•   Fill in the 5 functions by following the
    specifications in the multi-line comments
    (""" à """)
•   Submit to Gradescope (Exercise #2)
    •   Closes 15 minutes after class ends today
                                                   18
         GRADESCOPE AUTOGRADER TIPS
•   Do not import any package that is not specified in requirements.txt
    or already imported for you (ignore the gradescopeutils package)
•   Public tests will give you an idea of whether your output format is
    correct, logic correctness is generally not exposed until after grading
•   Submit early and often to get feedback!
                                                                              19
EXERCISE #2: ADD_TWO
EXERCISE #2: CONVERT_C_TO_F
EXERCISE #2: SUM_LIST
EXERCISE #2: SUM_DICT
EXERCISE #2: IS_PRIME
         HOMEWORK #1 ANNOUNCEMENT
•   Out today on Canvas and due 2/6 @ 11:59 PM ET on Gradescope
•   4 questions
    •   Q1: Get familiar with Python
    •   Q2: Numerical programming (Numpy)
    •   Q3-Q4: Dataset loading and visualization (Pandas)
                                                                  25