徐小玉的博客。
分类: Python/Ruby
2021-11-12 15:25:15
数据类型
浮点:
1.23e9=120000000
-0.000000012=0.12e-7
整数中间可以加横线:
10000000=10-000-000
字符用' ' 或 ”” 分割。
如果是单引号,可以“‘”
或者 ’ \‘ ’
\是普通的转意,通用。
r''可以不转义
print (r'This is a test about \' ,Yes!')
:This is a test about \' ,Yes!
如果不好阅读 '''...''' 也可以。
print('''Line1
... Line2
... Line3''')
布尔
And:
print(5>3 and 5>7)
_ Ture
Not:
>>> not 1 > 2
True
age=3
if age>=10:
print('Adult\n')
else:
print('Children\n')
+++++空值:NULL
除法:
/: 精确的。
//: 只取整数部分
%:得到余数
print (10/3)
print (70//10)
print(24%3)
print(29%7)
3.3333333333333335 7 0 1
ASCII、Unicode和UTF-8的关系,计算机系统通用的字符编码工作方式:
在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。
print('Python是可以支持中文的')
对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符:
print(ord('A'),'玩:',ord('玩'),chr(67),chr(29610))
bytes类型的数据: b' ' 或 b" "
Unicode字符串,用encode('')转为ByTes, 反向是decode('')
print('Hello'.encode('ascii'))
print('**'.encode('utf-8'))
#把bytes改成str
print(b'Christune'.decode('utf-8'))
print(b'\xe5\x82\xbb\xe9\x90\xbc'.decode('utf-8'))
List
Using [ ] to define:
MC_list=['Rob','Tyler','Ahmed']
print ('My Language partners are:')
print(MC_list)
输出:
My Language partners are:
['Rob', 'Tyler', ‘Ahmed']
好像不是想要的?
可以用下标获得内容。
print(MC_list[2])
长度函数:len
len(MC_list) 列表的元素数量
len(MC_list)-1: 最后一个的下标。
print(MC_list[len(MC_list)-1])
print(len(MC_list)-1)
MC_list[len(MC_list)-1]=MC_list[-1]:最后一个元素
append
to add a new element to the list:
MC_list.append(‘Hello’)
Insert (index,string)
To insert an element into the list to index positon
MC_list.insert(2,’Ken')
Pop()
To delete the last element
MC_list.pop()
pop(i)
To delete ith element
MC_list.pop(2)
Tuple
The fixed number list. Its element cannot be changed once it is defined. (using () to define)
MC_tuple=(M1,M2,M3)
If the only element is a number, it should be set as:
MC_t2=(3,):
Since it will be regarded as the number 3 instead of a tuple.
Conditions:
If contends:
The result..
Elif:
The things caused
Else:
What it will be .
print('How Old are you?')
age=input()
if age<=40:
print('you are',age,'years old.You must be uslesss')
print('But you still have lots of opportunities.')
elif age<=41:
print('No worries, you might still have chance in your life')
else:
print("you are",age," years old alreadt. You are as good as dead.”)
Loops:
For…in…
print ('My Language partners in for--in loop are:')
for MC_for in MC_list:
print(MC_for)
# to add 1 - 10
sum=0
for i in (1,2,3,4,5,6,7,8,9,10):
sum=sum+i
print('Now,time to show the turth,1++10 is:')
print(sum)
Range
Function random will generate a list of integer numbers.
range(101): will generate 1…100
sum=0
for i in range(101):
# print(i)
sum=sum+i
print('Now,time to show the turth,1++100 is:')
print(sum)
====5050
While loop:
To count the odd and even numbers below 100:
print ('The total of even integer numbers between 0-100 is:')
sum=0
number=100
while number>0:
sum=sum+number
number=number-2
print(sum)
==2550
print ('The total of odd integer numbers between 0-100 is:')
sum=0
number=99
while number>0:
sum=sum+number
number=number-2
print(sum)
===2500
Continue in a loop:
print ('To demestrate the function of continue in a while loop')
print ('The total of odd integer numbers between 0-100 is:')
sum=0
number=100
while number>0:
number=number-1
if number % 2 == 0:
continue
sum=sum+number
print(sum)
=2500
Dict of dictionary:
A structure similar to perl’s hash : key-value. Using {} to define.
Using in to test the existence. get() also works the same. But get(‘key’,93), 93 is the resulting number. ATTENTION, get() is not for inserting!! Only for checking if an element exists or not.
Pop function is used to delete a key-value pair: pop(key)
MC_dict={'Ken':62,'Ahmed':52,'Robert':39,'Tyler':35}
print("Hello Tyler,how old are you?")
print(MC_dict['Tyler'])
print('use "in" to test if a key exist.')
if 'Ken' in MC_dict:
print('Hello Ken, you are:')
print(MC_dict['Ken'])
else:
print('no Ken1 in thd dict.Plese double check.')
print('use "get" to test the existence or to insert an element if notavaliable.')
if MC_dict.get('Ken1'):
print('Hello Ken, you are:')
print(MC_dict['Ken'])
else:
print(MC_dict.get('Ken1',63))
print('Hello Ken1, You are getting older,hahaha.')
#print(MC_dict[‘Ken1'])
Set:
It saves key but not values. It will delete the repeated keys. It id defined by a list:
MC_set=set([1,2,3])
You could add as many the same keys as possible, but only one will be saved.
Using add to add new keys. To use remove to remove keys.
MC_set.add(‘Vert')
MC_set.remove(7)
MC_set=set([1,2,3,4,5,6,6,6,4,3])
#PUTPUT:set([1, 2, 3, 4, 5, 6])
print('This is Set MC_set. its elemesnt are:')
print(MC_set)
print('I am going to add new elment. I\'m going to add many times. But i guess it won\'y work?')
MC_set.add('Vert')
MC_set.add('Rough')
MC_set.add('Vert')
MC_set.add('Rough')
MC_set.add('Rough')
MC_set.add(8)
MC_set.add(7)
MC_set.add(7)
MC_set.add(7)
print(MC_set)
#=== OUTPUT:set([1, 2, 3, 4, 5, 6, 7, 8, 'Rough', 'Vert'])
print('to remove with function remove:')
MC_set.remove(7)
print(MC_set)
For this feature( no duplicate keys), it is useful for realizing the mathematic operations or AND or Either:
print('To use set to realise the AND and OR:')
MC_set1=set([10,20,30,40,50,60])
MC_set2=set([10,70])
print("NOW Either")
##10
print(MC_set1 | MC_set2)
print('NOW BOTH')
print(MC_set1 & MC_set2)
##set([50, 20, 70, 40, 10, 60, 30])
MC_set1=set(['Bleu','Rough','Rough','Black'])
MC_set2=set(['Black','Red'])
print("NOW Either")
print(MC_set1 | MC_set2)
#set(['Bleu', 'Rough', 'Black', 'Red'])
print('NOW BOTH')
print(MC_set1 & MC_set2)
# Black
Functions
print(abs(-23))
print(min(1,3,5,4,2,4,3,2,3,3))
print(max(1,3,5,4,2,4,3,2,3,3,95736))
To define a function:
def name(arguments):
function realises
Return ???
def MC_abs(x):
if x>0:
return x
else:
return -x
print ("-256 abs is:")
print(MC_abs(-256))
Non Function:
Pass:
print('\n------\nIt\'s time for None function:pass:\n----\n')
def MC_non():
pass
MC_pass=42
if MC_pass>42:
pass
else:
print('You are so old.')
It doesn’t check arugment types unless you define it. The built-in abs is checking, but the own-defined not yet….( pay attention it later//..)
print('checking canshu:')
print(abs(-23))
#print(abs('-23'))
print('And how about my funtion MC_abs?')
print(MC_abs('-256')) # NON, it doesnt cheak type... BAD bad bad.
To have more than one returned results:
To import a function:
print('To have more than one returns')
import math
def MC_move(x,y,step,angle=0):
mc_x=x+step*math.cos(angle)
mc_y=y-step+math.sin(angle)
return mc_x,mc_y
print (MC_move(60,80,30,math.pi/7))
print(math.pi)
The positional arguments:位置参数
计算平方
# positional arguments:
print ('The square of x:')
def MC_power(x):
return x*x
print(MC_power(5))
多加进去一个参数,想计算几次方,就计算几次方。多加一个位置参数。
# to define two positional arguments to handle any times power .
print ('The power of x:')
def MC_power(x,n):
s=1
while n>0:
n=n-1
s=s*x
return s
print(MC_power(2,12))
Default Argument:默认参数:
如果不指定,默认就是计算平方,如果指定了,才会具体计算指定的次方数
# the default argument:
print ('The default argument in power function :')
def MC_power(x,n=2):
s=1
while n>0:
n=n-1
s=s*x
return s
print(MC_power(2,9))
print(MC_power(9))
可变参数。
# 这是需要用一个list的方式作为输入的。(计算平方和)
# to calcuate the total of square of a2+b2...."
print(" the total of square of a2+b2(1-10)....")
def MC_cal_sqr(numbers):
s=0
for n in numbers:
s=s+n*n
return s
print(MC_cal_sqr([1,2,3,4,5,6,7,8,9,10]))
#但如果定义成可变参数,就简单多了 *
# to upgrade this funtion using chaning? argument *
print(" the total of square of (1-10) with using various arguments....")
def MC_cal_sqr(*numbers):
s=0
for n in numbers:
s=s+n*n
return s
print(MC_cal_sqr(1,2,3,4,5,6,7,8,9,10))
#如果想用一个list做输出参数,也可以这样把它变成一个可变参数:
# to change a list of items into a various argument.
print('to change a list of items into a various argument *')
chaning_list=[1,2,3,4,5,6,7,8,9,10]
print(MC_cal_sqr(*chaning_list))
关键字参数,想输入几个都可以的 **
#key arguments **
print('Key Arguments:')
def MC_keyv(name,age,**extra):
print('name:',name, 'age:' ,age, 'other:', extra)
print(MC_keyv(‘Tyler’,'34',City='US',Hobby='eating'))
或者,把一个dict变成一个关键字参数输入进去:
# to use dict as a key argument:
MC_extra={'City':'Beijing','job':'waiting for Death','Hope':'Nothing'}
print(MC_keyv('MMCC','42',**MC_extra))
可是使用pass来验证关键字是否存在:
# to check if the key argument exsits:
def MC_keyv(name,age,**extra):
if 'City' in extra:
pass
if 'Hobby' in extra:
pass
print('name:',name, 'age:' ,age, 'other:', extra)
print(MC_keyv('Tyler','34',City='US',Hobby='eating'))
但无法杜绝输入其它关键字。所以使用 * ,指定输入的关键字必须是其后规定的。这就是命名关键字。
# to limit that only the listed argument are allowed
def MC_keyv(name,age,*,City,Hobby):
print('name:',name, 'age:' ,age, 'other:', extra)
print(MC_keyv('Tyler','34',City='US',Hobby='eating'))
参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
递归:
递归就是在函数里再调用其它函数:
print('\n------\nIt\'s time for 递归:\n----\n')
def fact(n):
if n==1:
return 1
return n*fact(n-1)
print ('Fact(4) is:')
print(fact(4))
但要注意防止栈溢出。可以通过尾递归优化来防治栈溢出