python学习(anaconda)

Anaconda prompt

-conda list
-pip install *
-conda install *

problems & solutions

Description : when download did not go successfully.

Created with Raphaël 2.2.0 start step1 step2 step3 step4 step5 end

step1 : something unexpected occurred in this command.
step2 : go to Python Extension Packages for Windows.
step3 : press Ctrl+F to use the package name to find the binaries.
step4 : download the necessary binaries.
step5 : pip install package name.

Jupyter NoteBook

Calculation of numbers

Order

  • ( )
  • [**]
  • */
  • ±

Transference

type(*) -> to show the data type of *
a = int(b)
a = str(c)
a = float(d) 

abs(a)
round(a)
min(a,b,c)
max(a,b,c)

1.3e-5
1.3e5
bool

Character

test2 = 'hello '+'girls'
test3 = test2 * 3
len(test)

test4 = '1 2 3 4 5'
test4.split()
test4 = '1,2,3,4,5'
test = test4.spilt(',')

test5 = ''
test5.join(test)

test6 = 'very difficult'
test6.replace('difficult','easy')
test6.upper()
test6.lower()

test7 = '   so sophisticated   '
test.strip()
test.lstrip()
test.rstrip()

'{} {} {}'.format('liu','jia','qing')
'{2} {1} {0}'.format('liu','jia','qing')
'{liu} {jia} {qing}'.format(liu=11,jia=12,qing=13)

cool = 'liu jia qing :'
b = 666.0
c = 666
result = '%s %f %d' % (cool,b,c)

Index

test = 'you are extremely cool!'
test[n]    -> -len(test)<n<len(test)

test[a:b]  -> [a,b)
test[a:]   -> [a,len(test))
test[:b]   -> [0,b)
test[a,-c] -> [a,-c)
test[:]    -> print total length
tesst[::a] -> print a value every a numbers of length

List

definition

test = []
test = [1,2,3,4]
test = ['1','2','3','4']
test = [1,'liu',3.5]

test2 = list()
test2 = list([1,2,3])

operation

a = [123,456]
b = ['jia','qing']

len(a)
a+b -> join the two lists to become a longer one
a*3

···[index operating]
a[n] = 789
a[:] = ['jia','qing'] -> exchang the value

c = [1,2,3,4,5,6,7]
del c[0] -> take care not to lose significant data by mistake
3 in c : bool -> check whether the selected value is in the list
10 not in c : bool

d = [1,2,[3,4]] -> list of list
d[2]
d[2][1]

fruit = ['hawthorn','kiwi','hawthorn','pineapple','hawthorn','kiwi','kiwi','kiwi','hawthorn']
fruit.count('hawthorn')
fruit.index('pineapple')

pot = ['cacti','money plant','spider plant']
pot.append('succulents')
pot.append(['soil','water'])
pot.insert(2,'peach blossom') -> insert a value in the index 2 while others (including the initial value in the index 2)behind will move backward one position.
pot.remove(['soil','water'])
pot.pop(1)

nums = [1,2,45,6,21,44,55]
nums.sort()
orders = sorted(nums)

name = ['liu','jia','qing']
name.reverse()

Dictionary

Definition

key - value

test = {}
test = dict()
Operation
plant = {}
fruit = {'pitaya':red,'kiwi':green}
vegetable = {'eggplant':purple,'potato':yellow}
plant['fruit'] = fruit
plant['vegetable'] = vegetable

plant = dict([('succulents',123),('flowers',456)])

plant.get('fruit')
plant['fruit']
plant.get('trees',0)
plant.pop(fruit)
del plant['vegetable']

data1 = {'name':123,'age':177}
data2 = {'name':456,'height':155}
data1.update(data2)

'name' in data1 -> ttue
'marriage' in data1 -> false

data1.keys()
data1.values()
data1.items()

Set

test = [123,123,456,789]
test = set(test)

test2 = set([123,123,456,456,789])

test3 = {123,123,456,456,789}
Operation
a = {1,2,3,4}
b = {2,3,4,5}
a.union(b)
b.union(a)
a|b
a.intersection(b)
b.intersection(a)
a&b
a.difference(b)
b.difference(a)
a-b
b-a

a = {1,2,3,4,5}
b = {2,3,4}
a.issubset(b)
b.issubset(a)
b <= a
b > a
a <= a
a < a

a = {1,2,3,4}
a.add(5)
a.update([4,5,6])
a.remove(1)
a.pop()

Mechanism of Assignment

liu = 1000
qing = liu
id(liu)
id(qing)
liu is qing -> true
qing = 1234
id(qing)
liu is qing -> flase

test1 = 1000
test2 = 1000
id(test1)
id(test2) -> different

test1 = 1
test2 = 1
id(test1)
id(test2) -> same

Structure of Judgment

  • colon -> sign( : )
  • indents
number = 100
if number > 50:
	print('yes')	-> {} is not necessary,indent is needed

number = 50
if number >100:	
	print('yes')
elif number <=100:
	print('no')
else:
	print('error')	

datas = [123,456,789]
if 123 in datas:
	print('yes')

datas = {'number':123,'name':456}
if 'number' in datas:
	print('yes')

Structure of Loop

num = 0
while num<10:
	print(num)
	num += 1

datas = {'liu','jia','qing'}
while datas:
	data = datas.pop()
	print(data)
	
datas = {'liu','jia','qing'}
for name in datas:	-> another way to travel datas
	print(name)

datas = [123,456,531,4651051,5648]
for i in range(len(datas)):
	print(datas[i])
	
datas = [10,11,12,13,14]
for i in datas:
	if i%2 == 0:
		print(i)
	else: 
		continue | break -> notice the difference
	print(i)

Function

def add_ab(a,b):
	print(a+b)

def add_value(a,b):
	return(a+b)
c = add_value(1,2) -> 3

def add_value(a=3,b=5) -> initialize the values
	return(a+b)
c = add_value()
c = add_value(5)
c = add_value(5,5)

def add_num(a,*args):
	for i in args:
		a+=i
	return a

def add_num2(**kwargs):
	for arg,value in kwargs.items():
		print(arg,value)

def add_num3(a,*args):
	b=0;
	for i in args:
		a+=i
		b+=a
		return a,b
a,b = add_num3(1,2,3)
c = add_num3(1,2,3,4) -> c=(a,b)

Module & Package

%%writefile test.py
test_v = 10
def test_add(test_list):
	test_sum = 0
	for i in range(len(test_list)):
		test_sum += test_list[i]
	return test_sum
test_list = [1,2,3,4,5]
print(test_add(test_list)) -> to notice the difference of import test

%run test.py

import test -> notice the difference between first and second import

import test as t
test_list = [12,13,14]
t.test_add(test_list)
t.test_v

from test import test_v,test_add
test_v
test_add(test_list)

from test import *

Exception Management

  • try:
  • except:
  • finally:
try:
	1/0
except:   # It can also except exact error by using the 'except' + error's name. 
	print('error')
finally:
	print('runned')

class myError(ValueError): # to define a necessary error as you design
    pass
cur_list = ['liu','jia','qing']
while True:
    cur_input = input('Guess the value in the list:')
    if cur_input not in cur_list:
        raise myError('Wrong answer occurs: %s' %cur_input)
		

File Operation

%%writefile data.txt
Read
txt = open('./data.txt')
txt_r = txt.read()
print(txt_r)

txt.tell()
txt.seek(0) # to redirect and initialize the position of the index 

txt_l = txt.readline()
print(type(txt_l))
print(txt_l)
for line in txt_l:
	print(line)

txt.close()
Write
txt = open('data.txt','w')
for i in range(10):
	txt.write(str(i)+'\n')
txt.close()
txt2 = open('data.txt','r')
print(txt2.read())
txt2.close()

txt = open('day16.txt','w')
try:
    for i in range(100):
        10/(i-50)
        txt.write(str(i)+'\n')
except Exception:
    print('error',i)
finally:
    txt.close() # use 'finally' to assure to close the file

with open('day16.txt','w') as f:
    f.write('you are the best')  # do not have to close the file
	

Class

Definition
class people:
	'help information:This is a people'
	number=100
	def __init__(self,name,age):
		self.name = name
		self.age = age
	def display(self):
		print('number is '+people.number)
	def display_name(self):
		print('name is '+self.name)
Operation
people.__doc__

p1 = people('Jay',23)
p2 = people('Qing',24)

del p2.name
delattr(p2,'name')

hasattr(p1,'name')
getattr(p1.'name')

setattr(p1,'name','JayQ')
p1.name='JayJQ'

print(people.__doc__)
print(people.__name__)
print(people.__module__)
print(people.__bases__)
print(people.__dict__)

class Parent:
    number = 100
    def __init__(self):
        print('use the parent function')
    def parentM(self):
        print('use the parent method')
    def setAttr(self,attr):
        Parent.parentAttr = attr
    def getAttr(self):
        print('parent value: ', Parent.parentAttr)
    def newM(self):
        print('the parent method which is needed to be rewritten')
        
class child(Parent):
    def __init__(self):
        print('use the subclass function')
    def childM(self):
        print('use the subclass method')
    def newM(self):
        print('changed')

c = child()
c.childM()
c.parentM()
c.setAttr(100)
c.getAttr()
c.newM()

Time

import time

print(time.time())

print(time.localtime(time.time()))

print(time.asctime(time.localtime(time.time())))

print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))

import calendar
print(calendar.month(2017,11))
print(help(calendar.month))

·

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值