Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

1.

Dynamic Typing

What does a type mean the context of a computer?

Computer's memory → sequence of zeroes and ones (instead of strings or numbers or dictionaries).

How should a program interpret these sequences of zeros and ones?

1. It tells a program, you should be reading these sequences in chunks of 32 bits.


2. It tells the computer is what this number ( sequence of bits) represent (a floating-point number, or a
character, or a piece of music, or else).

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

When you assign variables to objects in Python:

1. We type x = 3 → Python will create the object which is 3.


2. Python will create the variable name x.
3. Python will insert a reference from the name of the variable to the actual object.

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.

So once we've run, x = 3 and y = 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 ).

2. L2 = L1 ( L1 which currently references the list already exists)


- Creates the variable (L2) .
- Reference the object that L1 references. L2 cannot reference L1 (another variable).
- L2 becomes a synonym for the very same object.

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?

When comparing lists → comparison is element-wise.

The content of these two lists is identical.

Is L the same object as M?


Python returns "False".
We can use the id function () to obtain the identity of an object.

Number returned → the object's location (“Social security number”) in memory.


id (L) is different than id (M)

Mutable objects can be identical in content, yet be different objects.

What if I wanted to create a copy of that list?


M = L → M is another name for the same list, L.

Create a new object that has identical content to L


Creates a new list, and then assign that list object to a new variable.

My list object (L) → in the computer's memory.


That's because these two objects are distinct. But if I ask, is M==L → true.

Copy of a list is to use the slicing syntax.

M is equal to L→ M = L [ : ]

- Creation of a new list object


- Assigned to the variable name M.

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.

Object x, and references to other objects embedded in our object x (a and b)

1. Shallow copy → X’ but then references in x to the original objects a and b.

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

Used to compute values, assign values, and modify attributes, etc.

Here are three examples of more specialized statements.

1. Return statement → to return values from a function.


2. Import statement → , import modules.
3. Pass statement → do nothing in situations where needed a placeholder for syntactical reasons.
4. Compound statements groups of other statements) → affect or control the execution of those
other.

- Compound statements span multiple lines.


- Consists of one or more clauses (header and a block or a suite of code).
- Close headers of a compound statement: start → keyword, end → colon; same
indentation level.
- Block or a suite of code of each clause → indented to indicate that it forms a group of
statements that logically fall under that header.

No hard and fast rules about indentation as long as you are consistent (tab or using four spaces).

Example:

Compound statement with one clause.


→ Header line: if x is greater than y followed by a colon (:).

→ 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:

Computing the absolute value between x and y.


Absolute value → how far two numbers are from one another.

If true, we will assign absolute value as x minus y → absval = x-y

If elif is true, we will define absval= y-x .

If not true, then proceed to line 5, which is the else statement.

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.

4. For and While Loops

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.

Set up a sequence of 10 numbers → range (10)

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.

List called names, 6 different names.

For Loop to iterate over all of the names on this list.

for name in names:


print (name)

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)

Dictionaries are accessed by their keys → use a loop variable


that conveys what the keys of the dictionary actually
stand for.
for name in age.keys ( ):
print ( name, age[name] )

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.

Loop over the dictionary keys in some order (alphabetical).

To sort the keys:


1. Extract the keys by saying age.keys,
2. Used a built-in function sorted ( ) to create a new list sorted.

Loop over your dictionary keys in reverse order.

We have to provide the attribute reverse → "reverse=True".

The keys will appear in reversed alphabetical order.

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.

OJO: You can accomplish a lot in just one line.

Why would you want to use a list comprehension in Python?


1. List comprehensions are very fast.
2. Are very elegant.

6. Reading and Writing Files

Read files in Python.

Created a simple text file with three lines → inputfile.txt


- Create a variable file name→ name of my input file.
For loops to read a file → "for line in open( )" inside open insert
-
filename.
What this does:
- open(filename) generates a file object.
- Loop over file objects using the for statement.
- Line will always contain one of the lines of the input file.
Print out the lines of the file → "print(line)" and Python will print out three lines.

Line of text that just says "first"


At the end of the line (you don't see it) → line break character
“ \n”
String where line = “ first”→ cause extra line breaks in processing of your text.

A way to remove this character using the rstrip() method.


If you call line.rstrip() → extracts the “\n” and leaves you with the first part of the string.
rstrip( ) method → line.rstrip( )."
OJO: strings are immutable. To keep the result, assign to a new or existing
variable.
Re-assignment→ "line=line.restrip()".
Run the loop→ the extra line breaks have disappeared.

Returns a string. So train a new string function at the end of the line→
line.rstrip().split(“ _ ”).

- : as argument, provide the character for splitting the line.


String split method → returns not a string but a list.

Write a text file line by line.


Let's create the file object by typing "open( )".

- Name of the file → "output.txt".


- When writing a file, we need a second argument → create a file object for writing, not reading.
- Indicate the second argument as a string, and the content "w" → open (“output.txt”, “w”)
- Capture this file object in some variable → F = open (“output.txt”, “w”)
File object has been opened, and ready to start writing.

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.

Written using the def statement.


You can send the result object back to the caller using the return statement.

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

1. Name of the function.


2. Provide both of the two inputs (12 and 15).
3. And returns the sum of those two numbers, 27.

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.

Arguments to functions are matched by position.

Tuples to return multiple values from a function.

Define a new function with two arguments → add_and_sub (a, b)


Inside, define a sum and mydiff →
Return mysum and mydiff to the caller of the function.
Using a tuple where the first returns my mysum and the second mydiff.

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.

Type newadd = add.


Two different names for calling the function→ use add or I can use newadd.

Arguments are passed by assigning objects to local names.

Mutable object.

Define a function called modify, with one argument→ modify (mylist).


Mylist function → first element at location 0 and it will multiply its value by 10.

Create a list L= [1, 3, 5, 7, 9].


Call my new function using L as the input argument.
I'll see that the first number at location 0 has be multiplied by 10.

8. Writing single functions

Split my screen into two parts.


Top → interactive mode.
Bottom → editor mode.

Write the function in the editor.

OJO: Functions with more than two or three lines are just easier in the
editor mode.

Name of the function→ intersect


2 input arguments to the intersect function→ s1 and s2.

Decide how are we going to keep track of the results?

Use a list → res as an empty list.


- Loop over all objects in s1 (membership)
- Loop over and ask if all of the members are in s2? (membership)
- If true, then we would like to retain that list in our result.
- Append that result to our res list, and we're done.
- Return the list res to whoever is calling this function.

Program that generates passwords.


Specify the character set and the length of the password.
- Function password with just one argument ( the length of the pw)

What module if any we may need to import.


- Choose characters from a sequence of characters →
module random.

OJO: random (method choice) → enables to choose randomly


from a sequence. Choose numbers from a list or a string,

Define is an empty password (as a string) → pw = str( )


Define set of characters to be used in my password → characters =
“abcdef”
- Pick one uniformly at random → random.choice method (characters)

Repeat this process multiple times.


- Sample characters (randomly) and construct my password
Loop → for i in range(length)
OJO: Repeat this process precisely length times, so for loop, not while
loop.
Store chosen characters (concat) → pw=pw + random.choice(characters)
Return password → pw

If I ask for a longer password, perhaps one with 10 characters, the code appears to be working correctly.

With few more characters to our character set.

OJO: rerun the function, to implement changes!

And you can see that Python is now randomly choosing characters from the
entire set of alphabets.

What if you also wanted to include numbers in our set of characters?


- Type the numbers 0, 1, 2, … right after our last letter in the string.
- Concatenate a new string to the end where we type out the numbers.

We can now try re running the function → password (5)

In this case, Python is including both characters (letters and numbers) in our password.
Really secure, generate a much longer password.

9. Common Mistakes and errors

A. Not reading or understanding error messages.

OJO: Lists are indexed by object positions.

So if I type L [5] → error message saying "list


index out of range".

What does this error mean?

You list only have locations are 0, 1, and 2. So even if I try to


access object at location 3, I will get the same error.

Make sure you know how long that sequence is.

B. Forgetting that dictionaries have no left-right ordering.

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.

C. Trying to do an operation that is not supported by the object.

List that consists of the numbers 2, 4, and 6.


I type L add 8 → Python gives me an error (attribute error)

The list object has no attribute "add."--> right method is "append."


Instead of typing L.add, → type is L.append then provide my
new number.

Make sure you know the type of the object so you know the methods that the object
supports.

D. Trying to access an object in the wrong way.

In this case, I have built a dictionary.


Keys → 1, 2, 3 and the values→ aa, bb, and cc.
Tempted to do a dictionary look up like this→ D [1]

Python is giving me a very short error message "KeyError: 1".

How should I interpret this message?


Keys are actually not numbers, but they are strings. So what I really should be providing here is a string, not a
number.

When accessing dictionaries, make sure you know the type of your key objects.

E. Trying to modify immutable objects.

Immutable objects cannot be modified after they have been created.

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.

F. Trying to operate on two objects that are actually of different type.

I'd like to concatenate a string and a number.


My string is "the answer is" and I'd like to simply concatenate that with
number 8.
Type error because we're trying to concatenate a string and a number.
F: ix is to turn the number to a string and now concatenation works.

Therefore, make sure that you always know the type of your objects.

G. Indentation
Simple function → calculating the running sum up to n.

Set up my result variable which is my running sum, which is initially = zero.


Set up a range object, and I use k to loop over all of the numbers in my range object.

Take my running sum and add the value of k to that sum. Return the result to the
caller.

Calculate the running sum for the first 12 integers → answer is


0.

So what went wrong here?

Instead of completing the for loop, we return rsum some during the first iteration.
The way to fix the problem is the following.

You might also like