本大白最近带一只小白入手编程,想法是在练习中学习,所以弄了几个题目。其中不少是经典的练习题,在很多编程入门书籍中都有出现;有的题涉及到一点数据结构的理念。在这里分享出来,刚接触编程的同学可以和我们一起做一做(无论学的是哪种语言都可以看一看,思路是通用的。这里我们学的是python),也欢迎大家指正。
1.打印"Hello world!"
经典的"hello world!"已成了学习编程的第一件事了,可以认为得到了"hello world"就得到了好运吧。python动态语言完成这个“开门红”任务再简单不过了。
print("Hello world!")
2.打印从控制台输入的内容
主要是对从控制台输入内容和向控制台打印内容有一个认识
print(input("What do you want to input: "))
3.选择判断,while循环
主要了解python中if-else,及if-elif-else结构(C++、Java对应if-else,if-else if-else, 及switch-case结构),定义一个函数,及while循环
3.1 回答 1 + 1 = , 并显示回答的正误性
3.2 给出分数,转化为绩点。用函数实现分数到绩点的转换。输入'q'表示退出
### 3.1
result = input("1 + 1 = ?")
if result == 2:
print("Correct!")
else:
print("Wrong!")
### 3.2 gpa
def get_gpa(grade):
if grade >= 90 and grade <= 100:
gpa = 4.0
elif grade >= 80:
gpa = 3.0
elif grade >= 70:
gpa = 2.0
elif grade >= 60:
gpa = 1.0
else:
gpa = 0
return gpa
while(True):
grade = input("Enter the grade: ")
if grade == 'q':
break
else:
print(get_gpa(int(grade)))
4. for循环
计算两个3*3矩阵的乘积
matrix_1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix_2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
matrix = matrix_product(matrix_1, matrix_2)
print_matrix(matrix)
# product function
def matrix_product(matrix_1, matrix_2):
matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0, 3):
for j in range(0, 3):
for k in range(0, 3):
matrix[i][j] += matrix_1[i][k] * matrix_2[k][j]
return matrix
# print function
def print_matrix(matrix):
for i in range(0, 3):
row = ''
for j in range(0, 3):
row += str(matrix[i][j]) + " "
5. 等差数列前n项和
输入首项、公差、项数,调用函数计算前n项和,并打印计算结果
initial = float(input("Enter the series' initial: "))
diff = float(input("Enter the series' difference: "))
num = int(input("Enther the series' number: "))
result = series_sum(initial, diff, num)
print("The sum of the series is " + str(result))
def series_sum(initial, diff, num):
result = initial
term = initial
for i in range(num - 1):
term += diff
result += term
return result
6. 打印菱形
输入整数n,然后在控制台打印符号"*"构成的菱形(2n-1行)
结果示例:
n = int(input("Enter an integer:" ))
print_rhombus(n)
def print_rhombus(n):
# first n rows
for row in range(1, n+1):
space = n - row
star = 2 * row - 1
for i in range(space):
print(' ', end = '')
for i in range(star):
print('*', end = '')
print('')
# row n+1 ~ row 2n-1
for row in range(1, n):
space = row
star = 2 * (n - row) - 1
for i in range(space):
print(' ', end = '')
for i in range(star):
print('*', end = '')
print('')
7. 判断闰年
输入一个年份,判断该年是不是闰年。闰年的规则如下:一般每4年为闰年,但每100年不是闰年,如2100年不是闰年;但每400年又是闰年,如2000年是闰年
year = int(input("Enter the year: "))
if leap(year):
print(str(year) + " is a leap year.")
else:
print(str(year) + " is not a leap year.")
def leap(year):
return ((year % 4 == 0 ) and (year % 100 != 0)) or (year % 400 == 0)