Python基础例子

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础例子相关的知识,希望对你有一定的参考价值。

编码风格

  • 使用 4 空格缩进,而非 TAB

    在小缩进(可以嵌套更深)和大缩进(更易读)之间,4空格是一个很好的折中。TAB 引发了一些混乱,最好弃用

  • 折行以确保其不会超过 79 个字符

    这有助于小显示器用户阅读,也可以让大显示器能并排显示几个代码文件

  • 使用空行分隔函数和类,以及函数中的大块代码

  • 可能的话,注释独占一行

  • 使用文档字符串

  • 把空格放到操作符两边,以及逗号后面,但是括号里侧不加空格:f(1, 2) g(3, 4)

  • 统一函数和类命名

    推荐类名用 驼峰命名, 函数和方法名用 小写_和_下划线。总是用 self 作为方法的第一个参数(关于类和方法的知识详见 初识类 )

  • 不要使用花哨的编码,如果你的代码的目的是要在国际化环境。Python 的默认情况下,UTF-8,甚至普通的 ASCII 总是工作的最好

  • 同样,也不要使用非 ASCII 字符的标识符,除非是不同语种的会阅读或者维护代码。

找素数

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, equals, x, *, n//x)
            break
    else:
        print(n, is a prime number)

        
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

找奇偶

for num in range(2, 10):
    if num % 2 == 0:
        print(Found an even number, num)
        continue
    print(Found a number, num)

    
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

一个能打印斐波那契的函数

>>> def fib(n):
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end =  )
        a, b = b, a+b
    print()

    
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 

带默认参数的函数

>>> def ask_ok(prompt, retries=4, complaint=Yes or no,Please!):
    while True:
        ok = input(prompt)
        if ok in (y, ye, yes):
            return True
        if ok in (n, no, nop, nope):
            return False
        retries = retries - 1
        if retries < 0:
            raise OSError(uncooperative user)
        print(complaint)

        
>>> ask_ok(Do you really want to quit?)
Do you really want to quit?what?
Yes or no,Please!
Do you really want to quit?yes
True

默认值只被赋值一次,当默认值是可变对象时会有所不同,比如列表、字典或者大多数类的实例。

例如,下面的函数在后续调用过程中会累积(前面)传给它的参数

>>> def f(a, L=[]):
    L.append(a)
    return L

>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>> 

关键字函数

>>> def parrot(voltage, state=a stiff, action=voom, type=Norwegian Blue):
    print("-- This parrot wouldn‘t", action, end= )
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It‘s", state, "!")

    
>>> parrot(1000)
-- This parrot wouldnt voom if you put 1000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- Its a stiff !
>>> parrot(a thousand, state=pushing up the daisies)
-- This parrot wouldnt voom if you put a thousand volts through it.
-- Lovely plumage, the Norwegian Blue
-- Its pushing up the daisies !

元组、字典的作为参数的函数

>>> def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I‘m sorry, we‘re all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    keys = sorted(keywords.keys())
    for kw in keys:
        print(kw, ":", keywords[kw])

        
>>> cheeseshop("Limburger", "It‘s very runny, sir.",
           "It‘s really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")
-- Do you have any Limburger ?
-- Im sorry, were all out of Limburger
Its very runny, sir.
Its really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

函数注解

对于参数的注解出现在紧随参数名之后的冒号之后

对于返回值,它们编写于紧跟在参数列表之后的一个 ->  之后.

>>> def func(a:‘spam‘,b:(1,10),c:float)->int:  
	return a+b+c

>>> func.__annotations__
{‘a‘: ‘spam‘, ‘b‘: (1, 10), ‘c‘: <class ‘float‘>, ‘return‘: <class ‘int‘>}

 

以上是关于Python基础例子的主要内容,如果未能解决你的问题,请参考以下文章

分享几个实用的代码片段(附代码例子)

Python基础例子

如何创建片段以重复变量编号中的代码行

有条件地导入 python 类的片段

python之基础篇——模块与包

[vscode]--HTML代码片段(基础版,reactvuejquery)