PHP前端开发

python编程基础代码

百变鹏仔 1个月前 (01-19) #Python
文章标签 代码

以下是一些python编程基础代码示例:

1、计算器:

def add(x, y):return x + ydef subtract(x, y):return x - ydef multiply(x, y):return x * ydef divide(x, y):return x / yprint("选择操作:")print("1.加法")print("2.减法")print("3.乘法")print("4.除法")choice = input("请输入操作对应的数字(1/2/3/4): ")if choice == '1':x = float(input("请输入第一个数字: "))y = float(input("请输入第二个数字: "))print("结果: ", add(x, y))elif choice == '2':x = float(input("请输入第一个数字: "))y = float(input("请输入第二个数字: "))print("结果: ", subtract(x, y))elif choice == '3':x = float(input("请输入第一个数字: "))y = float(input("请输入第二个数字: "))print("结果: ", multiply(x, y))elif choice == '4':x = float(input("请输入第一个数字: "))y = float(input("请输入第二个数字: "))print("结果: ", divide(x, y))else:print("输入错误,请输入正确的操作对应数字!")

2、判断闰年:

def is_leap_year(year):if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):return Trueelse:return Falseyear = int(input("请输入一个年份: "))if is_leap_year(year):print("{}年是闰年。".format(year))else:print("{}年不是闰年。".format(year))

3、字符串反转:

def reverse_string(s):return s[::-1]s = input("请输入一个字符串: ")print("反转后的字符串: ", reverse_string(s))

4、求和:

立即学习“Python免费学习笔记(深入)”;

def sum_numbers(n):return n * (n + 1) // 2n = int(input("请输入一个正整数: "))print("前 {} 个自然数的和为: {}。".format(n, sum_numbers(n)))

这些示例代码涵盖了基本的 Python 编程概念,如变量、数据类型、运算符、函数、条件语句等。通过学习这些基础代码,您可以逐步掌握 Python 编程。ython 编程概念,如变量、数据类型、运算符、函数、条件语句等。通过学习这些基础代码,您可以逐步掌握 Python 编程。