Powercoders

Introduction to the Python Language

Agenda

  • Introduction: Why, What and Where?
  • REPL and the Debugger
  • Syntax
    • Structure
    • Variables
    • Types
    • Operators
    • Flow Control
    • Functions

Learning objectives

  • Get an idea of what Python is
  • Get an idea of when to use Python

Resources and Material

Why use Python?

  • Simple
    • Lean Syntax
    • Readability (PEP8 )
  • Flexibility
    • procedural, object-oriented, functional
    • Interpreter, Just-in-time Compiler, Cython, Jython
  • Spread
    • Free and Open Source
    • For all OSs
    • Extensive libraries and modules
    • Big Community
  • Relevance: Data Science, Machine Learning

But really: Why use Python?

  • Extensive libraries and modules: pypi.org
  • Big Community

There is nearly every problem already solved and every question already asked!

What is Python?

  • General purpose programming language
  • Dynamically typed (like JavaScript)
  • Interpreted (like JavaScript)
  • Not one of that "curly-braces" languages (unlike JavaScript)
def main():
    print('Hello, world!')

main()

Where is Python used?

  • Data Science and Machine Learning
  • Webservers (Backend)
  • Shell scripts and tools
  • etc.

Read-eval-print loop (REPR) and the Debugger

Replit

Showcases

Replit

Syntax

Structure

  • One line per instruction
    sum = a + b + c
    sum = (
        a
        + b
        + c
    )
  • Blocks by indenting with 4 spaces
    def abs_diff(a, b):
        if a > b:
            return  a - b
        return b - a

Comments

  • Comments start with a #
    c = a + b  # I'm a comment
  • No block comments
    # There are
    # no block
    # comments
    

Variables

  • Variables are defined using a =, no keyword needed.
  • Names can contain _, numbers and UTF-8 letters, but no number at the start!
  • Upper and lower case matters.
  • Convention: snake_case.
    my_variable = 1  # valid
    π = 3.14         # valid
    2_chars = 'ab'   # not valid
    
  • Unpacking
    a, b = 1, 2

Types

Types

Type Description Example
NoneType Not a value None
bool Boolean True, False
int Integer 10
float Floating Point number 10.0
complex Complex number 1+1j
object Object object()

Types

Type Description Example
str String 'Hi!'
tuple Unmutable list (1, 2)
list Mutable list [1, 2]
set Set {1, 2}
dict Dictionary {1: 2}

More on Strings

  • Strings can be defined with ' or with "
    a = 'Hello'
    b = "World"
  • Both versions can be used within each other
    a = "'Hello'"
    b = '"World"'
  • Multi-line strings can be defined with three quotation marks (typically used for documentation)
    a = """I am a string
    that spans over
    multiple lines
    """
    

More on Lists and Tuples

  • They can contain arbitrary items
    [1, 'a', None]
  • They can be nested
    (1, [2, 3])
  • They can be converted
    list((1, 2))
    tuple([1, 2])
    

More on Sets and Dictionary

  • Both use {} ← this is an empty dict!
    set()  # this an empty set
  • Dicts can be nested, sets not
    {1: {1, 2}}
  • Dict keys and set items can be anything ...
    {1: 1, '2': '2', 3.0: 3.0}
  • ... but need to be hashable
    hash(dict())

Indexing Lists and Tuples

  • Access a subset of the items with []
  • Access one item with one index
    'Hello'[0]
  • Access a slice with a range from:to (to is not included)
    'Hello'[1:3]
  • Ranges can be empty (everything until) or negative (from the right)
    'Hello'[2:]
    'Hello'[:2]
    'Hello'[-2:]
    'Hello'[:-2]

Indexing Dictionaries and Sets

  • Access a dictionary item with []
    a = {1: 'a'}
    a[1]  # 'a'
    
  • Sets are not ordered and can not be indexed.
  • You could convert them to a tuple or list
    a = {1, 2}
    tuple(a)[0]
    

Indexing

Replit

Operators

Logical Operators

Operator Description Example
and logical AND True and False # False
or logical OR True or False # True
not logical NOT not True # False
^ logical XOR True ^ True # False

What evaluates to not? (5')

Replit

Mathematical Operators

Operator Description Example
+ Addition / Add strings 1 + 2.0 # 2.0
- Subtraction 1 - 2.0 # -1.0
* Multiplication 1 * 2.0 # 2.0
/ Division 1 / 2 # 0.5
// Integer division 1 // 2 # 0
% Modulo 1 % 2 # 1
** Power 2 ** 3 # 8

Comparison Operators

Operator Description Example
is Equal (bool, None) None is True # False
== Equal (everything else) 1 == 2 # False
is not Not equal (bool, None) False is not None # True
!= Not equal (everything else) 1 != 2 # True
< Less than 1 < 2 # True
Less or equal than 1 <= 2 # True
> Greater than 2 > 3 # False
Greater or equal than 2 >= 3 # False
in Contains 1 in [] # False

Python as a Calculator (5')

Replit

  • 10 ÷ ( 3.44 x ( 2.34 - 2.2 ÷ 4 ) ) = 1.624
  • 27 - 1 = 127
  • (12300.88 modulo 8003.35) 2 = 18468764.1
  • √ 2 = 1.41

Flow Control

if

  • if: conditional block
  • elif: additional conditional block(s)
  • else: if no condition met
  • No brackets around the condition needed
    if x > 0:
        do_somethig()
    elif x < -10:
        do_something_else()
    elif x < 0:
        do_yet_something_else()
    else:
        fall_back()
    

while

  • while: run while the condition is met
  • break: stop the while loop
  • continue: skip the rest of block
  • else: in case no break occured
    while x > a:
        x = x - b
        if x < a:
            break
        if x < c:
            continue
        x = x - d
    else:
        print('no break!')
    

for

  • for: iterate over all items
  • break: stop the while loop
  • continue: skip rest of block
  • else: in case no break occured
    for x in (1, 2, 3, 4):
        if x > 2:
            continue
        if x < 3:
            break
    else:
        print('no break!')
    
  • "for-able": sets, dict keys, lists, tuples, strings, ...

Functions

Functions

  • Define functions using the def keyword
  • Functions can return (something). If not, None is returned
  • Arguments can have a default value (=)
  • Arguments can be positional or by keyword
    def sum(a, b, c=0, d=0):
        return a + b + c + d
    
    sum(1, 2)
    sum(1, 2, 3)
    sum(a=1, b=2, c=3)
    sum(1, 2, d=4)
    

Built-in Functions

Countdowns (15')

How can you print a countdown (10 to 0)?

Replit

Importing

String formatting

  • How to embed variables in strings?
  • f-strings can contain expressions within {}
    name = 'World'
    f'Hello, {name}'  # 'Hello, World'
    
  • Expressions can have formatting options
    result = 1.23345
    f'The result is {result:.2f}'  # 'The result is 1.23'
    
  • Expressions can be expressions
    a = 5
    b = 6
    f'{a} * {b} is {a*b}'  # '5 * 6 is 30'
    

Exercise 1

Create a random password generator. The password has to have a length of at least 8 characters, at least 1 digit and 1 special char (_ or -).

Exercise 2

Validate a telephone number, as if written on an input form. Telephone numbers can be written as ten digits, or with dashes, spaces, or dots between the three segments, or with the area code parenthesized; both the area code and any white space between segments are optional.

Exercise 3

Create a program that prompts for a quote and an author. Display the quotation and author as shown here:
[Author] says, "[Quote]" (Replace [Author] and [Quote] with the actual values.

You might want to use quotes.rest and requests.

Exercise 4

Create a program that prompts for ingredients. Display possible food recipes.