Strings and Numbers in Python.
Simple Expressions. Variables. Comments.

Python design philosophy and syntax

Python design philosophy and syntax

The Zen of Python


            $ python -m this
            The Zen of Python, by Tim Peters

            Beautiful is better than ugly.
            Explicit is better than implicit.
            Simple is better than complex.
            Complex is better than complicated.
            Flat is better than nested.
            Sparse is better than dense.
            Readability counts.
            Special cases aren't special enough to break the rules.
            Although practicality beats purity.
            Errors should never pass silently.
            Unless explicitly silenced.
            In the face of ambiguity, refuse the temptation to guess.
            There should be one-- and preferably only one --obvious way to do it.
            Although that way may not be obvious at first unless you're Dutch.
            Now is better than never.
            Although never is often better than *right* now.
            If the implementation is hard to explain, it's a bad idea.
            If the implementation is easy to explain, it may be a good idea.
            Namespaces are one honking great idea -- let's do more of those!
        

Clean syntax

Statements are terminated by EOL ("End Of Line symbol"), not by semicolons
Though, you can use semicolons if you wish
Block of statements is wrapped by the same indentation, not by curly braces
You can use spaces or tabs for indent.
Mixing spaces with tabs can lead to errors or bugs.

Python syntax vs JavaScript syntax demo

Both programs deal with same task: to find the sum and product of array

            numbers = [1, 2, 3, 4]
            product = 1

            for i in numbers:
                product *= i

            total = sum(numbers)
            print(total, product)
        

            const numbers = [1, 2, 3, 4];
            let product = 1;
            let total = 0;

            for (let i of numbers) {
                product *= i;
                total += i;
            }

            console.log(total, product);
        
Other examples for comparing Python vs other languages you can find: rosettacode.org

Do not mix space and tabs

That code will lead to

TabError: inconsistent use of tabs and spaces in indentation

Same indent!

That code will lead to

IndentationError: unexpected indent

Wrong indentation can cause bugs!

Can you spot the bug?

Data Types Introduction

Data Types Introduction

Programming is about manipulating data
Each programming language defines its data types and the corresponding operations which can be performed on each data type.

			print( 1 + 2 ) # 3
			print( '1' + '2' ) # 12
			print( True + True ) # 2
			print( 3 * 4 ) # 12
			print( 3 * '4' ) # 444
		
In Python, each data type literal is represented internally as object

Numeric Data Types

Numeric Data Types

In Python we can use integer, floating point and complex numbers
Numbers are immutable data types! That is, they cannot be changed after they are created.
Most arithmetic operations are natively defined in Python.
More complex math functions are defined in the math module

integer numbers

we can use positive and negative integers:


            # positive integer literal:
            >>> 42
            42

            >>> +42
            42

            # negative integer literal:
            >>> -42
            -42
        

floating point numbers

we can use positive and negative floating point numbers


            >>> 3.1234
            3.1234

            >>> -0.255
            -0.255

            # leading zero can be skipped:
            >>> .44
            0.44
            >>> -.55
            -0.55
            >>>
        

Underscores in Numeric Literals

As of Python 3.6 you can use underscores in numeric literals to improve readability of long numbers

                >>> 1_000_000 + 2_000_000
                3000000
            

arithmetic operations

Python supports the standard arithmetic operations:

                >>> 5-3
                2
                >>> 5*3
                15
                >>> 5/3
                1.6666666666666667
                >>> 5//3
                1
                >>> 5%3
                2
            
Reference: Numeric Types@python docs

python3 vs python2 division

The division operator "/" in python2 returns the integer part(i.e. works like Floor division), while in python3 it returns the float result

            >>> 5/3
            1
        

            >>> 5/3
            1.6666666666666667

            >>> 5//3
            1
        

Floating Point Arithmetic: Issues and Limitations

Decimal numbers are represented in binary system.
Most decimal fractions cannot be represented exactly as binary fractions, which leads to peculiar results
Reference: Floating Point Arithmetic: Issues and Limitations @python.org

            print(0.1+0.2)

            # OUTPUT:
            # 0.30000000000000004
        

the math module

math module is native to every python distribution.
to use its functions you only have to import it in your program:

                import math

                # Example: Calculate square root of a number
                number = 16
                sqrt_value = math.sqrt(number)

                print("Square root of", number, "is", sqrt_value)
            
math — Mathematical functions @python docs

Built-in math functions

Python interpreter has a number of built-in functions which can be used without any imports.
Part of them, concerning Math are: abs(), max(), min(), round()

Example: math module methods


            >>> import math
            >>>
            >>> math.pi
            3.141592653589793
            >>> math.floor(math.pi)
            3
            >>> math.pow(2,3)
            8.0
            >>> math.sqrt(9)
            3.0
            >>> math.ceil(2.9)
            3
            >>> math.ceil(2.1)
            3
            >>> math.floor(2.9)
            2
            >>> math.floor(2.1)

        

Example: math built-in functions


            >>> round(2.51)
            3
            >>> round(2.49)
            2
            >>> max(1,2,3)
            3
            >>> min(1,2,3)
            1
            >>> abs(2-5)
            3

        

Strings in Python

Strings in Python

definition

Strings are immutable sequences of Unicode code points (will be discussed further).
Single-line strings literal should be closed in single or double quotes
No difference between single or double quoted strings!
Multi-line strings literal should be closed in triple single or double quotes

                >>> "this is a single line string"
                'this is a single line string'

                >>> 'another single line string with UTF charactes like 🍷'
                'another single line string with UTF charactes like 🍷'

                >>> 'but can not be spread  in multiple lines
              File "<stdin>", line 1
                'but can not be spred in multiple lines
                                                     ^
                SyntaxError: EOL while scanning string literal

                >>> """infact you can -
                ... if you use these triple quotes"""
                'infact you can - \nif you use these triple quotes'

                >>> '''or these triple quotes
                ... can separate multiline without errors'''
                'or these triple quotes\ncan separate multiline without errors'
            

Strings operations

Strings operations

concatenation: +

The operation is defined only when both operands are string.
Python can not concatenate "apples with oranges":


            #string concatenation with '+':
            >>> "ala" + "bala"
            'alabala

            >>> "1" + "2"
            '12'

            >>> "1" + 3
            Traceback ...
            TypeError: cannot concatenate 'str' and 'int' objects
        

repetition: *

One of the operands must be string, the other - integer


            >>> "-" * 10
            '----------'

            >>> "1" * 10
            '1111111111'

            >>> ">hello<" * 3
            '>hello<>hello<>hello<'

            >>> "a" * "3"
            Traceback ...
            TypeError: can't multiply sequence by non-int of type 'str'
        

String Methods


            # string methods:
            >>> "ada".capitalize()
            'Ada'
            >>> "alabala".count("a")
            4
            >>> "Alabala".count("a")
            3
            >>> "AlabAla".find("a")
            2
            >>> "alabala".replace("a", "o")
            'olobolo'
            >>> "one,two,three".split(",")
            ['one', 'two', 'three']
        

What a method is will be discussed further!

Reference: String Methods @docs.python.org

Variables/Value Names

Variables in Python

What is a variable in Python?

A name (identifier) for a "container" (located in RAM) in which values can be stored and retrieved.
When we say that we set value in a variable, it should be understood as to write a value into the corresponding container.
We can get the variable value, i.e. to read the content of the corresponding container
In Python, we speak of name binding when we assign a value to a variable.
Name binding in Python refers to the process of associating a variable name (an identifier) with a value or object in memory. When you assign a value to a variable, you are "binding" that name to the object.

A very simplified view of variables and RAM


            x = 99
            y = 3.141516
            first_name = "ada"
            sur_name = "byron"
            num_list = [1,2,3,4,5]
        

Variables (Identifiers) rules

Variables names should follow next rules:
Start with letter or underscore
Followed by zero or more letters, underscores and digits
Variable names are case-sensitive

            x = 99
            print("x = ", x)

            first_name = "ada"
            print("first_name = ", first_name)

            print("first_name = ", First_name) #NameError: name 'First_name' is not defined

            sur-name = "byron" #SyntaxError: can't assign to operator

        

Naming Conventions

Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Variable names follow the same convention as function names.
mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.
PEP 8 (Function and Variable Names)

Assignment Statement

An assignment statement in Python assigns a value to a variable. The basic syntax is:

                variable = expression
            
First expression is evaluated, and then its result is assigned to variable.
Variations:

                ### Multiple Assignments
                x, y = 10, 20 	# x=10 and y=20.

                ### Chain Assignment:
                x = y = 10      # x = 10 and y = 10

                ### Shorthand Assignment with Operators:
                x += 10  	# Equivalent to x = x + 10
                x **= 10  	# Equivalent to x = x ** 10

            

Name binding

Name binding is the association between a name and an a value
Note, that all values in Python are represented as objects
We can bind a value to a name with the assignment statement (=)
We can check the unique identity of an object by the id() built-in function.
CPython uses the object's memory address for the unique id

                a = 2
                print(id(a))

                # 9413216
            

Name binding

Garbage collection

Garbage Collection is a process of reclaiming the unused runtime memory automatically.

            a = 5
            print(id(a))
            # 9413312

            # Now we create a new object, and bind it to 'a'
            a = 6
            print(id(a))
            # 9413344

            # the object [id:9413312, value:5] will be deleted by the garbage collector, as nothing points to it
        

Comments

Comments

Why to comment our code?

Python interpreter ignores every part of a program, which is marked as a "comment"
Comments are used to explain and/or summarize a part of our program in a more readable manner
For debugging purposes - when we need fast to ignore a block of code
For other meta information about the program (programme name, author, date, etc.)
A well commented program is more readable and maintainable.
Reference: PEP8 - Comments

How to comment our code?

Single line comment: #
every line which starts with #(hash tag) is a comment and is ignored py Python interpreter

                # this is a just a comment: no print("whatever") will happens
                print("this will be printed, of course")

                ### a more semantic example for comment:
                # check if a triangle with sides (3,4,5) is a Pythagorean:
                print(3**2 + 4**2 == 5**2)
            

Exercises

Academical to Astronomical hours converter

The task

Task:
Write a Python program that calculates the total duration (in astronomical hours) of a Python course consisting of 64 academical hours, including the respective breaks.
Given:
1 astronomical hour = 60 minutes
1 academical hour = 40 minutes
The course is structured in sessions, where:
  • Each session consists of 4 academical hours
  • Each session includes a 20-minute break
Expected Output

                Total duration in astronomical hours: 48.00
            
Requirements:
Your solution should be readable and easy to maintain.
Write your code in: HW/acad_to_astro_hours.py.

Body Mass Index calculator

The problem

Calculate your body mass index (BMI) with Python, given the formula:
BMI = W / (H*H)
where:
W = weight_in_kilogram
H = height_in_meters
Your program should outputs the result rounded to 2 digits after the decimal point).
Try to think of a solution, which will be readable enough and easy to maintain in future (you can use comments and semantic variable names)
write your code in HW/BMI.py file

Tip: You can use the python's build-in round() function, like:

                >>> round(2.1457, 2)
                2.15

                >>> round(1.4234,2)
                1.42

                >>> round(1.4284,2)
                1.43
            

HW Submition

You can submit your files either by:
upload to your Github account.
Or sending as email attachment to course mail.

These slides are based on

customised version of

Hakimel's reveal.js

framework