Programming in Python

Hello Python

Gerald Senarclens de Grancy

Why Python?

Its features make it an excellent choice for beginners

Python's Advantages

  • Python compares favorable in terms of development time
  • Easy to learn
  • Simple and elegant syntax
  • Open Source
  • Multi paradigm scripting/ programming language
  • Platform independent
  • Excellent tools
  • Batteries included
  • Easily extensible - lots of third party modules
  • Huge community

Python's Disadvantages

  • Execution speed
  • Block delimiters confusing if editor is not properly configured
  • Limited application on mobile platforms

Jobs

When someone says "I want a programming language in which I need only say what I wish done" give him a lollipop.

Alan Perlis

Terminology

  • Variable, Assignment
  • Comment
  • Standard input, standard output and standard error
  • Source formatting/ indentation
  • Branching
  • Loops
  • Operator
    • A symbol representing an operation (eg.: mathematical operation)
    • There are arithmetic, logical, assignment, ... operators
  • Operator precedence
    • When in doubt, use parenthesis.
    • In order to make your code more readable, use parenthesis

Running Python Code

Python code can be executed in a shell by typing python $FILENAME

#!/usr/bin/env python3

"""
A 'Hello world!' program written in Python.
"""

print('Hello, World!')
Download hello.py

Python offers it's own read–eval–print loop (REPL), the Python shell
Python commands are immediately executed

Using python or ipython as a calculator

Getting help

When encountering an error message you do not understand, try pasting it into your favorite search engine

Branching

Allows to execute different commands based on provided conditions

The if statement

if <assignment_expression>:
    <suite>
(elif <assignment_expression>: <suite>)*
[else: <suite>]

Example (if)

#!/usr/bin/env python3

LANG = 'en'
# ...
if LANG == 'en':
    output = 'Good Morning!'
elif LANG == 'de':
    output = 'Guten Morgen!'
else:
    output = 'Bonjour!'
print(output)

Visualize execution

Conditional expression

<expression1> if <condition> else <expression2>

Example

#!/usr/bin/env python3

LANG = 'en'
# ...
output = "Good Morning!" if LANG == 'en' else "Guten Morgen!"
print(output)

Visualize execution

Exceptions

Allow splitting up error detection and error handling

try:
    <suite>
(except [<expression> [as <identifier>]]: <suite>)+
[else: <suite>]
[finally: <suite>]

Example (try)

#!/usr/bin/env python3

length = 3
rectangle_area = 12
# ...
try:
    width = rectangle_area / length
except ZeroDivisionError:
    print("The length of a rectangle must not be 0")
    # deal with problem or re-raise the exception
    raise
print(width)

Visualize execution

Python 3 Video Tutorial - Basic Control Flow

The while Statement

...is used for repeated execution as long as an expression is true

while <assignment_expression>:
    <suite>  # may include `break` and `continue`
[else: <suite>]
else
if <assignment_expression> is false, the suite of the else clause is executed
break
terminates the loop without executing the else clause's suite
continue
skips the rest of the suite and goes back to testing the expression

Example

#!/usr/bin/env python3

amount = 3000  # initial investment in euro
GOAL = 4000
INTEREST = 0.03  # 3%

years = 0
while amount < GOAL:
    years += 1
    amount = amount * (1 + INTEREST)

print(f"you'll reach your investment goal after {years} years")

Visualize execution

Python 3 Video Tutorial - While Loops

In-Class Example

  • Guessing game
    • Ask the user to input a guess
    • Compare the input with a "random number"
    • Inform the user if the number was correct
  • Enhanced game with feedback
  • Are we there?
  • Initial "release" of guessing game
    • Allow multiple guesses
    • Random integers
    • What is a random number? What about 7 or 17? :)

Summary

  • Commands "do", branches "decide" and loops "repeat" things
  • Assignment stores a value in a named container (variable)
  • if/ else branches
  • while loops
  • =, ==, !=, > operators (assignment and comparison)
  • Indentation matters
  • Built-in functions (BIFs)
    • print(.), input(.), int(.)
  • Standard library functions
    • random.randint(.)

Questions
and feedback...

Literature

Python Software Foundation Python Documentation http://docs.python.org/3/