Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python

An introduction to python
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python

An introduction to python
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

Alr, so, Python is generally the easiest language to use.

And the popular ML & AI with Python also requires some basic knowledge of Python.

The simplicity and readability in python is really elegant.

I alr have some basic understanding of it, so it should be pretty easy for me.

Let's get started !

How do we write comments in Python?

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%以上, 让别人好理解他的代码.
但是他实在是不喜欢写注释, 于是, 他复制了一百章斗破苍穹进去...
老板问新来的程序员, 代码理解到哪里了.
"刚到云岚宗"
哈哈哈哈 )

INDENTATION is extremely important is python, with indentation, we can get rid of


the annoying brackets.

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.

I'll show u why.

Let's try with a few examples.

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.

Python allows you to assign values to multiple variables in one line :

eg. x, y, z = "Orange", "Banana", "Cherry"


If you have a collection of values in a list, tuple or set, Python allows you to
unpack in the similar way.

eg. fruits = ["Apple", "Banana", "Cherry"]


x, y, z = fruits

Print function, as you noticed, is often used to output variables.

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)

output = Python is awesome

Indeed, Python is awesome, as it automatically helps to add a space in between.

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.

However, sometimes, you can't even type in " " manually.

x = 5
y = 7
print ( x + " " +y )

output = TypeError as numbers and strings combine together.

But there is a way to output numbers and stings simultaneously.

x = "John Wick"
y = 4
print( x , y )

output = John Wick 4

Global variable, in the name, can be used globally.

If you change such variable in a function, it becomes local variable in that


function, shown below.

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)

output = Python is fantastic

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

range function is often used for looping.

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

eg. range (2, 5) => 2, 3, 4

So it's ideal for a for loop.

for i in range (2, 5):


print ( i )

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.

eg. x = 35e3, y = 12E4, z = -87.7e100

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.

However, it fits the purpose of generating some random numbers, so we shouldn't be


too strict to ourself.

BTW, if you write x = int ("3"), it can identify the value in the string and
correctly assign this value.

Thus x = 3 in this case.

And if you try to convert a float number into an integer, the decimal places will
disapper.

eg. int (3.6) => 3, int (-3.6) => -3.

I bought a new wrist rest, well, I have to say that it's much better than the
previous one.

So now it's Day 4.

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 :

txt = " The best thing in my life"


if "my" in txt :
print ("Yes, this is smth related to myself")

You can also use if NOT to check the presence of smth inversely :

txt = "The best thing in my life is free!"


print ("expensive" not in txt)

outupt = True

Take note that, it should always be "True" instead of "true", you should make the
first letter to be uppercase.

Ok, now we comes to a very important thing, "SLICING".

Slicing will be very helpful in the later parts of the study, let's see how it
works.

Slicing is to get characters from index A to index B in an array.

b = "Helloworld!"
print ( b [2:5] )

output = "llo" (including 2th index but excluding 5th index)

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.

Sometimes, negative index is helpful.

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?

Let's get back to the string.

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.

x = " Why there are so many spaces? Oh, nvm "


print (x.strip())

output = 'Why there are so many spaces? Oh, nvm'

Replace() function replaces certain characters in the string with desired


characters.

a = "banana"
a.replace ( "an", "b" )
print(a)

output = 'bbba'

So it replaces all satisfied characteres and it doesn't have to be one character.

Split() function returns a list where the text on both sides of the seperator
becomes list items (comma as default)

a = "Hello, my name is DACONGMING"


print(a.split(","))
print(a.split(" "))

output =
['Hello', ' my name is DACONGMING']
['Hello,', 'my', 'name', 'is', 'DACONGMING']

So as you can see, choosing different seperator makes a significant difference,


based on what you want.

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.

Ok, after knowing those functions, let's turn to smth simpler.


Strings can combine together using "+", this is smth you should know. ( like "My" +
" " + "go" = 'My go' )

But it only allows same type combine together, meaning you cannot write smth like
this :

eg. age = 108


txt = "I'm " + age + " years old right now"
output = TypeError

Apparantly, we need to change age (int) into a string type.

We can use "format()" or f-string to achieve this.

f-string :

txt = f"I'm {age} years old right now"


print (txt)

output = 'I'm 108 years old right now'

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.

Meaning, it should be {total_price/num :.2f} instead of {total_price/num : .2f }.

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 :

txt = "We are the "Vikings" from the north"

Python reports a Syntax Error, that's why sometimes we have to use single quote.

But there's another way to solve it.

The escape character "\".


To put it simply, any character after the escape character is not taken into
consideration. eg:

txt = "We are the \"Vikings\" from the north"

Now Python is muted, he completely agrees with you.

Actually, there are a lot of escape characters that are not taken into
consideration.

" \' " means single quote. ( the character after \ )


" \\ " means backslash. ( same thing )
" \n " => New line
" \r " => Carriage return ( only return the part after it )
" \t " => Tab
" \b " => Backspace ( pretty interesting, eg. txt = "Hello\bWorld!" output =
'HellWorld' )
" \ooo " => octal value (actually the last two digits are numbers, eg. " \o45 ")
" \xhh " => hex value (the same thing, eg. " \x6c ")

Well, maybe you don't have to memorize all of them, you'll slowly get famaliar with
them, hope they welcome u.

If you have addictions to collections, here is a collection of all the string


methods.

capitalize() <=> Converts the first character to upper case


casefold() <=> Converts string into lower case
center() <=> Returns a centered string
count() <=> Returns the number of times a specified value occurs in a string
encode() <=> Returns an encoded version of the string
endswith() <=> Returns true if the string ends with the specified value
expandtabs() <=> Sets the tab size of the string
find() <=> Searches the string for a specified value and returns the position of
where it was found
format() <=> Formats specified values in a string
format_map() <=> Formats specified values in a string
index() <=> Searches the string for a specified value and returns the position of
where it was found
isalnum() <=> Returns True if all characters in the string are alphanumeric
isalpha() <=> Returns True if all characters in the string are in the alphabet
isascii() <=> Returns True if all characters in the string are ascii characters
isdecimal() <=> Returns True if all characters in the string are decimals
isdigit() <=> Returns True if all characters in the string are digits
isidentifier() <=> Returns True if the string is an identifier
islower() <=> Returns True if all characters in the string are lower case
isnumeric() <=> Returns True if all characters in the string are numeric
isprintable() <=> Returns True if all characters in the string are printable
isspace() <=> Returns True if all characters in the string are whitespaces
istitle() <=> Returns True if the string follows the rules of a title
isupper() <=> Returns True if all characters in the string are upper case
join() <=> Joins the elements of an iterable to the end of the string
ljust() <=> Returns a left justified version of the string
lower() <=> Converts a string into lower case
lstrip() <=> Returns a left trim version of the string
maketrans() <=> Returns a translation table to be used in translations
partition() <=> Returns a tuple where the string is parted into three parts
replace() <=> Returns a string where a specified value is replaced with a specified
value
rfind() <=> Searches the string for a specified value and returns the last position
of where it was found
rindex() <=> Searches the string for a specified value and returns the last
position of where it was found
rjust() <=> Returns a right justified version of the string
rpartition() <=> Returns a tuple where the string is parted into three parts
rsplit() <=> Splits the string at the specified separator, and returns a list
rstrip() <=> Returns a right trim version of the string
split() <=> Splits the string at the specified separator, and returns a list
splitlines() <=> Splits the string at line breaks and returns a list
startswith() <=> Returns true if the string starts with the specified value
strip() <=> Returns a trimmed version of the string
swapcase() <=> Swaps cases, lower case becomes upper case and vice versa
title() <=> Converts the first character of each word to upper case
translate() <=> Returns a translated string
upper() <=> Converts a string into upper case
zfill() <=> Fills the string with a specified number of 0 values at the
beginning

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.

Well, at least that's for me, as an ordinary human being.

This is the end, and I'm going to take a rest.

It's now Day 5, and it's a chill afternoon.

Hopefully I can easily go through everything.

Now we are looking at Boolean values.

There are only two types of values : True or False.

If you want to return a bool value, you may use bool() function. eg :

print(bool("hello")) => True

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.

eg. False , None , 0 , "" , () , [] , {}.

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

Python divides operators in the following groups :

- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators

Let's go throught one by one.

Arithmetic Operators

These are simple operators to perform math calculations.

Including + , - , * , / , % (Modulus) , ** (same as ^) , // (Floor division).

A few interesting things to know :

x % y + ( x // y ) * y = x

x ** y = x ^ y, eg : 2 ** 5 = 2 ^ 5 = 32, the order should never change.

Assignment Operators

In the name, they are used to assign values to variables.

Like = , += , -= , *= , /= , these are quite easy.

Here comes the interesting part, it has a better way to assign a variable.

For eg, if I want to print variable of 3, normally I'll write as :

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.

Bitwise AND (&=) n Bitwise XOR (^=) follows similar rules.

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 == , != , > , < , <= , >= .

This is too fundamental, I decide not to talk about it.

Logical Operators

Including "and" , "or" n "not" , this is too easy as well.

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

Well, I guess I don't have to explain anymore, as it is covered in previous


section.

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 is ordered, changable and duplicate-allowed.


Tuple is ordered, unchangable and duplicate-allowed.
Set is unordered, unchangable, unindexed and no duplicates allowed.
Dictionary is ordered, changable and no duplicates allowed.

List

List is one of the built-in data types to store collections of data, eg. list =
[ a, b, c, d ]

List is Ordered, Changable and Duplicates-Allowed.

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.

Duplicates-Allowed means duplicated items can exist in the same list.

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.

If necessary, you can create a list using the list() constructor.

thislist = list( ("a", "b", "c", "d") )


print ( type(thislist) )
output = <class 'list'>

You might also like