Introduction to Python III

Text Editor

  • Geany
  • sudo apt-get install geany 
  • Open geany and then open a .py file you've created before in this class
  • Build > Set Build Commands
    • Compile command: python3 -m py_compile "%f"
    • Execute command: python3 "%f"
  • Execute your Python scripts with F5

Review

  • Conditional statements
  • Loops
  • Blocks of code
  • Input

Review Exercise

If you have $100 saved in your bank account, and they pay you 3% interest every year, how much money will you have for each year, up to 10 years?

 

Hint: Use a for-loop. Don't forget to add the interest to the total

Functions

  • Functions allow you to write code just once, then reuse that code in your programs multiple times
  • Functions take in parameters, which is a variable you give it that is only available in the body of the function (the block of code inside of it)
def function(parameter):
    # block of code

Example of a Function

def printName(name):
       print("Hello, %s!" % name)

You define (make) the function like this:

And call it like this:

printName("John")

Which will return:

Hello, John!

Remember input()?

Example of a Function

def savings(chores, paper, spending):
    return chores + paper - spending
    # or return(chores +paper - sending)

Another example, except with return() instead of print:

And call it like this:

print(savings(10, 10, 5))

Which will return:

15

What does return() do? What's the different between return() and print()?

# comments the code

Scope

  • Not all variables are accessible from all parts of our program.
  • Where a variable is accessible depends on how it is defined.
  • We call the part of a program where a variable is accessible its scope.
  • ​A variable which is defined in the main body of a file is called a global variable.
    • It will be visible throughout the file, and also inside any file which imports that file.
  • A variable which is defined inside a function is local to that function.
    • It is accessible from the point at which it is defined until the end of the function
# This is a global variable
a = 0

if a == 0:
    # This is still a global variable
    b = 1

def my_function(c):
    # this is a local variable
    d = 3
    print(c)
    print(d)

# Now we call the function, passing the value 7
# as the first and only parameter
my_function(7)

# a and b still exist
print(a)
print(b)

# c and d don't exist anymore -- these statements
# will give us name errors!
print(c)
print(d)

SSH

  • Remotely access your Pis with Secure Shell
  • On your Pi: ifconfig
    • Look for the IPv4 (inet) address uner eth0
  • On your laptop: ssh pi@IP
  • Type in your password
    • First 3 letters of Pi name reversed, pi183
    • The first letter of your pi name is capitalized in the password
      • ex Pi name: awesomepi
      • Password: ewApi183

Introduction to Python III

By jtheadland

Introduction to Python III

  • 708