Python study notes five: basic knowledge summary

1. Variables and types

  • Commonly used data types:
    • Integer: There is only int in Python 3, and it supports binary (0b100 = 4), octal (0o100 = 8), decimal, and hexadecimal (0x100 = 256)
    • Floating point type: also called decimal, and supports scientific notation
    • String type: any text enclosed in single or double quotation marks, special usage: multiple lines of text can be written with three quotation marks
    • Boolean: 0 (false), true (1, 2, 3...)
    • Complex number type: Same as mathematical representation, the only difference is that the imaginary part i is replaced by j
#算术运算
a = 5
b = 2
print(a + b)  # 7
print(a - b)  # 3
print(a * b)  # 10
print(a / b)  # 2.5
print(a // b) # 2
print(a % b)  # 1
print(a ** b) # 25

Use type() to check the type of the variable:


a = 1
b = 3.14
c = 5 + 2j
d = 'Hello,World'
e = True
print(type(a))  # <class 'int'>
print(type(b))  # <class 'float'>
print(type(c))  # <class 'complex'>
print(type(d))  # <class 'str'>
print(type(e))  # <class 'bool'>

1.1 Variable type conversion

  • int(): Convert a numeric value or string to an integer
  • float(): Convert a string to a floating point number
  • str(): Convert the specified object into a string form, and the code can be specified
  • chr(): Convert an integer to the string corresponding to the code (a character)
  • ord(): Convert a string (a character) to the corresponding code (integer)
a = int(input('a = '))
b = int(input('b = '))
print('%d + %d = %d' % (a, b, a + b)) # %后面跟的变量值会替换掉占位符
print('%d - %d = %d' % (a, b, a - b))
print('%d * %d = %d' % (a, b, a * b))
print('%d / %d = %f' % (a, b, a / b))
print('%d // %d = %d' % (a, b, a // b))
print('%d %% %d = %d' % (a, b, a % b))
print('%d ** %d = %d' % (a, b, a ** b))
# 占位符语法:
# %d是整数的占位符
# %f是小数的占位符
# %%表示百分号

a = 1
b = 1
1 + 1 = 2
1 - 1 = 0
1 * 1 = 1
1 / 1 = 1.000000
1 // 1 = 1
1 % 1 = 0
1 ** 1 = 1

# 赋值运算符和复合赋值运算符
a = 2
b = 3
a += b     # 等于a = a + b
a *= a + 1 # 等于a = a * (a + 2)
print(a) 

30


Case 1: Convert Fahrenheit to Celsius

# 案例一:
# 华氏温度到摄氏温度的转换公式为:$C= (F - 32)/div 1.8$

F = float(input("请输入华氏温度:"))
C = (F - 32) / 1.8
print("%.1f华氏度 = %.1f摄氏度" % (F, C)) # 也可以使用:%

Please enter the temperature in Fahrenheit: 100
100.0 degrees Fahrenheit = 37.8 degrees Celsius

Case 2: Enter the radius of the circle to calculate the perimeter and area

# 案例二:
import math

r = float(input("请输入圆的半径:"))
perimeter = 2 * math.pi * r
area = math.pi * r ** 2
print("圆的周长为:%.2f" % perimeter)
print('圆的面积为:%.2f' % area)

Please enter the radius of the circle: 2
The perimeter of the circle is: 12.57
The area of ​​the circle: 12.57

Case 3: Enter the year to determine whether it is a leap year

#输入年份,如果是闰年输出true,否则为false

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

Branch structure

  • if statement
    • elif、else
    • Nested branch structure
  • Comparing the two cases, we can conclude that case 1 is easier to understand and run, indicating that flat is better than nested, that is, flat
    • Don't use nesting when you can use a flat structure
# 案例1:

a = input("输入关键字:")

if a == "1":
    print("yes")
else:
    print("no")
    
# 案例2:
# 分段函数求值:
"""
        3x - 5  (x > 1)
f(x) =  x + 2   (-1 <= x <= 1)
        5x + 3  (x < -1)

"""

x = float(input("x = "))

if x > 1:
    f = 3 * x -5
elif -1 <= x <= 1:
    f = x + 2
else:
    f = 5 * x +3
print('f(%.2f) = %.2f' % (x, f))

# 案例2:
# 嵌套的分支结构,完成上面的分段函数求值
# 双层嵌套

x = float(input('x =  '))

if x > 1:
    f = 3 * x - 5
else:
    if x >= -1:
        f = x + 2
    else:
        y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, f))

Case 3: Conversion of 100-point system scores to grade system scores

score = float(input("请输入成绩: "))

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("E")

Cyclic structure

  • for-in loop (used when the number of loops is known)
    • Usage of range:
      • range(101) generates a sequence of integers from 0 to 100
      • range(1, 100) generates a sequence of integers from 1 to 99
      • range(1, 100, 2) generates a sequence of numbers from 1 to 99, the step size is: 2
  • while loop (used when the number of loops is unknown)
    • break: terminate the loop where the break is located
    • continue: Abandon the subsequent code of this loop and directly let the loop enter the next round
# 循环求和
s = 0

for x in range(11):
    s += x
print(s)
# 双重循环嵌套
# 实现九九乘法表

for i in range(1, 10):
    for j in range(1, i+1):
        s = i * j
        print(s, end ="\t")
    print()

Case 1: Number of daffodils Case:

  • The daffodil number is a three-digit number, and the sum of the cubes of each digit on the number is equal to the three-digit number
for num in range(100,1000):
    fir = num % 100
    sec = num // 10 % 10 # 此处使用地板除
    thd = num // 100
    if num == fir ** 3 + sec ** 3 + thd ** 3:
        print(num)
        # 407

Case 2: Invert a positive integer (using a while loop)

  • For example: 123 becomes 321
num = int(input('num = '))
reversedNum = 0
while num > 0:
    
    # 首先,反转数字reversed_num为0
    # 被反转的数字每次将他的最低位数字给 reversedNum
    # 并且每次扩大10倍
    
    reversedNum = reversedNum * 10 + num % 10
    num //= 10
    
print(reversedNum)


Case 3: Craps gambling game (combining the above grammar to realize)

  • This game uses two dice, and players can play the game by shaking __two__ dice to get points.
  • game rules:
    • If the player rolls the dice for the first time at 7 or 11 points, the player wins
    • If the player rolls 2 points, 3 points or 12 points for the first time, the dealer wins
    • Other players continue to roll the dice
      • If the player rolls 7 points, the dealer wins
      • If the player rolls the first point, the player wins
      • For other points, the player continues to take the dice until the winner is determined
from random import randint

money = 1000
while money > 0:
    print('你的总资产为:', money)
    needs_go_on = False
    
    while True:
        debt = int(input('请下注: '))
        if 0 < debt <= money:
            break
            
    first = randint(1, 6) + randint(1, 6)
    print('玩家摇出了%d点' % first)
    
    if first == 7 or first == 11:
        print('玩家胜!')
        money += debt
    elif first == 2 or first == 3 or first == 12:
        print('庄家胜!')
        money -= debt
    else:
        needs_go_on = True
    while needs_go_on:
        needs_go_on = False
        current = randint(1, 6) + randint(1, 6)
        print('玩家摇出了%d点' % current)
        if current == 7:
            print('庄家胜')
            money -= debt
        elif current == first:
            print('玩家胜')
            money += debt
        else:
            needs_go_on = True
print('你破产了, 游戏结束!')

Case 4: Find all perfect numbers between 1 and 999

  • A perfect number is a number whose sum of all factors except itself is exactly equal to the number itself
  • For example: 6 = 1 + 2 + 3, 28 = 1 + 2 + 4 + 7 + 14
import math

for num in range(1, 1000):

    result = 0
    for factor in range(1, int(math.sqrt(num)) + 1): # sqrt:表示平方根函数
        # 确定出factor是否是因子,即能够完全整除的数
        if num % factor == 0:
            result += factor
            # 排除相同的因子,例如4 = 2 * 2
            if factor > 1 and num // factor != factor:
                result += num // factor
    # 判断因子之和是否和数字本身相等
    if result == num:
        print(num) 

1
6
28
496

Case 5: Output all prime numbers within 100

  • A prime number refers to an integer in a natural number greater than 1, except for 1 and the integer itself, a number that cannot be divisible by other natural numbers
import math

for num in range(2, 100):
    prime = True
    # 对num进行开平方,可以这样理解:
    # 100以内的数字只要能够整除2到int(math.sqrt(num)) + 1之间的数
    # 就表明,这个数不是素数,即不止1和他本身两个因子
    for factor in range(2, int(math.sqrt(num)) + 1):
        if num % factor == 0:
            prime = False
            break
    if prime == 1:
        print(num, end=' ')

Guess you like

Origin blog.csdn.net/amyniez/article/details/104383899