CMSC330

Python

Python

Intro
Typing
Scoping
Object Orientation
Data Types and Syntax

Intro

Intro

Our First Program
# hello_world.py
print("Hello, World!")
          
  • Comments use #
  • no semicolons needed
  • print() to print
python hello_world.py
          

Typing

Our Second Program
# typing.py
y = "hello"
y = 3
z = 4
print(y + z)
          
python typing.py
          
  • No error?
  • No variable type?

Python uses dynamic and latent typing

Type Checking

Type Checking: The process of determining a variable's type

Dynamic typing: type checking is performed at run-time

Static typing: type checking is performed at compile-time

Typing

Manifest (explicit) typing: explicitly telling the compiler the type of new variables

Types are associated with variables

Latent (implicit) typing: not needing to give a type to a variable

Types are associated with values

Scoping

Something Familiar
# scoping-1.py
a = 5
b = 20
def h(c):
  d = True
  e = 0
  while d:
    if c < b - c:
      c = c + 1
      e = e + 1
    else:
      d = False
  return e

f = input("Enter a number: ")
print(h(int(f)) + a)
          
Also Familiar
# scoping-2.py
a = 5
def b():
  print(a)
b()
          

But consider:

# scoping-3.py
a = 5
def b():
  a = a + 1
  print(a)
b()
          
# scoping-3.py
a = 5
def b():
  a = a + 1
  print(a)
b()
          

Enter the 'global' keyword

# scoping-3.py
a = 5
def b():
  global a
  a = a + 1
  print(a)
b()
          

Object Oriented Programming

Python support Object Oriented Programming (OOP)

a = "hello"
type(a) # class str
a.upper() # "HELLO"
a.islower() # True
          

Objects have methods

Python has an equivalent to Java's Null

print(None)

Reminders about Object Oriented Programming

Values are references to Objects

Objects are instances of Classes

Classes inherit from each other

Class Creation
class Square:
  def __init__(self,size):
    self.size = size

  def area(self):
    s = self.size
    return s * s

s = Square(5)
print(s.area())
          
Class Creation
class Square:
  def __init__(self,size):
    self.size = size

  def area(self):
    s = self.size
    return s * s

s = Square(5)
print(s.area())
          
public class Square{
  private int size;
  public Square(size){
    this.size = size;
  } 

  public int area(){
    int s = size;
    return s * s;
  }
} 

public static void main(String[] args){
  Square s = new Square(5);
  System.out.println(s.area);
}
          

Things to Note

Instance variables are public

__init__ is the constructor

methods typically need self parameter

Indentation matters!

Data Types and Syntax

Integers and Floats

          type(1)         #int
          type(2+3)       #int
          type(1.0)       #float
          type(1.5*2)     #float 
          type(int(1.5))  #int
          
Strings

          "hellos"
          len("hello") #5

          #structural equality
          "hello" == "hello" #True

          # can concatonate variables
          name = "cliff"
          print("My name is " + name)

          # cannot concatonante non strings
          print("I am older than " + 18) #fail

          # but can repeat strings
          print("na"*15 + " BATMAN!") 
          
Lists

          # bracket syntax
          lst = [1,2,3,4]
          lst = []
          lst = list()

          # can be heterogenous
          lst = [1,"hello",3.0]

          # bracket indexing
          lst = [1,2,3,4]
          print(lst[1])
          printlst[-1])

          # no bounds checking
          arr = [1,2,3,4]
          arr[3] = 3
          arr[5] = 6 #fail

          # multidimensional
          a = []
          a.append([])
          print(a)
          a[][] # error
          a = [[]]*5
          a = [[None] *3] * 3

          # has operations
          a = [1,2,3,4]
          b = [4,5,6,7]
          print(a+b)

          # stack behaviour
          a = [1,2,3]
          a.append(4)
          a.pop
          
Dictionary

          # Curly Brace syntax
          d = {}
          d = {"key":"value",}

          # bracket indexing
          print(d["key"])
          d["key2"] = "value2"

          # multidimensional
          d = {}
          d[0] = {}
          d[0][0] = 1
          print(d)
          
Conditionals

          True or False
          
          #syntax
          if False:
            print("not here")
          elif None:
            print("nor here")
          else:
            print("Here I am")

          # while loop
          count = 0
          while (count < 5):
            print(count)
            count += 1

          # for loop
          # must go through an iterator
          a = [1,2,3]
          for value in a
            print(value)