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

What's in a program

If we make an analogy with a natural language:
Bulgarian Python
novel <=> program
paragraph <=> block
sentences <=> instructions
types of sentences (declarative, imperative,...) <=> types of instructions (statements, expressions)
grammar rules (can be ambiguous) <=> grammar rules (could not be ambiguous)

What's in a Python program

A program consists of set of instructions, which are executed by the computer.
In Python, we write each instruction on a new line.
Instructions which performs one task are separated as a block.
In Python the block is not separated by braces, as in other programming languages, but by same indentation of the instructions in it.

Data Types?

Programming is about manipulating data
Each programming language defines its data types and the corresponding operations which can be performed on each data type.
In Python, each data type literal is represented internally as object

Number data Type

In Python we can use integer, floating point and complex numbers
Numbers are immutable data type!
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:


			>>> 42
			42
			>>> -42
			-42
		

floating point numbers

we can use positive and negative floating point numbers


			>>> 3.1234
			3.1234
			>>> -0.255
			-0.255
			>>> .44
			0.44
			>>> -.55
			-0.55
			>>>
		

arithmetic operations

Arithmetic operators @programiz.com

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

Example: arithmetic operations


				>>> 5-3
				2
				>>> 5*3
				15
				>>> 5/3
				1.6666666666666667
				>>> 5//3
				1
				>>> 5%3
				2
		

Example: python3 vs python2 division


			>>> 5/3
			1
		

			>>> 5/3
			1.6666666666666667

			>>> 5//3
			1
		

Python3 adds the "//" operator for Integer division

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
				# do something with math
			

Example: math functions


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

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
Multi-line strings literal should be closed in triple single or double quotes

Examples


			>>> "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 spred in multiple lines
		  File "", line 1
		    'but can not be spred in multiple lines
		                                         ^
			SyntaxError: EOL while scanning string literal
		

Examples


			>>> """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

concatenation: +

The operation is defined only on same data types, I.e. 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:
			>>> "iva".capitalize()
			'Iva'
		

What a method is will be discussed further!

For now, you can try to look at the docs: String Methods @docs.python.org

Variables

What are they?

A names for "containers" (placed in RAM) in which values can be stored
We can set values in a variable, i.e. to write a value into the corresponding container.
We can get the variable value, i.e. to read the content of the corresponding container

example


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

			print("x = ", x,)
			print("y = ", y)
			print("first_name = ", first_name)
			print("sur_name = ", sur_name)
			print("num_list = ", num_list)
		

A very simplified view of variables in RAM

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

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 problem

Given that:
An astronomical hour consists of 60 minutes
An academical hour consists of 40 minutes
For each 4 academical hours there are 20 minutes brake
Write a Python program, that will print out how many astronomical hours a python course should take, if it consists of 64 academical hours, including the respective brakes

			48.0
		

solution - without variables


			"""
			acad_to_astro_hours.py

			Solution without using variables to store values
			"""

			print((64*40 + 64/4*20)/60)
		

solution: too many variables


			"""
			acad_to_astro_hours_with_vars.py

			An example of too many variables, with too long names.
			"""

			# given:
			minutes_in_astro_hour = 60
			minutes_in_acad_hour = 40
			acad_course_hours = 64
			acad_hours_in_a_partida = 4

			# program logic:
			acad_hours_partidas = acad_course_hours/acad_hours_in_a_partida

			total_minutes_brakes = acad_hours_partidas * 20

			minutes_in_a_course = acad_course_hours * minutes_in_acad_hour + total_minutes_brakes

			course_in_astro_hours = minutes_in_a_course / 60

			print(course_in_astro_hours)




		

HW:acad_to_astro_hours

Write your solution, using your logic and your variables names.
Try to think of a solution, which will be readable enough (# you can use comments) and easy to maintain in future
write your code in a file, named <prefix>_acad_to_astro_hours.py
where <prefix> is your name initials
For instance: iep_acad_to_astro_hours.py
send it to progressbg.python.course@gmail.com

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 rounded result (to 2 digits from the decimal point). 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
			

BMI Categories

What is your BMI category?

BMICategory
<= 18.5Underweight
18.5–24.9Normal
25–29.9Overweight
>= 30Obesity

solution


			"""
			Solution without using variables to store values,

			and given that W = 53, H = 1.67:
			"""
			print(round(53/(1.67*1.67), 2))

			# 19.0

		

HW: BMI.py

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 a file, named <prefix>_BMI.py
where <prefix> is your name initials
For instance: iep_BMI.py
send it to progressbg.python.course@gmail.com

These slides are based on

customised version of

Hakimel's reveal.js

framework