I719 Fundamentals of Python/lecture1v2

From ICO wiki
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Lesson 1

Running Python

There are executables python, python2, and python3 By default on ubuntu and most systems, python is symlinked to python2

python 2 or 3?

  • v2 is more commonly used
  • v3 is the official standard
  • all the code we write today will run on both versions

interactive

many interactive shells

  • default repl, python3
  • IPython (recommended), ipython3
  • bpython, bpython3

Run a python script

python3 my_script.py

Writing python

The editor must recognize that python requires a 4 space indent.

  • Use what ever editor you want
  • If you do not know what to do, use Spyder
  • If you want to learn something new, I recommend learning vim or emacs
  • PyCharm is a popular IDE

Language basics

Whitespace dependent

  • 4 space indent
  • no brackets { } like in java
  • no semicolons
  • indent level replaces brackets

For example in javascript:

function hi (name) {  // uses '{' to determine what is in function body
    return "Hi " + name;
}

would become in python:

def hi(name):  # code indented after the function definition is the function body, and is executed when the function is called
    return 'Hi {}'.format(name)

Comments and Documentation

  • use # for comments
  • use """ or to start and close multiline strings that will become documentation
def hi(name):
    """
    Prepend 'Hi ' before name. This is documentation
    """
    result = 'Hi {}'.format(name)  # this is a comment
    return result

Types

  • to find the type of a symbol a, use type(a)

Strings

hello = 'Hello World!'
print(hello)
  • double or single quotes are fine
  • length of string determined by function len()
  • concatenate strings with +
hello = 'Hello'
world = 'World'
hello_world = hello + ' ' + world  # 'Hello World'
  • substitute variable in a template string with format

    template_string = 'Hi {}'
    hi_bob = template_string.format('Bob')  # 'Hi Bob'
    

Arithmetic

  • uses operators like most other languages
  • similar to java, 1 + 1 returns 2

functions

  • to define a function, start with def
  • then the function name
  • functions are always in snake case. always lower case and words are separated by underscores
  • add the end of the name, list of arguments in parethesis
  • to document function, use triple quoted string after function definition
  • functions can use named arguments, which allow a default value for the argument. They are called 'Keyword Arguments'
  • Arguments can be made in order they are in the function definition, or be named specifically

Lists

lists in Python are like arrays in Java. They do not have predetermined length, and elements can be any type

a = [1, 2, 3]  # defines a list

For loops

Python's for is different from other languages. It is a "foreach" loop. It goes through each element of an iterator.

"""
0
1
2
"""
for i in range(3):
    print(i)

i in this example becomes an element of the iterator being iterated.

"""
H
e
l
l
o
"""
for character in "Hello":
    print(character)

Tasks

Task 1

"Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”."

Example Solution

for x in range(1,101):
    if x % 15 == 0:
        print("FizzBuzz")  # Catch multiples of both first.
    elif x % 3 == 0:
        print("Fizz")
    elif x % 5 == 0:
        print("Buzz")
    else:
        print(x)

Task 2

Write a function that meets these requirements:

Args: name: a string exclamation: optional, defaults to 'Hi'

Returns: string with name prefixed by the exclamation.

>>> test_function('Bob')
'Hi Bob!'
>>> test_function('Sally', exclamation='Bye')
'Bye Sally!'

Example solution

def hi(name, exclamation='Hi'):
    return '{e} {n}'.format(n=name, e=exclamation)

Task 2

Write a function that meets these requirements:

Args: numbers - a list of numbers

Returns: Boolean True if an odd number exists in the list of numbers False if only even numbers exist in numbers.

>>> test_function([2,1])
# 1 is an odd number
True
>>> test_function([2,4])
# Both 2 and 4 are even numbers
False

Example solution

def has_odd(l):
    for i in l:
        if i % 2 != 0:
            return True
    return False