Essential Python Programming (for begineer)¶
Print¶
print()
is the first step of Python. It show you stuff.
Python | |
---|---|
Type¶
type()
tell you the type of the object.
Number¶
Number in Python is just written like a number.
String¶
String is different from number.
Changing Type¶
By now you should know that type(3)
is int
and type("3")
is str
. This type can also use as a transform function.
Variable¶
Just like 3x = y in school algebra, x
and y
are variable. Variable is a name. There is a value behind the name.
Comment¶
Comment is not part of the program. Python do not excute the part you written as a comment by default. #
indicate stuffs behind is intended to be a comment.
You can see nothing is being output. Since those lines for outputing stuffs on screen are now comments.
For the sake of convenient, now I use comment to show the output of certain line.
Operation¶
Condition¶
Condition is simple. If
this do this else
do that.
Python | |
---|---|
Temporary variable¶
Temporary variable is like this: temp := some condition
. When the condition is evaluated as True, that value is assigned to the variable name temp
. Usually using with condition.
Below is the conventional code.
Python | |
---|---|
You want to print the value if name == "Mary"
but this code do not seem smart. Use temporary variable
When the value of name == "Mary"
is not False, it will be assigned to variable name message
. What means by is not False? It is that the string is not empty, the string is not evaluated as False.
Range¶
Provided a upper bound and a lower bound, you can count numbers. You can ask if a value is within the range.
Python | |
---|---|
List¶
List is a list. For example name list, a bunch of names inside a single list. list()
is a function that can change some specific stuff into a list.
Python | |
---|---|
Check how many stuffs are in the list. len()
stands for length.
N dimensional List¶
You can put anything insided a List, including a List itself.
List index¶
Stuffs inside a List count from 0. 0th element, 1st element, 2nd elenment, and so on.
Python | |
---|---|
List is mutable¶
Stuff inside a List can be changed.
List contain a reference¶
id()
is how you can check the memory address of a object.
Python | |
---|---|
You see that both return the same value. Both are referencing to the same memory address. In Python, number/interger is inmutable and everytime you callit, it refers to the same object. Unless you do not want this feature on purpose.
So there is "imutable" object in Python. Of cos, there is "mutable" object in Python. One of this kind is the List we are looking right now.
So when you put a List inside another List, you are puting the reference of the List only, not the elements inside of the first list. Hence when you change the element, the changes happen to everywhere.
Python | |
---|---|
List copying¶
To prevent the global changes of element, you have to create new object for each of them.
Python | |
---|---|
Or you may use the copy()
function from List itself. But also, it only give you the reference of its elements. When the element is another list, it is the same object before and after copying.
Let's first see how List.copy() work in action.
Python | |
---|---|
You can see original x is not affected because element of x
is number/integer and it is imutable. And imutable object is the end of the journey, you cannot reassign another value to that memory address.
Python | |
---|---|
x2[1]
refer to the inner List [2,3]
. x2[1][1]
means that we are changing the second value of this inner List to 99
. By print the memory address, you can see that both refer to the same object. Hence when you change one side, the other side also changed.
Deepcopy¶
In the previous section, we see that modifying a N dimension List will have some unwanted side effect. How to prevent that?
Here comes a function that is handy but if not careful enough, it hurt the performance a lot.
Loop¶
One of the greatest thing in programming is that you can repeat same task for many times. This ability is called looping. Mainly, there are two types of loop in Python. For loop and WHITE loop.
For loop¶
Python | |
---|---|
For loop with condition¶
For loop break continue pass¶
You can stop the For loop manually by break
.
You can skip the current cycle by continue
.
You can pretend that there is code but actually nothing.
Nothing is being done inside the loop. But that still require some computational resource since it is still counting from 0 to 7.
But pass
is different from continue
, pass
is like a space holder but do not have the same functionality of continue
. pass
do not do skip.
N dimensional For loop¶
For each layer of For loop, one element is being taken out from the list. When that element is also a list, you can use for loop on this element of list.
Python | |
---|---|
By changing the position of function print()
, or stuff inside function print()
, you can obtain different effect.
Python | |
---|---|
So the overall printing will be:
Enumerate¶
When it become confusing to make sense of N dimensional Loop, use enumerate()
.
Python | |
---|---|
More typical usage of enumerate()
is like this.
Python | |
---|---|
So that you know which dimension is which.
Building List using For loop¶
You can put stuff into empty list by List.append()
.
Python | |
---|---|
Decompose List using For loop¶
Python | |
---|---|
List comprehension¶
The building process of a list and the expression of For loop can be compressed into a single line. []
construct a List. for name in namelist
make a For loop. By combining both, you can make a List in one line of code.
List comprehension with condition¶
This is the same as:
Python | |
---|---|
N dimensional List comprehension¶
Python | |
---|---|
This is the same as:
Python | |
---|---|
You can use this method to build a empty matrix.
List comprehension with temporary variable¶
Explained: Counting from 0 to 10, not include 10. num%2
means remainder after num is divided by 2. It the remainder is nonzero, it means True to Python. Therefore, If the number has remainder after divided by 2, assign this remainder to the new List x. So eventually you obtain a List full of 1.
By changing num%1
to num%4
, you got the x mod 4
in algebra.
WHILE loop¶
WHILE loop is like this: While the condition is True, do the following non stoply.
Output:
Explained:While True and break¶
Sometimes it is just more convenient to do the loop first, check the condition then.
Python | |
---|---|
The usage depend on you.
But never forget to end the loop. Otherwise it is called infinite loop. The loop will never end. And Python can not tell itself is doing infinite loop of if the loop is going to end. When you wait so long and still not seeing the result of your program, probably you wrote some infinite loop back there.
While Continue Pass¶
Same usage as For loop.
While Comprehension¶
As far as I know there is no such thing in Python (or is it?)
Dictionary¶
Vocabulary -> Meaning. This is the Dictionary. Creating a connected pair. Or mathematically speaking, a mapping (hey no one understand this!).
Dictionary is constructed by {}
. Inside this curvy braket, key : value. A for Apple B for Bob!
When extrating the value back, use the same syntax of List indexing. Calling x["A"]
like asking the Dictionary hey what is connected to "A"? The Dictionary anwser you Oh it is "Apple".
Dictionary Construction¶
Well almost same as if this is a list. But a little different.
Python | |
---|---|
But this code do not seem smart. Then, use zip()
. zip()
combine two or more stream of data into one, so that you can write a for loop for it!
Python | |
---|---|
Zip Dictionary Construction¶
zip()
usage in the previous section. We can make use of that and write just a fewer code to achieve the same thing.
Python | |
---|---|
zip()
combine two list, and dict()
turn this combined stream of data into a Dictionary.
But this only work if stuff inside zip()
make a pair. If you have something like zip(list1, list2, list3)
, this do not work. What you need is the next technique.
Dictionary Comprehension¶
Just like List Comprehension, there is Dictionary Comprehension too. Given that {}
make a Dictionary, just like []
make a List, you can do this. The syntax is only differ from List Comprehension by a little.
Basically this is just the code from previous section with different ordering.
Python | |
---|---|
By Dictionary Comprehension, you can now do zip(list1, list2, list3)
.
As you see from this demostration, everything can be assigned as a value of Dictionary including number, string, List, Dictionary... But not the key. For a key, Dictionary require you to have a unique key for each object. But is way beyond comprehension of a begineer, so you can totally ignore this fact. Just try if you are not certain. Sometime Python will stop you from doing that. Try using a list as a key of Dictionary like the following code.
Enumerate Dictionary¶
Dictionary provide the fastest way to access a value by its key. But what if you want the inverted version: access a key by its value?
For example a List, you want to know the List index of certain string. Here you can combine Dict Comprehension and function enumerate()
to achieve that.
Python | |
---|---|
But this only work if and only if the element inside the List is all unique. For example when you have two Amos ["Amos", "Amos", "Behemoth", "Ceres"], the information from the first entry is being covered by the second entry. So the resulting lookup dictionary will only store it Amos is in position 1, not [0,1].
For multiple entry, you need to write a normal For loop.
Python | |
---|---|
Now you may ask if that if value not in lookup:
checking is cumbersome because it actually is. So there is a better solution for this. A DefaultDict.
DefaultDict¶
First you need to tell the DefaultDict, what is your default value if the key is not being assigned to the dict. This time you say you want a list as default. So that DefaultDict will create a empty list for you.
Python | |
---|---|
Tuple¶
Tuple is the imutable version of List. And because Tuple is imutable, you can assign it as a key of a Dictionary!
Python | |
---|---|
Python | |
---|---|
Imutable¶
Almost everything is same as a List except that now you cannot change the content inside a Tuple.
But just as what you have learnt from the section of referencing, Tuple only keep track of the first layer of reference. If you put List inside a Tuple, you can not change the List, but you can change stuff inside that List.
Python | |
---|---|
But you can do this does not mean that you should do this.
Tupling¶
Just lke you can turn something into a List by using function list()
, you can almost do the same thing with function tuple()
.
Python | |
---|---|
Tuple Comprehension¶
Do not like List or Dictionary, for Tuple, you need to use function tuple()
to write a comprehension.
Python | |
---|---|
Itemgetter¶
Function itemgetter()
comes handy when you need to obtain multiple element from a List of from a Tuple of from a Dictionary at once.
Usually people do this.
Python | |
---|---|
Stop doing this. Use itemgetter.
Python | |
---|---|
If you obtaining multiple stuff, Itemgetter return a Tuple. If you obtain only single stuff, itemgetter return that single object without putting it in any List or Tuple. You need to be careful with this. Since tou can use *
to unpack a List or Tuple even if that List or Tuple contain only single element. But since you are using *
to unpack something, you are expecting many things inside. Really, be careful of this behaviour.
But first of all what means by "use *
to unpack a List or Tuple" ??? This is explained in the following section.
But before that, just one more thing. You can use itemgetter()
to extract element from 2 dimension List.
Python | |
---|---|
map(itemgetter(0), x)
is like a idiom, so remenber it.
Multiple Unpack¶
Python | |
---|---|
You have seen this in the section of Dictionary. You should have ask the question "What is that for (initial, value) in zip(
? "
This is called multiple unpack in Python. Pairs are being returned from function zip()
, and you assign a each of them to a variable name initial
and value
. Basically this act the same as following code.
Python | |
---|---|
With multiple unpack, we can just split and asign each element inside a Tuple or a List of something work like them with a variable name.
Although multiple unpack is useful, do not addict to it. Sometimes it comes with performance penalty like the following.
Python | |
---|---|
Set¶
So you know there is List, Tuple, Dictionary. There is one more: Set .
Set share the same symbol as Dictionary. But to build a Set, you need to call the function set()
.
Python | |
---|---|
Building a Set using For loop¶
Python | |
---|---|
Set Comprehension¶
Well, there has List Comprehension, Dict Comprehension, no Tuple Comprehension, but there has Set Comprehension. It is just [
for the List thing replaced by {
.
Python | |
---|---|
Setting¶
Python | |
---|---|
List(Set(List))¶
For example you got a List x=[1,2,3,1,2,3,1], you want to eliminate duplicated elelment. Do this, list(set(List)).
No matter what your algorithms textbook is saying, this is the known fastest way in Python.
Set Relation¶
Make use of set relationship. You can make the fastest program out of them.
Python | |
---|---|
Want More?¶
Created: 2023-06-28