Python基础之Python面面观1

该系列为南京大学课程《用Python玩转数据》学习笔记,主要以思维导图的记录

2.1 条件

2.1

编程练习题

  1. 编写一个输入分数,输出分数等级的程序,具体为:

    Score Grade

    90~100 A

    70~89 B

    60~69 C

    0~59 D

    others Invalid score

    请添加必要的输入输出语句,尽量让程序友好。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    if __name__ == '__main__':
    score = int(input('please input your score:'))
    if score >= 90:
    print('Your grade is A!')
    elif score >= 70:
    print('Your grade is B!')
    elif score >= 60:
    print('Your grade is C!')
    elif score >=0:
    print('Your grade is D!')
    else:
    print('Invalid score!')
  2. 编写程序,从键盘输入一个二元一次方程ax^2+bx+c=0的三个参数a、b、c(均为整数),求此方程的实根。如果方程有实根,则输出实根(保留一位小数),如果没有实根则输出没有实根的信息。

    [输入样例1]

    1,0,-1

    [输出样例1]

    x1 = 1.0, x2 = -1.0

    [输入样例2]

    1,2,1

    [输出样例2]

    x = -1.0

    [输入样例3]

    2,2,3

    [输出样例3]

    no real solution

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    if __name__ == '__main__':
    a, b, c = eval(input("please input a,b,c values of a*x^2+b*x+c:"))
    t = b ** 2 - 4 * a * c
    if t > 0:
    x1 = (-b + sqrt(t)) / (2 * a)
    x2 = (-b - sqrt(t)) / (2 * a)
    print('x1 = {}, x2 = {}'.format(x1, x2))
    elif t == 0:
    x = -b / (2 * a)
    print('x = {}'.format(x))
    else:
    print('no real solution')

2.2 Range函数

2.2

2.3 循环

2.3

编程练习

  1. 输入一个整数,求其逆序数。注:虽然可通过字符串切片等方法轻松获得一个数的逆序数,但用整数通过循环来获得逆序数是锻炼逻辑思维的一个好例子。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    def reversed1(number):
    length = len(number)
    out = ''
    for i in range(len(number)):
    out += number[length - 1 - i]
    return out


    def reversed2(number):
    number = int(number)
    out = 0
    while number != 0:
    out = out * 10 + number % 10
    number = number // 10
    return out


    if __name__ == '__main__':
    number = input('input a number:')
    out1 = reversed1(number)
    out2 = reversed2(number)
    print(out1)
    print(out2)
  2. 将一个正整数分解质因数。例如:输入90,打印出90=233*5。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    def sp1(number):
    start = str(number)
    out = []
    i = 2
    while number != 1:
    while number % i == 0:
    number //= i
    out.append(str(i))
    i += 1
    print(start + '=' + '*'.join(out))


    def sp2(number):
    print(str(number) + '=', end='')
    i = 2
    while number != 1:
    while number % i ==0:
    number //= i
    if number == 1:
    print('{:d}'.format(i), end='')
    else:
    print('{:d}*'.format(i), end='')
    i += 1


    if __name__ == '__main__':
    number = eval(input('input a number:'))
    sp1(number)
    sp2(number)

2.4 循环中的break、continue和else

2.4

2.5 自定义函数

2.5