首页  >  文章  >  后端开发  >  python编程基础代码

python编程基础代码

zbt
zbt原创
2023-10-25 10:42:051408浏览

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

1、计算器:

def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("选择操作:")
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 True
else:
return False
year = 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、求和:

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

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

以上是python编程基础代码的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn