Intro to Python

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Python

Lets run some code in python!

Interactive1 mode (you will see me use this for quick examples):

  • open a terminal (aka shell)
  • type python (or python3)

Python variables

  • You do not need to declare variables
  • Python is dynamically typed
    • Variables do not have a type
    • Values have a type
    • Type safety is enforced as the program runs

To know something’s type: type(x)

Python types

  • strings
    • “double quotes”
    • ‘single quotes’
    • “““triple-double quotes”“” (these can go over multiple lines and contain double quotes)
  • integers
  • floating point values (doubles)
  • complex numbers
  • booleans

Python types

type("hello")
type('hello')
type(2)
type(2.0)
type(2+3j)
type(True)

Floating Point Errors

0.1 + 0.2
0.30000000000000004
  • There are several reasons floats are not exactly accurate
  • Python approximates 0.1 as around 0.10000000000000000555, 0.2 as 0.2000000000000000111, and 0.3 as 0.29999999999999998889
format(0.1, ".20f" )
'0.10000000000000000555'

Suggestions on how to solve the 0.1 + 0.2 == 0.3 problem?

Python type conversion functions

  • Math follows “standard” rules (only returns int, if both parameters are int, except division, which always returns a float )
  • conversion methods try to turn their input into the given type
int(x)
float(x)
str(x)

Error is thrown if conversion is not possible

Python Expressions

An expression in programming language is a piece of code that describes/computes a value

Types of expressions:

  • literals (5, 2.45, “apple”, True)
  • variables
  • function calls
  • mathematical expressions
  • boolean expressions

(lots of other expressions through operator overloading)

Python math expressions

Python follows the same math syntax and rules as most other programming languages

Exceptions:

  • Two division operations:
    • / (always float value)
    • // (always round down)
  • ** performs exponentiation

Python Script

Let’s switch to Visual Studio code and run Python scripts

Statements (vs expressions)

  • Expressions represent values or the computation of values
  • Statements represent executable steps in a program
  • Statements often include expressions

Here’s a statement that invokes the print function with the expression 3 + 4 as an argument.

print(3 + 4)
7

Documentation

Three ways to document your code:

  • Use good variable names - python prefers snake_case naming
  • in-line comments #
  • Docstrings - strings included as first lines of programs or functions

Python function

Use def function_name(parameter) to define a function. Notice the indentation

def double(n):
  """ returns double of n """
  result = n * 2
  return result
  • whitespace denotes code blocks
  • don’t miss the colon which marks the beginning of a block

Call the function:

print(double(5))
10

What happens if there’s no return statement?

Blocks of code in python

Code block – A casual term for a series of lines of code, often introduced in if statements, loops, and functions

In Python whitespace characters must match exactly - careful with spaces and tabs.

Example

def is_divisible(x, n):
  """Returns True if x is divisible by n"""
  return (x % n) == 0

def is_even(x):
  """ Returns True if x is even """
  return is_divisible(x, 2)

if __name__ == "__main__":
  assert is_even(4) == True

Exercise

Write a python function called circle_area, that calculate the area of a circle given a radius parameter (it returns the circle area).

  • formula: \(area = \pi * radius^2\)
  • use 3.1415 for \(\pi\)

Tests:

assert circle_area(7) == 153.9335
assert circle_area(4) == 50.264
assert circle_area(10) == 314.15000000000003

Submit your solution (name your file circle.py) to gradescope

Solution 1

def circle_area(radius):
  area = 3.1415 * (radius ** 2)
  return area

if __name__ == "__main__":
  assert circle_area(7) == 153.9335
  assert circle_area(4) == 50.264
  assert circle_area(10) == 314.15000000000003
  print("Passed all tests")
Passed all tests

Solution 2

def circle_area(radius):
    pi = 3.1415
    area = pi * radius ** 2
    return area

Warnings

  • A function call that returns a value is not the same as printing to the standard output
  • Note we are not taking input from the user yet
  • A function is like a box, arguments go in, values come out