Home >Backend Development >Python Tutorial >python programming basic code

python programming basic code

zbt
zbtOriginal
2023-10-25 10:42:051499browse

The following are some basic Python programming code examples:

1. Calculator:

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. Determine leap year:

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. String reversal:

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

4. Sum:

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

These sample codes cover basic Python Programming concepts such as variables, data types, operators, functions, conditional statements, etc. By learning these basic codes, you can gradually master Python programming. Python programming concepts such as variables, data types, operators, functions, conditional statements, etc. By learning these basic codes, you can gradually master Python programming.

The above is the detailed content of python programming basic code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn