{Notes} Python development notes

Lost in Russia
10 min readJun 22, 2020

--

List of notes for learning python

Let's learn Python

This is a list of notes I´m taking as I learn how to develop in Python and I hope they will be helpful to the world.

Whats an SDK?

It is a software development kit, as the tools you need to write programs. In this case, the Python SDK includes an interpreter, that can understand Python code, and execute it, as well a debugger.

SDK can also include useful modules that can be included in your code. For Python, the modules are in the Python Standart Library.

SDK´s can be setup for different versions of Python, that will help after the program is written, to make sure it works with all the versions that you support.

Packages should be installed in other directories, not in the main Python installation as it can generate issues if it is incmpatible, for that reason a better approach is to create a Python Virtual Environment, or virtualenv. or even venv.

What is a programming paradigm

Is a way of programming and how we structure the code. Most languages combine several of them.
There are 14 common paradigms, although 5 are the most used.

Imperative: Explicit sequence of commands

result = []
i = 0
start:
numPeople = length(people)
if i >= numPeople goto finished
p = people[i]
nameLength = length(p.name)
if nameLength <= 5 goto nextOne
upperName = toUpper(p.name)
addToList(result, upperName)
nextOne:
i = i + 1
goto start
finished:
return sort(result)

Structured: Developing by commands, where control flow is defined by nested loops, conditionals and subroutines.

result = [];
for i = 0; i < length(people); i++ {
p = people[i];
if length(p.name)) > 5 {
addToList(result, toUpper(p.name));
}
}
return sort(result);

Object-Oriented: Defining objects that send messages to each other.

result := List new.
people each: [:p |
p name length greaterThan: 5 ifTrue: [result add (p name upper)]
]
result sort.
^result

Declarative programming: The developer only states what the result should look like.

select upper(name)
from people
where length(name) > 5
order by name

Functional programming: is expressed by combining function calls

sort(
fix(λf. λp.
if(equals(p, emptylist),
emptylist,
if(greater(length(name(head(p))), 5),
append(to_upper(name(head(p))), f(tail(p))),
f(tail(people)))))(people))

References: https://cs.lmu.edu/~ray/notes/paradigms/

Printing in Python

print("Hello, World!")
print(1 + 2)
print (7 * 6)
print()
print("the end", "or is it?", "keep watching to learn more about python", 3 )#### Results ####Hello, World!
3
42the end or is it? keep watching to learn more about python 3Process finished with exit code 0

Print is a function
“Hello, World!” Is a string literal.
Literal is a sequence of characters.

Single quotes or double quotes are possible to enclose the string.

Literal: a value of some type, numeric like 1, 42, 98.04, or string as “Hello, World!”. This is called as well an argument.

Function: A value passed to a function, to give it values or work with it.

Calling a function: using the function name to execute the function´s code.

Return value: Is the value that the function returns.

Process finished with exit code 0

String concatenation

Strings can be stored in variables and make concatenation.

If we define name as “bruce” after we create a variable concatenated with greeting + name (adding + ’ ‘ + so we get space between words) we will get hello Bruce as a result.

greeting = "hello"
name = "Bruce"print(greeting + ' ' + name)

When we define that greeting = “Hello” and then we created the input name as name = input (“Please enter your name”) we will have the option to introduce the name.

print("Today is a good day to learn Python")
print("Python is fun")
print("Python´s strings are easy to use")
print('We can even include "quotes" in string')
print("Hello" + " world")
greeting = "Hello"
name = input("Please enter your name ")
#if we dont add + ' ' + the name and greeting will not have space
print(greeting + name)
#if we want a space, we can add that too
print(greeting + ' ' + name)

Backslash character in python

The backslash character is used to escape the character that follows it, to give to it special meaning.
Examples: /n to start a new line or /t to insert a tab
Backslash can be used as well to escape special characters like quotes or double-quotes.

splitString = "This string has been\nsplit over\nseveral\nlines"
print(splitString)
tabbedString = "1\t2\t3\t4\t5"
print(tabbedString)#You can add \ before every ' so is escaped and used as a common text
print('The pet shop owner said "No, no, \'e\'s uh,...he\'s resting".')#You can add \ on the beginning and end (start and close) so no need to repeat it several times
print("The pet shop owner said \"No, no, 'e's uh,...he's resting\".")#You can use """ three times so the compiler you will not need to escape any quotes
print("""The pet shop owner said "No, no, 'e's uh,...he's resting". """)
anotherSplitString = """This string has been \
split over \
several \
lines"""
print(anotherSplitString)

Adding backslash as part of your text

We can add backlash to the code in two different ways, one is duplicating the \\ so python determinates that we want it, the second is using the letter “r” (raw) before the quotation marks.

print("C:\\users\\timbuchalka\\notes.txt")
print(r"C:\users\timbuchalka\notes.txt")

Variables and types in Python

A variable is a way to name an area of memory into which we can place certain values, as when a program is running needs to be stored on the computer´s memory.

When we create a variable, Python allocates an area of memory for it. That variable will have a type and limits what kind of things this variable can do.

greeting = "Hello"
name = input("please enter your name ")
print(greeting + name)

On this example, we have the variable greetings and is a type string.

Rules for variable names:

  1. Start with a letter or underscore _
  2. Can contain letters, numbers or underscore characters
  3. Can’t begin with a number
  4. They are case sensitive
  5. Variables are created when attached to =

What are the types?

Data types describe the type of information we are storing.

greeting = "Hello"
age = 24
print(type(greeting))
print(type(age))

After we write this code, asking Python what type is greeting and age, we get class

<class ‘str’>
<class ‘int’>

Class string value
Class integer value

In Python, you can rebind the same name to a different value, without getting an error message,

age = "2 years"age = 24
print(age)
print(type(greeting))
print(type(age))
age = "2 years"
print(age)
print(type(age))

What is printed from it:

24
<class 'str'>
<class 'int'>
2 years
<class 'str'>Process finished with exit code 0

Numeric data types in Python

Python has several built-in data types that can be classed as:

  • Numeric:
    Integer (int) — they are whole numbers without a fractional part. Computations using int are significantly faster than using floating-point numbers. This has no limit to the size of the value.
    Floating points (float) — is another name for real numbers, having a fractional part after the decimal point. The size limit for float goes 97.98, 32.3+e18 and the minimum is -32.54e100.
    complex
  • Iterator
  • Sequence (they are also iterators)
  • Mapping
  • File
  • Class
  • Exception

Even using int values, divisions produce float results

a = 12
b = 3
print(a + b) # 15
print(a - b) # 9
print(a * b) # 36
print(a / b) # 4.0
print(a // b) # 4 integer division, rounded down towards minus infinity
print(a % b) # 0 modulo. the remainder after integer division## Results ##
15
9
36
4.0
4
0Process finished with exit code 0

But when we want to do some other codes, even when the int value prints float we will get a bug:

print()
for i in range(1, a / b):
print(i)

This will give an error as

for i in range(1, a / b):
TypeError: 'float' object cannot be interpreted as an integer

We can avoid the error by using double slash // as then we will get float object interpreted as float, not as int:

print()
for i in range(1, a // b):
print(i)## Results ##
1
2
3Process finished with exit code 0

Indexing and Slicing in Python

On Python, you can choose individual characters of substrings. The square brackets will access to individual “something”.

The character N is in position 0 and the “e” in blue is in position 13
You can as well do negative indexing, in that case, we will count from the last character. So -1 will be “e”
You can as well choose slices to “cut” a section of the str, where the last number is not included [0:4], that means that 0, 1, 2 and 3 will be included, excluding 4.
When adding 3 different options as [0:6:2] this will slice between 0–6 not including 6 but just every two characters. Can be used in negative as well.

#                   1
# 012345678901234
parrot = "Norwegian Blue"
print(parrot)print(parrot[3]) # this is "r"
print(parrot[4]) # this is "e" from Norwegian
print(parrot[-1]) # this is "e" from blue
print(parrot[0:4]) # this is Norw (not including the 4th)
print(parrot[0:6:2]) # Nre

This can be used to separate values giving you the result of “[9, 223, 372, 36, 854, 775, 807]” so if you have a list of values, one of the uses is to print the data in the right way.

number = "9,223;372:036 854,775;807"
separators = number[1::4]
print(separators)
values = "".join(char if char not in separators else " " for char in number).split()
print([int(val) for val in values])

Python sequence types

A sequence is defined as an ordered set of items.
For example, the string “Hello world” contains 11 items, and each item is a character.
A list is also a sequence type, for example [“computer”, “monitor”, “keyboard”, “mouse”]. This list contains 4 items each of them a string.

Because a sequence is ordered, we can use indexes to access individual items in a sequence.

Python has 5 sequence types build in:

  • The string type
  • List
  • Tuple
  • Range
  • Bytes and Byterray

String replacement fields in Python

When printing string and numbers you can display a single call to print.
Numbers can´t be concatenated with string using +, as the presence of a number instructs Python to attempt addition and it fails.

One approach is to coerce our numbers with the str function.

Age = 24
print("My age is " + str(age) " Years")

There is a faster way to do this avoiding writing str function every time and is using string replacement fields

Example:

age = 24
print("My age is {0} years".format(age))
print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6}, {7}"
.format(31, "Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec" ))
print("There are {0} days in Jan, Mar, May, Jul, Aug, Oct and Dec".format(31))
print("Jan: {2}, Feb: {0}, Mar: {2}, Apr: {1}, May: {2}, Jun: {1}, Jul {2}, Sep: {1}, Oct: {2}, Nov: {1}, Dec: {1}".format(28,30,31))
print()print("""Jan: {2}
Feb: {0}
Mar: {2}
Apr: {1}
May: {2}
Jun: {1}
Jul: {2}
Sep: {1}
Oct: {2}
Nov: {1}
Dec: {1}""".format(29, 30, 31))### Result ###My age is 24 years
There are 31 days in Jan, Mar, May, Jul, Aug, Oct, Dec
There are 31 days in Jan, Mar, May, Jul, Aug, Oct and Dec
Jan: 31, Feb: 28, Mar: 31, Apr: 30, May: 31, Jun: 30, Jul 31, Sep: 30, Oct: 31, Nov: 30, Dec: 30Jan: 31
Feb: 29
Mar: 31
Apr: 30
May: 31
Jun: 30
Jul: 31
Sep: 30
Oct: 31
Nov: 30
Dec: 30Process finished with exit code 0

We can as well make formating in Python by adding the spacing on it, where after “:x” we will get a format so all the data is organised in columns.

for i in range (1, 13):
print("No. {0:2} squared is {1:4} and cubed is {2:4}".format(i, i ** 2, i ** 3) )### Result ###No. 1 squared is 1 and cubed is 1
No. 2 squared is 4 and cubed is 8
No. 3 squared is 9 and cubed is 27
No. 4 squared is 16 and cubed is 64
No. 5 squared is 25 and cubed is 125
No. 6 squared is 36 and cubed is 216
No. 7 squared is 49 and cubed is 343
No. 8 squared is 64 and cubed is 512
No. 9 squared is 81 and cubed is 729
No. 10 squared is 100 and cubed is 1000
No. 11 squared is 121 and cubed is 1331
No. 12 squared is 144 and cubed is 1728##################################################################for i in range (1, 13):
print("No. {0:2} squared is {1:<3} and cubed is {2:<4}".format(i, i ** 2, i ** 3) )### Result ###No. 1 squared is 1 and cubed is 1
No. 2 squared is 4 and cubed is 8
No. 3 squared is 9 and cubed is 27
No. 4 squared is 16 and cubed is 64
No. 5 squared is 25 and cubed is 125
No. 6 squared is 36 and cubed is 216
No. 7 squared is 49 and cubed is 343
No. 8 squared is 64 and cubed is 512
No. 9 squared is 81 and cubed is 729
No. 10 squared is 100 and cubed is 1000
No. 11 squared is 121 and cubed is 1331
No. 12 squared is 144 and cubed is 1728##################################################################for i in range (1, 13):
print("No. {0:2} squared is {1:^3} and cubed is {2:4}".format(i, i ** 2, i ** 3) )### Result ###No. 1 squared is 1 and cubed is 1
No. 2 squared is 4 and cubed is 8
No. 3 squared is 9 and cubed is 27
No. 4 squared is 16 and cubed is 64
No. 5 squared is 25 and cubed is 125
No. 6 squared is 36 and cubed is 216
No. 7 squared is 49 and cubed is 343
No. 8 squared is 64 and cubed is 512
No. 9 squared is 81 and cubed is 729
No. 10 squared is 100 and cubed is 1000
No. 11 squared is 121 and cubed is 1331
No. 12 squared is 144 and cubed is 1728##################################################################print("Pi is approximatelly {0:12}".format(22 / 7)) # General format
print("Pi is approximatelly {0:12f}".format(22 / 7)) # With F (floating format) we get 6 digits after
print("Pi is approximatelly {0:12.50f}".format(22 / 7)) # floating point format with a precision of .50 precision
print("Pi is approximatelly {0:52.50f}".format(22 / 7))
print("Pi is approximatelly {0:62.50f}".format(22 / 7))
print("Pi is approximatelly {0:72.50f}".format(22 / 7))### Result ###

--

--

Lost in Russia
Lost in Russia

No responses yet