---
# System prepended metadata

title: Python studying memo
tags: [Python]

---

---
tags: Python
---
# Python studying memo
###### tags: `python`

## virtualenv

### create new virtual environment

```bash=
sudo apt-get install python3
sudo apt-get install python-pip
pip3 install --upgrade
pip3 install virtualenv
virtualenv -p python3 [virtual_environment_name] 
# ex: virtualenv -p python3 tf_2012_tf1_py3
# After that, it will create a folder named tf_2012_tf1_py3, and it contains two folders: bin and lib
```

### run in a created virtual environment

```bash=
. ./[vitrual_environment_name]/bin/activate
```

### exit virtual environment

```bash=
deactivate
```

## 精通Python 讀後筆記 (未完成)

### Note

I only read a little, because I may not used all of these content

### book_url_example

```python=
import webbrowser
import requests
import json
from urllib.request import urlopen

print("Let us find an old website.")

site = input("Type a website URL: ")
era = input("Type a year, month and a day, like 20150613: ")
url = "http://archive.org/wayback/available?url=%s&timestamp=%s" % (site, era)
response = urlopen(url)
contents = response.read()
text = contents.decode("utf-8")
data = json.loads(text)
try:
	old_site = data["archived_snapshots"]["closest"]["url"]
	print("Found this copy: ", old_site)
	print("It should appear in your browser now")
	webbrowser.open(old_site)
except:
	print("Sorry, no luck finding", site)
```

```python=
print("Let us find an old website.")

site = input("Type a website URL: ")
era = input("Type a year, month and a day, like 20150613: ")
url = "http://archive.org/wayback/available?url=%s&timestamp=%s" % (site, era)
response = requests.get(url)
data = response.json()
try:
	old_site = data["archived_snapshots"]["closest"]["url"]
	print("Found this copy: ", old_site)
	print("It should appear in your browser now")
	webbrowser.open(old_site)
except:
	print("Sorry, no luck finding", site)
```

### variable 

```python=
var_num = 123
type(var_num) # int

var_str = '456'
type(var_str) # str

print(var_num+int(var_str)) # output: 579 # (datatype: int)
print(str(var_num)+var_str) # output: 123456 # (datatype: str)
```

### print 

```python=
var_name = input('Your Name : ')
print('Your Name : ' + var_name)
```

### if-else 

```python=
var_money = input('Your Money : ')
if int(var_money) > 600:
	print('badminton')
elif int(var_money) < 600 and int(var_money) > 300: 
	print('eat')
else:
	print('go home and sleep')
```

### list 

```python=
spells = [
"Riddikulus!",
"Wingardium Leviosa!",
"Avada Kedavra!",
"Expecto Patronum!",
"Nox",
"Lumos",
]
print(spells[2]) # output: Acada Kedavra!
print(spells) # output: ['Riddikulus!', 'Wingardium Leviosa!', 'Avada Kedavra!', 'Expecto Patronum!', 'Nox', 'Lumos']
spells.append("Sectumsempra") # added var to 'last' place of list
print('after list.append, ', spells) # output: after list.append,  ['Riddikulus!', 'Wingardium Leviosa!', 'Avada Kedavra!', 'Expecto Patronum!', 'Nox', 'Lumos', 'Sectumsempra']
spells.insert(2,"Crucio") # added var to the place which you pointed to
print('after list.insert, ', spells) # output: ['Riddikulus!', 'Wingardium Leviosa!', 'Crucio', 'Avada Kedavra!', 'Expecto Patronum!', 'Nox', 'Lumos', 'Sectumsempra']
spells.pop() # if there is no parameter for list.pop method, it automaticly delected last value of the list
print('after list.pop, ', spells) # output: ['Riddikulus!', 'Wingardium Leviosa!', 'Crucio', 'Avada Kedavra!', 'Expecto Patronum!', 'Nox', 'Lumos']
del_num = 2
print('del_num : ', del_num)
spells.pop(del_num) # output: 'Crucio' # deleted list[2] value
print('after list', del_num,'.pop, ', spells) # output: ['Riddikulus!', 'Wingardium Leviosa!', 'Avada Kedavra!', 'Expecto Patronum!', 'Nox', 'Lumos']
spells.insert(0,"Avada Kedavra!") # input "Avada Kedavra" at list[0]
print('after list.insert, ', spells) # output: ['Avada Kedavra!', 'Riddikulus!', 'Wingardium Leviosa!', 'Avada Kedavra!', 'Expecto Patronum!', 'Nox', 'Lumos']
spells.remove("Avada Kedavra!") # delected all value "Avada Kedavra" in list
print('after list.remove, ', spells) # output: ['Riddikulus!', 'Wingardium Leviosa!', 'Avada Kedavra!', 'Expecto Patronum!', 'Nox', 'Lumos']
spells.clear() # clear the list
print(spells) # output: []
```

```python=
list_num = [
2,
5,
3,
8,
9,
22,
]
print(list_num[2]) # output: 3
print(list_num) # output: [2, 5, 3, 8, 9, 22]
list_num.append(15) # added var to last place of list
print('after list_num.append, ', list_num) # output: [2, 5, 3, 8, 9, 22, 15]
list_num.insert(2,16) # added var 16 to place 2 of list
print('after list_num.insert, ', list_num) # output: [2, 5, 16, 3, 8, 9, 22, 15]
print('max : ', max(list_num)) # output: max :  22
print('min : ', min(list_num)) # output: min :  2
print('sum : ', sum(list_num)) # output: sum :  80
print('list_num.length : ', len(list_num)) # output: list_num.length :  8
print('2nd to 4th place of list_num : ', list_num[1:4]) # output: 2nd to 4th place of list_num :  [5, 16, 3]
```

### for_loop 

```python=
for cnt in range(1, 10):
	print(cnt)
    """ 
    output: 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    """
print("\n")

for cnt in range(2, 20, 2):
	print(cnt)
    """
    output: 
    2
    4
    6
    8
    10
    12
    14
    16
    18
    """
print("\n")

for cnt in range(20, 2, -2):
	print(cnt)
    """
    output: 
    20
    18
    16
    14
    12
    10
    8
    6
    4
    """
    
for countdown in 5, 4, 3, 2, 1, "hey!!!":
	print(countdown)
    """result will be : 
    5
    4
    3
    2
    1
    hey!!!"""
```

### dictionary 

```python=
quotes = {
"Moe": "A wise guy, huhy?",
"Larry": "Ow!",
"Curly": "Nyuk nyuk!",
}
Name = "Larry"
print(Name, "says", quotes[Name]) # output: Larry says Ow!
```

### function 

```python=
def hello_world():
	print('hello world')

def print_variable(i):
	print('input variable : ',i)

def plus(a,b):
	c = (int(a) +int(b))
	print(a, '+', b, '=', c)

hello_world()
print_variable('500')
plus_one = 3
plus_two = 5
plus(plus_one, plus_two) # output: 3 + 5 = 8
```

### object 

```python=
class Animal():
	def set_age(self, age):
		self.age = age
	def say_my_age(self):
		print("My age is : ", self.age)
	def howl(self):
		print("HELLO PYTHON")

class Cat(Animal):
	def set_name(self, name):
		self.name = name
	def say_my_name(self):
		print("My name is : ", self.name)

cat_a = Cat()
cat_a.set_age('26')
cat_a.set_name('Tom')
cat_a.howl() # output: HELLO PYTHON
cat_a.say_my_age() # output: My age is :  26
cat_a.say_my_name() # My name is :  Tom
```

```python=
class Animal:
	def __init__(self, name, age):
		self.name = name
		self.age = age
	def move(self):
		print(str(self.name) + " moving")
	def showing_age(self):
		print(self.name + ' age: ' + self.age)

class Cat(Animal):
	def __init__(self, name, age):
		self.name = name
		self.age = age
	def sound(self):
		print(str(self.name) + " meow")
	def showing_age(self):
		print(self.name + ' age: ' + self.age)

def print_hello_world():
	print("Hello_World")

print("__name__ : " + str(__name__))
print_hello_world()

print("\n\n\n")

Tom = Cat('Tom', '28')
Tom.move()
Tom.showing_age()
Tom.sound()

print("\n\n\n")

Kevin = Animal('Kevin', '29')
Kevin.move()
Kevin.showing_age()
Kevin.sound()
"""

"""
```

### source
1.  https://kopu.chat/2017/01/18/%e4%b8%80%e5%b0%8f%e6%99%82python%e5%85%a5%e9%96%80-part-1/
2.  https://mofanpy.com/tutorials/python-basic/basic/

## python operators

### python Logical operators
```python=
a = 1
b = 2
result = (a == b)
if (result):
    print("result is true") # false => this part is not going to execute
if (not result):
    print("result is not true") # not false => this part is going to execute
if ((not result) and (a < 0)):
    print("result is not true and a is less than 0") # not false but a > 0 => this part is not going to execute
if (result or (b > 0)):
    print("result is true or b is more than 0") # false, however b > 0 => this part is going to execute
```

## if __name__ == '__main__':

file name: test.py
```python=
print(__name__)
print('I love Python')

def love():
    print('In function love, Python is Good')

if __name__ == '__main__':
    love()
    print('I wrote python everyday')
```

```bash=
python3 test.py
<< output: 

__main__
I love Python
In function love, Python is Good
I wrote python everyday

output: 
```

file name: import_test.py
```python=
import test
```

```bash=
python3 import_test.py

<< output: 

test
I love Python

output: 
```

only if __name__ == __main__, code in if __name__ ==  __main__ will be executed

### source
1. http://hn28082251.blogspot.com/2019/05/python-if-name-main.html

## def __init__

```python=
class Animal():
	def __init__(self, name):
		self.name = name

Lucky = Animal("Lucky")
print(Lucky.name) # output: Lucky

Unlucky = Animal()
print(Unlucky.name) # output: TypeError: __init__() missing 1 required positional argument: 'name'
```

def __init__ always executes when the object is declared

### source
1. https://weilihmen.medium.com/%E9%97%9C%E6%96%BCpython%E7%9A%84%E9%A1%9E%E5%88%A5-class-%E5%9F%BA%E6%9C%AC%E7%AF%87-5468812c58f2

## class a(b):
To describe it simply, object a inherit attribute of object b
http://yltang.net/tutorial/python/15/

## python _ __

### _function (sample code with bug)

plus one underscore in front of name of function, that means other programs outside can not use this function

Common.py
```python=
def _gcd_core(a, b):
    if a > b:
        return a
    else:
        return b

def find_cd(a):
    cd_list=[]
    for x in range(1, (a + 1)):
        ans = a % x
        if ans == 0:
            cd_list.append(x)
    return cd_list

print(find_cd(30)) # output: [1, 2, 3, 5, 6, 10, 15, 30]

print(_gcd_core(30, 7)) # output: 30
```

test.py
```python=
from Common import *
find_cd(30) # output: [1, 2, 3, 5, 6, 10, 15, 30]
_gcd_code(30,7) # output: 
"""
output: 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_gcd_code' is not defined
"""
```

https://medium.com/bits-to-blocks/python%E4%B8%AD%E7%9A%84underscore-%E8%88%87-9b40caf32483

### reference
https://www.w3schools.com/python/python_operators.asp

## pack python code to .exe

### reference
https://kknews.cc/zh-tw/code/ab2oy5n.html
