Python
Python
And the popular ML & AI with Python also requires some basic knowledge of Python.
I alr have some basic understanding of it, so it should be pretty easy for me.
It's a bit unique, simply using a #, unlike C++ or others, using // or /* ... */ .
eg. # this is not a command
If you want a multiple-line explanation and you don't want to trouble yourself, use
""" """.
eg.
"""
this is
a multiple-line
explanation
"""
( 讲个段子
就是有一个程序员, 负责编写和维护程序, 然后公司要求注释率要保持在 20%以上, 让别人好理解他的代码.
但是他实在是不喜欢写注释, 于是, 他复制了一百章斗破苍穹进去...
老板问新来的程序员, 代码理解到哪里了.
"刚到云岚宗"
哈哈哈哈 )
In C++:
if (a>b) {
if (b<c) {
print("c is the biggest of the three");
}
}
else if ( c > b ){
print("c is the biggest among the three")
}
In Python:
if a > b :
if b < c :
print("c is the biggest of the three")
elif c > b :
print ("c is the biggest among the three")
Maybe now you get what I mean by the elegant "simplicity" of Python.
Alr, get back to the point, indentation is the space (tab) for each block of code.
If there is no space before the code block, it's called Indentation Error.
Talking about variables, again, I have to thank for the simplicity of Python.
In C++ :
int a = 5;
float b = 5.0;
str c = "5";
In Python :
a = 5
b = 5.0
c = "5"
If you can't see the difference, I'll introduce you the best optical doctor I know.
Kidding, as you can see, Python automatically recognizes what type of that
variable.
Cuz Python has some built-in functions, it improves the simplicity but slow down
the operating speed.
Well, but I still prefer Python, as it drastically improves simplicity of code and
a little bit slower.
I'm not a software engineer of any internet companies yet, so I don't have to worry
about that for now.
( Just for a complement, u can still use " x = int(5) " if you want )
Trust me, if the question doesn't give you the variable name, it'll be hard for you
to come up with one.
Remember, the variable name should be precise and readable, here are some
techniques :
- Camel Case - each word, except the first, starts with a capital letter. eg.
myVariableName = "."
- Pascal Case - each word begins with a capital letter. eg. MyVariableName = "."
- Snake Case - each word to be seperated by an underscore letter. eg.
my_variable_name = "."
( And your variable name shouldn't start with a number and cannot be any of the
Python keywords )
OK, that's for Day1 of my study, it's pretty easy and pleasant, I will try to learn
more tmr.
Day 2.
Again, Python allows you to go the easy way, you can output multiple variables,
seperated by a comma.
eg.
x = "Python"
y = "is"
z = "awesome"
print(x , y , z)
Of course, you can choose to go the hard way, which is to use "+" to put them
together.
eg. print( x + y + z )
output = Pythonisawesome
As you can see, now you have to type in the " " manually.
x = 5
y = 7
print ( x + " " +y )
x = "John Wick"
y = 4
print( x , y )
x = "awesome"
def myfunc() :
x = "fantastic"
print("Python", "is", x)
print("Python", "is", x)
output :
Python is fantastic
Python is awesome
So the change in local variable doesn't affect the value of global variable.
However, if you want to create a global variable in a function, we can use the
global command.
x = "awesome"
def myfunc( ) :
global x
x = "fantastic"
myfunc( )
print("Python", "is", x)
WELL, it means you can change the global value in a local function.
But unless you have some special purposes, I don't recommend doing so.
Day 3
But firstly, let's talk about what does a range function mean.
range (a,b) represents a set of number bigger than a (inclusive) and less than b
(exclusive).
output = 2 3 4
If you want to assign a very large number or a very small one to a varaibe, you can
use the scientific numbers.
Take note that, these numbers are considered as float numbers, and "e" represents
the power of 10.
If you want random numbers, u can choose to import the random module, as shown
below.
import random
print (random.randrange (1, 10))
But I remember it's randint smth? I'm sure I saw that before, nvm, we'll find out
along the way.
And, I have to say that, unless we invent quantum computer someday, we can't
generate real random number.
Most random numbers are generated based on the time at that moment, and it's
predictable.
BTW, if you write x = int ("3"), it can identify the value in the string and
correctly assign this value.
And if you try to convert a float number into an integer, the decimal places will
disapper.
I bought a new wrist rest, well, I have to say that it's much better than the
previous one.
For a string in Python, you can see it as an array and output every letter; you can
read the length using len() ;
And you can even check whether it contains some word by "in ..." function :
You can also use if NOT to check the presence of smth inversely :
outupt = True
Take note that, it should always be "True" instead of "true", you should make the
first letter to be uppercase.
Slicing will be very helpful in the later parts of the study, let's see how it
works.
b = "Helloworld!"
print ( b [2:5] )
As shown, it's used as " arrayname [index A : index B] ", representing array from A
to B-1.
Also, you can use [ :5] or [2: ] if that fits the situation, meaning from the start
to 4 or from 2 to the end.
Positive index counts from left to right, negative index counts from right to left.
txt = "Helloworld"
txt [1] = "e"
txt [-1] = "d"
So you can easily spot the difference, as index 0 belongs to the 1st character.
In slicing, txt[ : -1] means from the beginning to the end, pretty easy to use,
isn't it?
You should know what is "upper()" and "lower()" function, if not, just guess out of
the name.
Strip() function removes the whitespace at the BEGINNING or the END, pretty
interesting.
a = "banana"
a.replace ( "an", "b" )
print(a)
output = 'bbba'
Split() function returns a list where the text on both sides of the seperator
becomes list items (comma as default)
output =
['Hello', ' my name is DACONGMING']
['Hello,', 'my', 'name', 'is', 'DACONGMING']
Actually, the brackets are all not empty, indeed, they are filled with default
conditions, but it's too hard to memorize all of them. And there is a specific
order for all the conditions, I hope we don't have to use it.
But it only allows same type combine together, meaning you cannot write smth like
this :
f-string :
Obviously, I can't be typing here if I'm really 108 years old, but at least it's
working.
You can also modify and perform math operations inside this placeholder, eg :
total_price = 1500
num = 19
txt = f"The clothes are {total_price/num : .2f } dollars on average"
print (txt)
output = ValueError: Invalid format specifier '.2f ' for object of type 'float'
Just now I made a mistake, never never add spaces when you are trying to modify it.
If you still can't find it, it should be ":.2f}" instead of ": .2f }".
See that? If you change it correctly, (try it yourself), the output is 'The clothes
are 78.95 dollars on average'.
format() is a bit outdated, alright, actually I want to know, but w3schol webiste
never talks about it.
So, ya, I guess f-string is more convenient and covers all the applications, at
least I hope so.
In a string, it's not allowed to have the same quote in the text. eg :
Python reports a Syntax Error, that's why sometimes we have to use single quote.
Actually, there are a lot of escape characters that are not taken into
consideration.
Well, maybe you don't have to memorize all of them, you'll slowly get famaliar with
them, hope they welcome u.
If you read through everything, feeling it's so easy and you don't have a headache
at all.
那兄弟你离神不算近, 但是离人类已经很远了.
I recommend you to use "help" function to check for the desired methods, yet it'll
still be troublesome.
If you want to return a bool value, you may use bool() function. eg :
It means that anything other than zero is considered True, only zero is False.
Well, in fact, there are a lot of values representing False, but all of them are
somewhat related to null.
The only exception might be _len_ function, if your object comes from a class with
such function, it returns 0.
class myclass() :
def _len_(self) :
return 0
myobj = myclass()
print( bool(myobj) )
But of cuz you can use the same principle and return a True value.
def myFunction() :
return True
print( myFunction() )
Since it's a boolean value, it's also ideal for conditions of if-else statement :
if myFunction() :
print( "YES!" )
else :
print( "NO" )
Many built-in functions return a boolean value as well, like isdigit() or isalpha()
in the previous section.
Python Operators
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Arithmetic Operators
x % y + ( x // y ) * y = x
Assignment Operators
Here comes the interesting part, it has a better way to assign a variable.
x = 3 print( x )
But now we can simply write as print( x := 3 ), where ":=" means assigning 3 to
variable x and print it.
Actually there are some Bitwise operators involved, but it's pretty easy to
understand.
Bitwise OR ( |= ) : Convert the two values into binary, on any bit, using OR
function to combine the two numbers.
In fact, "^" here represents XOR instead of power, maybe the father of Python
doesn't like him.
Right Shift and Left Shift are also included, which moves all the bits to right or
left by 1.
eg. x = 8
x >>= 1 ==> output = (100) = 4
x <<= 1 ==> output = (10000) = 32
Maybe you kinda feel that it's not that tough, right?
It is true, so don't always be so afraid, enjoy how they design the system n use
it.
Comparison Operators
They are for comparison purposes, including == , != , > , < , <= , >= .
Logical Operators
Just take note that, "not" has the highest priority, then "and", "or" is the last
one.
Indentity Operators
Including "is" and "is not", as you can imagine, "is" only returns True when the
two objects are exactly the same.
Membership Operators
Including "in" and "not in", which is discussed before, hopefully you still
remember it.
Bitwise Operators
Including "&" (AND) , "|" (OR) , "^" (XOR) , "~" (NOT) , "<<" (Left Shift) and ">>"
(Right Shift).
It studies the relationship between every bit in the two binary numbers, using
different logics.
We've studied all the operators so far, what happens if there're lots of operators
at the same time?
They operate part by part following the precedence order, starting from the highest
precedence at the top.
(When they have same precedence, we evaluate the expression from left to right)
() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary minus, and bitwise NOT
* / // % Multiplication, division, floor division, and modulus
+ - Addition and subtraction
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not in Comparisons, identity, and
membership operators
not Logical NOT
and AND
or OR
Sadly, we don't use this often in real applications ; Even more sadly, this is hard
to memorize ; Even more more sadly, cuz it is hard to memorize, it's likely to be
tested, meaning u have to memorize all of them.
You might take a small break and review what we've gone so far, at least I plan to
do so.
Python Collections
There are four types of collection in Python : List, Tuple, Set and Dictionary.
List
List is one of the built-in data types to store collections of data, eg. list =
[ a, b, c, d ]
Ordered refers to a defined order of items, if u add a new item (.append), it's
placed at the end of the list.
Changable means that we can change, add, and remove items in a list after it's
created.
If you try len() function, it returns the number of items in the list.
And list items can be any data type, whether it's int, bool or string.