Python foundation leveling Raiders: day01

If you have enough time to do something, it will be better at.

Knowledge points:

  • Computer Basics
  • variable
  • Operators
  • The if statement
  • for-in loop
  • function
  • Lists, tuples, dictionaries, strings, collections

ascii, unicode, utf-8, gbk difference

ASCII主要用于显示现代英语和其他西欧语言,规定了128个字符的编码,使用一个字节编码,不支持中文;
GBK编码是对GB2312的扩展,完全兼容GB2312。采用双字节编码方案,剔出xx7F码位,共23940个码位,共收录汉字和图形符号21886个;
Unicode为世界上所有字符都分配了一个唯一的数字编号,采用4个字节编码,意味着一个英文字符本来只需要1个字节,而在Unicode编码体系下需要4个字节,其余3个字节为空,这就导致资源的浪费;
UTF-8是一种针对Unicode的可变长度字符编码,又称万国码,用1到6个字节编码UNICODE字符;

Enter the year is not a leap year judgment.

year = int(input('请输入年份: '))
is_leap = (year % 4 == 0 and year % 100 != 0 or
           year % 400 == 0)
print(is_leap)

Percentile scores turn hierarchy

Percentile score score transfected hierarchy
than 90 points -> A, 80 minutes to 89 minutes -> B, 70 minutes to 79 minutes -> C, 60 minutes to 69 minutes -> D, 60 minutes or less -> E

score = float(input('请输入成绩: '))
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'E'
print('对应的等级是:', grade)

1 with the for-loop 100 sums

sum = 0
for x in range(101):
    sum += x
print(sum)

Determining a number of the input is not a prime number.

from math import sqrt

num = int(input('请输入一个正整数: '))
end = int(sqrt(num))
is_prime = True
for x in range(2, end + 1):
    if num % x == 0:
        is_prime = False
        break
if is_prime and num != 1:
    print('%d是素数' % num)
else:
    print('%d不是素数' % num)

Calculated greatest common divisor of two integers positive input and the least common multiple

x = int(input('x = '))
y = int(input('y = '))
if x > y:
    x, y = y, x
for factor in range(x, 0, -1):
    if x % factor == 0 and y % factor == 0:
        print('%d和%d的最大公约数是%d' % (x, y, factor))
        print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor))
        break

And function calculating achieve greatest common divisor of the least common multiple

def gcd(x, y):
    (x, y) = (y, x) if x > y else (x, y)
    for factor in range(x, 0, -1):
        if x % factor == 0 and y % factor == 0:
            return factor


def lcm(x, y):
    return x * y // gcd(x, y)

The number is not determined to achieve a function of the number of palindromic

def is_palindrome(num):
    temp = num
    total = 0
    while temp > 0:
        total = total * 10 + temp % 10
        temp //= 10
    return total == num

Implement a function to determine the number is not a prime number

def is_prime(num):
    for factor in range(2, num):
        if num % factor == 0:
            return False
    return True if num != 1 else False

Write a program that determines whether the input is a positive integer not palindromic prime

if __name__ == '__main__':
    num = int(input('请输入正整数: '))
    if is_palindrome(num) and is_prime(num):
        print('%d是回文素数' % num)

Marquee display text on the screen

import os
import time


def main():
    content = '北京欢迎你为你开天辟地…………'
    while True:
        # 清理屏幕上的输出
        os.system('cls')  # os.system('clear')
        print(content)
        # 休眠200毫秒
        time.sleep(0.2)
        content = content[1:] + content[0]


if __name__ == '__main__':
    main()

Generating a design function specified length codes, codes composed of uppercase and lowercase letters and numbers

import random


def generate_code(code_len=4):
    """
    生成指定长度的验证码

    :param code_len: 验证码的长度(默认4个字符)

    :return: 由大小写英文字母和数字构成的随机验证码
    """
    all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    last_pos = len(all_chars) - 1
    code = ''
    for _ in range(code_len):
        index = random.randint(0, last_pos)
        code += all_chars[index]
    return code

Evaluates the specified date is the first few days of the year

def is_leap_year(year):
    """
    判断指定的年份是不是闰年

    :param year: 年份
    :return: 闰年返回True平年返回False
    """
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0


def which_day(year, month, date):
    """
    计算传入的日期是这一年的第几天

    :param year: 年
    :param month: 月
    :param date: 日
    :return: 第几天
    """
    days_of_month = [
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    ][is_leap_year(year)]
    total = 0
    for index in range(month - 1):
        total += days_of_month[index]
    return total + date


def main():
    print(which_day(1980, 11, 28))
    print(which_day(1981, 12, 31))
    print(which_day(2018, 1, 1))
    print(which_day(2016, 3, 1))


if __name__ == '__main__':
    main()

Print Pascal's Triangle

def main():
    num = int(input('Number of rows: '))
    yh = [[]] * num
    for row in range(len(yh)):
        yh[row] = [None] * (row + 1)
        for col in range(len(yh[row])):
            if col == 0 or col == row:
                yh[row][col] = 1
            else:
                yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
            print(yh[row][col], end='\t')
        print()


if __name__ == '__main__':
    main()

Pick color ball

from random import randrange, randint, sample


def display(balls):
    """
    输出列表中的双色球号码
    """
    for index, ball in enumerate(balls):
        if index == len(balls) - 1:
            print('|', end=' ')
        print('%02d' % ball, end=' ')
    print()


def random_select():
    """
    随机选择一组号码
    """
    red_balls = [x for x in range(1, 34)]
    selected_balls = []
    selected_balls = sample(red_balls, 6)
    selected_balls.sort()
    selected_balls.append(randint(1, 16))
    return selected_balls


def main():
    n = int(input('机选几注: '))
    for _ in range(n):
        display(random_select())


if __name__ == '__main__':
    main()

Write function, the calculation of numeric strings, letters, spaces, and other incoming number, and returns the result

def func(s):
    dict = {'num': 0, 'alpha': 0, 'space': 0, 'other': 0}
    for i in s:
        if i.isdigit():
            dict['num'] += 1
        elif i.isalpha():
            dict['alpha'] += 1
        elif i.isspace():
            dict['space'] += 1
        else:
            dict['other'] += 1
    return dict

a = input('请输入字符串:')
print(func(a))

Write function, the user checks the incoming objects (strings, lists, tuples) of each element if it contains empty content, and returns the result

def func(s):
    if type(s) is str and s:
        for i in s:
            if i == ' ':
                return True
    elif type(s) is list or type(s) is tuple:
        for i in s:
            if not i:
                return True
    elif not s:
        return True

a = input('请传入对象(字符串、列表、元组):')
print(func(a))

Guess you like

Origin www.cnblogs.com/Rohn/p/10987639.html