[综合练习题]Python3 语法基础练习
- 1. Python Hello World 实例
- 2. Python 二次方程
- 3. Python 随机数生成
- 4. Python 判断闰年
- 5. Python 阶乘实例
- 6. Python 九九乘法表
- 7. Python 生成日历
- 8. Python 文件 IO
- 9. Python 计算元素在列表中出现的次数
- 10. Python 使用正则表达式提取字符串中的 URL
1. Python Hello World 实例
以下实例为学习Python的第一个实例,即如何输出"Hello World!":
# -*- coding: UTF-8 -*-
# Filename : helloworld.py
# 该实例输出 Hello World!
print('Hello World!')
2. Python 二次方程
以下实例为通过用户输入数字,并计算二次方程:
# Filename : test.py
# 二次方程式 ax**2 + bx + c = 0
# a、b、c 用户提供,为实数,a ≠ 0
# 导入 cmath(复杂数学运算) 模块
import cmath
a = float(input('输入 a: '))
b = float(input('输入 b: '))
c = float(input('输入 c: '))
# 计算
d = (b**2) - (4*a*c)
# 两种求解方式
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('结果为 {0} 和 {1}'.format(sol1,sol2))
3. Python 随机数生成
以下实例演示了如何生成一个随机数:
# -*- coding: UTF-8 -*-
# Filename : test.py
# 生成 0 ~ 9 之间的随机数
# 导入 random(随机数) 模块
import random
print(random.randint(0,9))
4. Python 判断闰年
以下实例用于判断用户输入的年份是否为闰年:
# -*- coding: UTF-8 -*-
# Filename : test.py
year = int(input("输入一个年份: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} 是闰年".format(year)) # 整百年能被400整除的是闰年
else:
print("{0} 不是闰年".format(year))
else:
print("{0} 是闰年".format(year)) # 非整百年能被4整除的为闰年
else:
print("{0} 不是闰年".format(year))
5. Python 阶乘实例
整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×…×n。
#!/usr/bin/python3
# Filename : test.py
# 通过用户输入数字计算阶乘
# 获取用户输入的数字
num = int(input("请输入一个数字: "))
factorial = 1
# 查看数字是负数,0 或 正数
if num < 0:
print("抱歉,负数没有阶乘")
elif num == 0:
print("0 的阶乘为 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("%d 的阶乘为 %d" %(num,factorial))
6. Python 九九乘法表
以下实例演示了如何实现九九乘法表:
# -*- coding: UTF-8 -*-
# Filename : test.py
# 九九乘法表
for i in range(1, 10):
for j in range(1, i+1):
print('{}x{}={}\t'.format(j, i, i*j), end='')
print()
7. Python 生成日历
以下代码用于生成指定日期的日历:
# Filename : test.py
# 引入日历模块
import calendar
# 输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
# 显示日历
print(calendar.month(yy,mm))
8. Python 文件 IO
以下代码演示了Python基本的文件操作,包括 open,read,write:
# Filename : test.py
# 写文件
with open("test.txt", "wt") as out_file:
out_file.write("该文本会写入到文件中\n看到我了吧!")
# Read a file
with open("test.txt", "rt") as in_file:
text = in_file.read()
print(text)
9. Python 计算元素在列表中出现的次数
定义一个列表,并计算某个元素在列表中出现的次数。
例如:
输入 : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]
x = 10
输出 : 3
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print(countX(lst, x))
10. Python 使用正则表达式提取字符串中的 URL
给定一个字符串,里面包含 URL 地址,需要我们使用正则表达式来获取字符串的 URL。
import re
def Find(string):
# findall() 查找匹配正则表达式的字符串
url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
return url
string = '数据大咖的网页地址为:https://www.shujudaka.com,Google 的网页地址为:https://www.google.com'
print("Urls: ", Find(string))
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。