Python | Python basics

Python implementation

  1. Python calculates the sum of factorials from 1 to 10
  2. Python implements nine-nine multiplication table
  3. python Fibonacci sequence
# python计算1~10的阶乘之和
if __name__ == '__main__':
    def factorial(num1):
        if num1 == 1:
            return 1
        return num1 * factorial(num1 - 1)


    sum1 = 0
    for i in range(1, 10):
        num = factorial(i)
        sum1 += num
    print("1~10的阶乘之和为%s" % sum1)
# python 实现九九乘法表
if __name__ == '__main__':
    for i in range(1, 10):
        for k in range(1, i + 1):
            print("%s * %s = %s" % (k, i, k * i), end=" ")
        print()
# python 斐波那契数列
if __name__ == '__main__':

    def fibonacci(n):
        a, b, count = 0, 1, 1
        while True:
            if count > n:
                return
            a, b = b, a + b
            yield a
            count += 1


    g = fibonacci(10)
    for i in g:
        print(i)

Python object-oriented-inheritance

class People:
    name = ''
    age = 0

    def __init__(self, n, a):
        self.name = n
        self.age = a


class Student(People):
    name = ''
    age = 0
    profession = ''

    def __init__(self, n, a, p):
        People.__init__(self, n, a)
        self.profession = p


if __name__ == '__main__':
    student = Student("小明", 19, '计算机')
    name = student.name
    age = student.age
    profession = student.profession
    print("%s %s %s" % (name, age, profession))

Python network programming

server

import socket

if __name__ == '__main__':
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 8888
    s.bind((host, port))
    s.listen(5)
    while True:
        clientSocket, address = s.accept()
        print("连接地址:%s" % str(address))
        msg = "欢迎访问"
        clientSocket.send(msg.encode("utf-8"))
        clientSocket.close()

Client

import socket

if __name__ == '__main__':
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 8888
    s.connect((host, port))
    msg = s.recv(1024)
    s.close()
    print(msg.decode("utf-8"))

Guess you like

Origin blog.csdn.net/y1534414425/article/details/106473727