Python是一款简单易学的高级编程语言,被广泛应用于Web开发、科学计算、数据处理、人工智能等多个领域。作为一名Python爱好者,我们应该掌握一些基本的编程技能,下面我将为大家介绍100个Python编程实例,让大家更好地了解Python编程。
1. 输出“Hello, world!”
print("Hello, world!")
2. 计算1+2+...+100的总和
total = 0
for i in range(1, 101):
total += i
print(total)
3. 判断一个数是否为质数
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
print(is_prime(23))
4. 打印斐波那契数列
def fibonacci(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
fibonacci(1000)
5. 判断一个字符串是否为回文串
def is_palindrome(s):
s = s.lower()
left, right = 0, len(s) - 1
while left < right:
while not s[left].isalnum() and left < right:
left += 1
while not s[right].isalnum() and left < right:
right -= 1
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome("A man, a plan, a canal: Panama"))
6. 找出一个列表中最大的数
def max_num(lst):
max_num = lst[0]
for i in lst:
if i > max_num:
max_num = i
return max_num
print(max_num([1,5,3,7,10]))
7. 去除一个列表中的重复元素
def remove_duplicate(lst):
lst_new = []
for i in lst:
if i not in lst_new:
lst_new.append(i)
return lst_new
print(remove_duplicate([1,2,1,3,4,2]))
8. 计算一个数的阶乘
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
9. 判断一个字符串是否为数字
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
print(is_number("123"))
10. 将一个字符串中的大写字母转为小写字母
s = "AbCDeFGHIjklM"
print(s.lower())
11. 将一个字符串中的小写字母转为大写字母
s = "AbCDeFGHIjklM"
print(s.upper())
12. 将一个列表中的元素倒序排列
lst = [1,2,3,4,5]
lst.reverse()
print(lst)
13. 将一个字符串中的单词倒序排列
s = "hello world"
lst = s.split()
lst.reverse()
s_reverse = " ".join(lst)
print(s_reverse)
14. 计算一个数的平方根
num = 9
sqrt = num ** 0.5
print(sqrt)
15. 求一个列表中所有元素的平均值
def average(lst):
return sum(lst) / len(lst)
print(average([1,2,3,4,5]))
16. 求一个列表中的中位数
def median(lst):
lst.sort()
l = len(lst)
if l % 2 == 0:
return (lst[int(l/2)-1] + lst[int(l/2)]) / 2
else:
return lst[int(l/2)]
print(median([1,2,3,4,5,6,7]))
17. 交换两个变量的值
a, b = 1, 2
a, b = b, a
print(a, b)
18. 在控制台输入三个数,判断是否能构成三角形
a = int(input("请输入三角形的第一条边的长度:"))
b = int(input("请输入三角形的第二条边的长度:"))
c = int(input("请输入三角形的第三条边的长度:"))
if (a + b > c) and (a + c > b) and (b + c > a):
print("是一个三角形")
else:
print("不是一个三角形")
19. 统计一个字符串中各个字符出现的次数
s = "hello, world!"
d = {}
for i in s:
if i in d:
d[i] += 1
else:
d[i] = 1
print(d)
20. 计算某年某月的天数
import calendar
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
days = calendar.monthrange(year, month)[1]
print(days)
21. 判断一个字符串是否为有效的IP地址
import re
def is_valid_ip(ip):
pattern = re.compile(r'^(\d{1,3}\.){3}\d{1,3}$')
match = pattern.match(ip)
if match is None:
return False
lst = ip.split('.')
for i in lst:
if int(i) > 255:
return False
return True
print(is_valid_ip("192.168.1.1"))
22. 判断一个字符串是否为有效的URL地址
import re
def is_valid_url(url):
pattern = re.compile(r'^https?://[a-z0-9]+([\-\.][a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(/.*)?$')
match = pattern.match(url)
if match is None:
return False
else:
return True
print(is_valid_url("http://www.baidu.com"))
23. 判断一个字符串是否为有效的电子邮件地址
import re
pattern = re.compile(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$')
match = pattern.match(email)
if match is None:
return False
else:
return True
print(is_valid_email("12345@qq.com"))
24. 将一个列表中的元素进行随机排序
import random
lst = [1,2,3,4,5]
random.shuffle(lst)
print(lst)
25. 将一段英文文本中的单词进行计数,并按照出现次数从高到低排序
s = "hello world hello python hello hello python"
d = {}
lst = s.split()
for i in lst:
if i in d:
d[i] += 1
else:
d[i] = 1
lst_sort = sorted(d.items(), key=lambda x:x[1], reverse=True)
print(lst_sort)
26. 计算一个数对另一个数的余数
num1, num2 = 10, 3
print(num1 % num2)
27. 将一个字符串中的空格替换为指定的字符串
s = "hello world"
s_replace = s.replace(' ', '-')
print(s_replace)
28. 将一个列表中的元素进行排序
lst = [1,4,2,8,5]
lst.sort()
print(lst)
29. 判断一个字符串是否为有效的手机号码
import re
def is_valid_mobile(mobile):
pattern = re.compile(r'^1[3-9]\d{9}$')
match = pattern.match(mobile)
if match is None:
return False
else:
return True
print(is_valid_mobile("13888888888"))
30. 计算两个数的最大公约数
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
print(gcd(54, 24))
31. 计算两个数的最小公倍数
def lcm(a, b):
return a * b // gcd(a, b)
print(lcm(54, 24))
32. 判断一个字符串中是否含有指定的子串
s = "hello, world!"
if 'world' in s:
print("包含")
else:
print("不包含")
33. 将一个字符串中的字母进行大小写互换
s = "aBcDeFG"
s_swap = ""
for i in s:
if i.islower():
s_swap += i.upper()
else:
s_swap += i.lower()
print(s_swap)
34. 计算一个数的n次方
num = 2
n = 4
res = num ** n
print(res)
35. 将一个字符串中的每个单词首字母大写
s = "hello, world!"
lst = s.split()
lst_new = []
for i in lst:
i_new = i.capitalize()
lst_new.append(i_new)
s_new = " ".join(lst_new)
print(s_new)
36. 实现一个简易计算器
def calculator(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return None
print(calculator(2, 3, '*'))
37. 将一个字符串中的所有单词首尾颠倒
s = "hello, world!"
lst = s.split()
lst_new = []
for i in lst:
i_new = i[::-1]
lst_new.append(i_new)
s_new = " ".join(lst_new)
print(s_new)
38. 判断一个字符串是否为回文数(从左往右和从右往左读都一样)
s = "abcba"
if s == s[::-1]:
print("是回文数")
else:
print("不是回文数")
39. 求数列中的最大连续子序列之和
def max_subseq(lst):
max_sum = lst[0]
cur_sum = 0
for i in lst:
if cur_sum < 0:
cur_sum = i
else:
cur_sum += i
if cur_sum > max_sum:
max_sum = cur_sum
return max_sum
print(max_subseq([-2,1,-3,4,-1,2,1,-5,4]))
40. 将一个列表中的元素按照指定的顺序排序
lst = ["apple", "pear", "banana", "orange"]
lst_sort = sorted(lst, key=lambda x:len(x))
print(lst_sort)
41. 实现一个单链表的节点的数据结构
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
42. 实现单链表的插入、删除操作
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
if self.head is None:
self.head = Node(data)
else:
node = Node(data, self.head)
self.head = node
def delete(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
curr = self.head
while curr.next:
if curr.next.data == data:
curr.next = curr.next.next
return
curr = curr.next
43. 实现单链表的查找操作
class LinkedList:
def __init__(self):
self.head = None
def search(self, data):
curr = self.head
while curr:
if curr.data == data:
return True
curr = curr.next
return False
44. 判断一个字符串是否为有效的日期格式
import re
def is_valid_date(date):
pattern = re.compile(r'^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$')
match = pattern.match(date)
if match is None:
return False
lst = re.split(r'(\-|\/|\.)', date)
year, month, day = int(lst[0]), int(lst[2]), int(lst[4])
if month < 1 or month > 12 or day < 1 or day > 31:
return False
elif month in [4, 6, 9, 11] and day > 30:
return False
elif month == 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0) and day > 29:
return False
elif month == 2 and day > 28:
return False
else:
return True
print(is_valid_date("2000/02/29"))
45. 将一个字符串中的所有单词颠倒顺序,并在每个单词后追加指定的字符串
s = "hello, world!"
lst = s.split()
lst_new = lst[::-1]
s_new = "_".join(lst_new)
print(s_new)
46. 将一个字符串中的所有单词颠倒顺序,并在每个单词后追加指定的字符串
s = "hello, world!"
lst = s.split()
lst_new = lst[::-1]
lst_new_new = [i + '_' for i in lst_new]
s_new = "".join(lst_new_new)
print(s_new)
47. 计算一个字符串中出现次数最多的字符
s = "hello, world!"
d = {}
for i in s:
if i in d:
d[i] += 1
else:
d[i] = 1
lst_sort = sorted(d.items(), key=lambda x:x[1], reverse=True)
print(lst_sort[0][0])
48. 计算两个字符串中的最长公共子串
def longest_common_substring(str1, str2):
len1, len2 = len(str1), len(str2)
dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]
max_len = 0
pos = -1
for i in range(1, len1 + 1):
for j in range(1, len2 + 1):
if str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] > max_len:
max_len = dp[i][j]
pos = i
else:
dp[i][j] = 0
return str1[pos - max_len:pos]
print(longest_common_substring("abcdefg", "bcdabc"))
49. 计算两个字符串中的最长公共子序列
def longest_common_subsequence(str1, str2):
len1, len2 = len(str1), len(str2)
dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]
for i in range(1, len1 + 1):
for j in range(1, len2 + 1):
if str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
res = []
i, j = len1, len2
while i > 0 and j > 0:
if str1[i-1] == str2[j-1]:
res.append(str1[i-1])
i -= 1
j -= 1
elif dp[i-1][j] >= dp[i][j-1]:
i -= 1
else:
j -= 1
res.reverse()
return "".join(res)
print(longest_common_subsequence("abcdefg", "bcdabc"))
50. 实现一个简单的TCP/IP客户端程序
import socket
host = 'www.baidu.com'
port = 80
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
request = "GET / HTTP/1.1\r\nHost: " + host + "\r\n\r\n"
client_socket.send(request.encode())
response = client_socket.recv(4096)
print(response.decode())
51. 实现一个简单的TCP/IP服务器程序
import socket
host = ''
port = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print("服务器正在监听,请等待客户端连接...")
client_socket, address = server_socket.accept()
print("客户端已连接:", address)
message = "欢迎来到服务器"
client_socket.send(message.encode())
client_socket.close()
52. 计算一个字符串的MD5哈希值
import hashlib
s = "hello, world!"
m = hashlib.md5()
m.update(s.encode())
print(m.hexdigest())
53. 计算一个字符串的SHA-1哈希值
import hashlib
壹涵网络我们是一家专注于网站建设、企业营销、网站关键词排名、AI内容生成、新媒体营销和短视频营销等业务的公司。我们拥有一支优秀的团队,专门致力于为客户提供优质的服务。
我们致力于为客户提供一站式的互联网营销服务,帮助客户在激烈的市场竞争中获得更大的优势和发展机会!
发表评论 取消回复