python 学习第四周(20201130)书写规范学习

本文探讨了Python编程中的重要原则'所见即所得',强调了命名规则的正确性。作者分享了避免使用 '_' 连字符命名模块的问题,并提倡使用4个空格代替tab,以及如何优化代码结构以提高可读性和可视化效果。内容涵盖了语句作用、命名空间管理、异常处理和常用语法实例。
摘要由CSDN通过智能技术生成

What you see is what you get. 所见即所得
自己得规范性和可读性,这是最重要基本功。

自我反省一下:
问题1、原来很喜欢用 xxx_xxx.py来命名,发现这个是一个重大的错误,如果带_命名模块无法自己自行调用,还有其他问题,共勉。
问题2:4空格和tab 不要同时使用,建议4个空格,个人喜欢。合理跨行,力争可视化,保持简单。

print('========python所见即所得============')
# What you see is what you get. 规范性和可读性,这是最重要基本功。
# 4空格和tab 不要同时使用,建议4个空格,个人喜欢。合理跨行,力争可视化,保持简单。
print('========python常用语法============')
"""
来源:python学习手册 page276-277。
continue表示跳过后面的程序,重新循环; 而pass表示站位,什么也不做,后面的代码(else之前)还是会执行。
语句         角色          例子
赋值         创建引用值     a, b, c ='good', 'bad', 'ugly'
调用         执行函数       log.write("spam, ham")
打印调用      打印对象       print ('The Killer', joke)
if/elif/else 选择动作      if "python"in text:
                              print(text)
for/else    序列迭代       for x in mylist:
                             print(x)
while/else   一般循环      while X>Y:
                             print('hello')
pass          空占位符     while True:
                            pass
break         循环退出     while True:
                             if exittest(): break
continue     循环继续      while True:
                             if skiptest(): continue
def          函数和方法    def(a, b,c=1, *d):
                            print(a+b+c+d[o])
return       函数结果      def f(a, b, c=1, *d):
                             return a+b+c+d[0]
yield       生成器函数     def gen(n):
                             for in n: yield i*2
"""

"""
表10-1: Python语句(续)
语句            角色             例子
global      命名空间            x ='old'
                               def function():
                                  global x, y; x ='new'
nonlocal    Namespaces(3.0+)   def outer():
           命名空间(Python3.0及     x='old'
           其以上版本)               def function():
                                       nonlocal x; x ='new'
import      模块访问            import sys
from        属性访问            from sys import stdin
class       创建对象            class Subclass(Superclass):
                                  staticData=[]
                                  def method(self): pass
try/except/ finally捕捉异常     try:
                                   action()
                               except:
                                   print ('action error')
raise        触发异常           raise EndSearch(location)
assert       调试检查           assert X>Y, 'X too small'
with/as      环境管理器(2.6)     with open('data') as myfile:
                                    process(myfile)
del          删除引用            del data[k]
                                del data[i:j]
                                del obj.attr
                                del variable
"""

#continue表示跳过后面的程序,重新循环,而pass表示占位,什么也不做,后面的代码(else之前)还是会执行。
a = 'python'
i = 2
for element in a:
    if element == 'y':
        pass
        i = 3    #pass占位
    else:
        print('pass:',element + str(i))

a = 'python'
i = 2
for element in a:
    if element == 'y':
        continue
        i = 3
    else:
        print('continue:',element + str(i))


print('========python输入英文自动词首字母大写,以下内容都可以按段复制运行============')
# while True:
#     reply = input('Enter Reply:')
#     if reply =='stop':
#         break
#     print(reply.title())

# while True:
#     reply = input('Enter Reply:')
#     if reply =='stop':
#         break
#     print(reply.title())
# print('Goodbye!!!')

#求数值平方,通用模式,但是一般python不采取这个
# while True:
#     reply = input('Enter Reply:')
#     if reply =='stop':
#         break
#     elif not reply.isdigit():
#         print('输入错误,请重新输入有效数字!') #事先用isdigit方法检查输入字符串内容
#     else:
#         print(int(reply)**2)
# print('Bye! See you next time.')

print('========输入内容,英文首字母转大写,数字求平方,暂时不支持组合============')
# while True:
#     reply = input('Enter Reply:')
#     if reply =='stop':
#         break
#     elif reply.isalpha():   #是否有字母, isalnum()书否为数字或者字母
#         print(reply.title())
#     else:
#         if not reply.isdigit():  #是否为数字
#             print('输入错误,请重新输入有效内容!')  # 事先用isdigit方法检查输入字符串内容
#         else:
#             print(int(reply)**2)
# print('Bye! See you next time.')

print('========输入内容,任意数值,求素数(或质数)之和,个数和清单============')
num = int(input('输入任意的数值num,求2-num之间所有的素数:'))
list_sum=0
list_num=[]
for i in range(2,num+1):
    for j in range(2,i):
        if i%j==0:
            break
    else:
        # print(i,'是素数。')
        list_num.append(i) #list_num =list_num+[i]
        list_sum += i  #list_num=list_num+i
print('2-%d素数之和为:%d,素数总个数为:%d。'%(num,list_sum,len(list_num)))
print('2-%d之间的素数为:'%num,list_num)

print('========赋值学习============')
nudge = 1
wink = 2
A,B = nudge,wink
print(A,B)
[C,D]= [nudge,wink]
print(C,D)

nudge = 1
wink = 2
nudge,wink = wink,nudge
print(nudge,wink)

[a,b,c] = (1,2,3)
print(a,c)
(a,b,c)='ABC'
print(a,c)

print('========高级序列赋值语句模式============')
# string = 'SPAM'
# a,b,c,d,e = string
# print(a,d,e)

string = 'SPAM'
a,b,c,d = string #见上语句无法运行,因为无足够位置
print(a,d)

string1 = 'spam'
a,b,c,d=string1
a,b,c = string1[0],string1[1],string1[2:]
print(a,b,c)

a,b =string1[:2]
c=string1[2:]
print('a,b,c分别为:',a,b,c)

a,b,c = list(string1[:2])+[string1[2:]]  #注意括号限制 还有加号
print(a,b,c)

(a,b),c=string1[:2],string1[2:]
print('a,b,c分别为2:',a,b,c)

(a,b),c=('sp','am')
print(a,b,c)

red,green,blue = range(3)
print(red,green,blue)
print(list(range(3)))

l11= [1,2,3,4,5]
while l11:
    front,l11 = l11[0],l11[1:]
    print(front,l11)

a,*b='spam'
print('b为:',b)

a,*b,c='spam'
print('b2为:',b)

l12 =[1,2,3,4,5]
while l12:
    front,*l12=l12
    print(front,l12) #与上面l11等价

seq=[1,2,3,4]
a,b,c,*d = seq
print('a,b,c,d为:',a,b,c,d)

# *a=seq   #错误
# print(a)

# a,*b,c,*d =seq  #错误
# print(a,b,c,d)

*a,=seq
print('*a,为:',a)

"""
如果有多个带星号的名称,或者如果值少了而没有带星号的名称(像前面一
样),以及如果带星号的名称自身没有编写到一个列表中,都将会引发错误:
"""

print('========应用于for============')
for (a,b,c) in [(1,2,3),(5,6,7)]:
    print(a,c)
print('========多目标赋值及共享引用============')
a=b=c='spam'
print(a,b,c)

print('========增强赋值及共享引用============')
L=[1,2]
M=L
L=L+[3,4]
print(L,M)

L=[1,2]
M=L
L+=[3,4]
print(L,M)
#注意以上对比: += 对列表原处做修改,  + 完全合并,生成新的对象

"""
变量命名规则
介绍了赋值语句后,可以对变量名的使用做更正式的介绍。在 Python中,当为变量名赋
值时,变量名就会存在。但是,为程序中的事物选择变量名时,要遵循如下规则。
语法:(下划线或字母)+(任意数目的字母、数字或下划线)
变量名必须以下划线或字母开头,而后面接任意数目的字母、数字或下划线
spam、spam以及pam_1都是合法的变量名,但1_Spam、 spams以及#!则不是
分大小写:SPAM和spam并不同
 Python程序中区分大小写,包括创建的变量名以及保留字。例如,变量名和x指的
是两个不同的变量。就可移植性而言,大小写在导入的模块文件名中也很重要,即
使是在文件系统不分大小写的平台上也是如此。
禁止使用保留字
定义的变量名不能和 Python语言中有特殊意义的名称相同。例如,如果使用像
 class这样的变量名, Python会引发语法错误,但允许使用 kclass和 Class作为变量
 
"""

"""
表11-3: Python3.0中的保留字
 False class finally is
 return
 None
 continue for
 lambda try
 True
 def
 from
 nonlocal while
 and
 del
 global not
 with
 as
 elif
 if
 or
 yield
 assert else import pass
 break except in
 raise
"""

"""
命名惯例
除了这些规则外,还有一组命名惯例——这些并非是必要的规则,但一般在实际中都会遵守。例如,因为变量名前后有下划线时(例如,name),通常对 Python解释器都有特殊意义,你应该避免让变量名使用这种样式以下是Python遵循的一些惯例。
·以单一下划线开头的变量名(_x)不会被 from module import*语句导入。
前后有下划线的变量名(_x_)是系统定义的变量名,对解释器有特殊意义。
以两下划线开头、但结尾没有两个下划线的变量名(_x)是类的本地(“压缩”)变量。
·通过交互模式运行时,只有单个下划线的变量名(_)会保存最后表达式的结果。
"""

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老来学python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值