以下是一些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、求和:
立即学习“Python免费学习笔记(深入)”;
def sum_numbers(n):
return n * (n + 1) // 2
n = int(input("请输入一个正整数: "))
print("前 {} 个自然数的和为: {}。".format(n, sum_numbers(n)))这些示例代码涵盖了基本的 Python 编程概念,如变量、数据类型、运算符、函数、条件语句等。通过学习这些基础代码,您可以逐步掌握 Python 编程。ython 编程概念,如变量、数据类型、运算符、函数、条件语句等。通过学习这些基础代码,您可以逐步掌握 Python 编程。
以上就是python编程基础代码的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号