Part 3 - Python For Research
Part 3 - Python For Research
Dynamic Typing
Computer's memory → sequence of zeroes and ones (instead of strings or numbers or dictionaries).
- Move data from one variable to another or if the types of these variables
do not match→ potentially lose information.
- Program expects a floating-point number, but you provide an integer→ no problem; integers are a
subset of floating point numbers.
- Program expects an integer, and you provide it with a floating point number→ some information is lost.
Typing or assigning data types → set of rules that the language uses to ensure that the part
of the program receiving the data knows how to correctly interpret that data.
Languages Statically typed (type checking is performed during compile time) → C or C++
Languages Dynamically typed (type checking is performed at run time) → Python.
Example:
Tell Python x = 3, how does Python know that x should stand for an integer? 3 important concepts (variable,
object, and reference.
Variable names and objects are stored in different parts of computer's memory. It will always link to objects,
never to other variables.
Variable → a reference to the given object (a name is possibly one out of many attached to that object).
OJO: When assigning objects → mutable objects (lists and dictionaries) can be modified at any point of
program execution while immutable objects (numbers and strings) cannot be altered after they've been created
in the program.
1. x→ 3
- Creates the object (3), then it creates the variable name (x)
- Inserts reference from the variable → name to the object .
2. y = x
- Creates object (x) which is 3 that already exists.
- Creates a new variable (y) and reference to the object (x)
OJO: a variable cannot reference another variable, only reference an object.
3. y = y - 1
- Python first looks at the object here (y), which is our number 3.
- As numbers are immutable, a new object has to be created → number 2.
- Variable name y is in our computer's memory, so it removes this reference and inserts a reference from y
to the object 2.
Dynamic typing for mutable objects → looks different, but it follows the same logic as for
immutable objects.
1. L1 = [ 2, 3, 4]
- Creates the object→ list 2, 3, 4.
- Creates the variable name L1.
- Variable (L1) will reference this object (list ).
3. L1 [0] =24.
- L1 to reference this object
- Modifying the content of the number at location 0 from 2 to 24.
- Changes the content of the list is going to be 24, 3, and 4.
First impression→ have two lists, L1 and L2, and only list L1 gets modified.
Dynamic typing works in Python, we only have two names that reference the same object.
The last line, L1 [0] = 24 would have been identical to L2 [0] = 24.
Each object → type, value, and an identity. Mutable objects can be identical in content and be different
objects.
Is L equal to M?
M is equal to L→ M = L [ : ]
M is L → I get a false.
2. Copies
For complex structures → Copy module, you can use for creating identical copies of object.
2 types available:
1. Shallow copy → constructs a new compound object and then insert its references into it to the
original object.
2. Deep copy → constructs a new compound object and then recursively inserts copies into it of the
original objects.
2. Deep copy → create a copy of x (X’’) and create copies own objects
(a’’) and (b’’)
Into my new copy of x → insert references to the
copies of a and b.
3. Statements
No hard and fast rules about indentation as long as you are consistent (tab or using four spaces).
Example:
→ Lock of code.
If true, then Python will:.
- Calculating the difference as x minus y.
- Printing out the message, x is greater than y.
- Line 4 will always get printed.
Most programming languages, indentation is not compulsory. In Python, indentation determines the logical
structure of your programs.
A. If statement :
Selects from among one or more actions, and it runs the block of code associated with
the first if or elif test that happens to be
true. If False → runs the else block.
Example:
If it turns out that x> y on line 1, the other conditions will not even be evaluated.
OJO: Python goes through different conditions (if and elif) until first True statement. If all else fails, then
execute the else statement.
Calculate absolute values, you could use the built-in abs function.
A sequence iteration that assigns items in sequence to target one at a time and runs the block of code for
each item. Unless the loop has a break statement → the block of code is run as many times
as the items in the sequence.
1. Target points to the object at location 0 and runs the block of code
connected with the for compound statement.
2. Target will point to position 1 and so on.
3. At the very end of the loop, target will be pointing to the very last
object in that sequence and then run the block of code.
Just print out the number so I'll just simply type print(x).
And Python loops over the range sequence and prints out the numbers one at a time.
Python goes over my list of names and prints them out one at a time.
Another language (not Python) → use an index to get out the different names from your
list.
Dictionary age → keys are names and values are the ages.
Use a For Loop to iterate over the key value pairs in a dictionary.
OJO: by typing "age.keys ( )", I get a dictionary view object (dynamic view
of all of the keys)
Shorthand way
OJO: In dictionary a given key always goes with the associated object. But the key value pairs themselves don't
follow any particular ordering.
While Loop → used for repeated execution of code as long as a given expression is true (repeatedly
tests the expression).
Sometimes there is some confusion about when to use a For Loop and when to use a While Loop.
- While Loop → you're testing some condition some number of times. You don't know
how many times you'll be running through that loop.
- For Loops → where when beginning the loop, you know exactly how many times you would like
to run through the block of code.
5. List Comprehension
To take an existing list, apply some operation to all of the items on the list, and then create a new list with the
results.
Computing squares of a list of numbers.
List call "squares", as an empty list.
For Loop go over each of my numbers, square it, and append the result to my
squares list.
- For number in numbers, my square = to my number squared.
- Append my squared number to the squares list
"squares.append(square)".
List comprehensions.
Using square brackets → [ ]
- Already given a number stored in a variable "number".
- Square that number, and it becomes an item in my list.
- "for number in numbers" → comprehension.
Returns a string. So train a new string function at the end of the line→
line.rstrip().split(“ _ ”).
Writing method
write( ) of the file object, called F → "F.write( )" and provide the string to
write to my text file.
- Write the word "Python"→ The input as a string, in this case
"Python."
- Have to add an extra character→ “ \n”
- When done with writing, close the file object → "F.close()"
7. Function
Devices for grouping statements so that they can be easily run more than once in a program. They maximize
code reuse and minimize code redundancy and enable dividing larger tasks into smaller chunks, an approach
that is called procedural decomposition.
- First def keyword add function and take two input arguments→ add (a, b).
- Calculate a sum by saying→ mysum = a+b
- Return statement to return mysum to the caller of the function.
Examples:
All names created or assigned in a function are local of that function and they exist only while the function runs.
To modify the value of a global variable from inside a function, you can use the global statement.
OJO: Functions do not exist until Python reaches and runs the def statement. Not executed until is called using
the name followed by parentheses syntax.
The def statement → creates an object and assigns it to a name. You can reassign the function object to
another name.
Defined a function add.
Mutable object.
OJO: Functions with more than two or three lines are just easier in the
editor mode.
If I ask for a longer password, perhaps one with 10 characters, the code appears to be working correctly.
And you can see that Python is now randomly choosing characters from the
entire set of alphabets.
In this case, Python is including both characters (letters and numbers) in our password.
Really secure, generate a much longer password.
OJO: In a dictionary, a given key object is always coupled with its value object, but the key value pairs
themselves can appear in any order inside the dictionary.
Make sure you know the type of the object so you know the methods that the object
supports.
When accessing dictionaries, make sure you know the type of your key objects.
I cannot do is try to modify the content of the zeroth element. String object
does not support item assignment.
The fundamental problem here is strings are immutable objects so their content cannot be modified.
Therefore, make sure that you always know the type of your objects.
G. Indentation
Simple function → calculating the running sum up to n.
Take my running sum and add the value of k to that sum. Return the result to the
caller.
Instead of completing the for loop, we return rsum some during the first iteration.
The way to fix the problem is the following.