python常用代码示例大全

1、Hello World

使用 print 函数输出字符串 “Hello World!” 到控制台:

print("Hello World!")

2、计算数字的平方和

以下是使用 python 计算数字的平方和的代码:

def square_sum(numbers):

    sum = 0

    for num in numbers:

        sum += num ** 2

    return sum

print(square_sum([1, 2, 3, 4])) # 输出 30

3、计算简单数学表达式

# 计算简单数学表达式

def calculate(expression):

    return eval(expression)


# 用户输入数学表达式

expression = input("请输入一个数学表达式:")


# 计算并输出结果

print("结果是:", calculate(expression))

4、字符串操作

字符串连接:使用 + 或 + 运算符可以将两个字符串连接起来。
字符串重复:使用 * 运算符可以将字符串重复多次。
字符串截取:使用索引和切片可以截取字符串中的一段。
字符串搜索:使用 in 和 not in 运算符可以在字符串中搜索某个子字符串。
字符串替换:使用 replace() 函数可以将字符串中的一个子字符串替换为另一个子字符串。
字符串分割:使用 split() 函数可以将字符串按照指定的分隔符分割为多个子字符串。

# Define a string

string = "Hello World!"

 

# Print the original string

print("Original string:", string)

 

# Get the length of the string

string_length = len(string)

print("Length of the string:", string_length)

 

# Concatenate two strings

new_string = string + " How are you?"

print("Concatenated string:", new_string)

 

# Repeat the string

repeated_string = string * 3

print("Repeated string:", repeated_string)

 

# Get a substring

substring = string[0:5]

print("Substring:", substring)

 

# Replace a substring

replaced_string = string.replace("Hello", "Hi")

print("Replaced string:", replaced_string)

 

# Check if a string contains a substring

is_hello_there = "Hello there!"

if "Hello" in is_hello_there:

    print("'Hello' is in the string.")

else:

    print("'Hello' is not in the string.")

5、if 语句

if 语句用于检查一个条件是否为真,如果为真,执行对应的代码块。

语法

if condition:

    # Execute this block if the condition is true

else:

    # Execute this block if the condition is false

 范例

x = int(input("Enter a number: "))

 

if x > 0:

    print("Positive number")

elif x < 0:

    print("Negative number")

else:

    print("Zero")

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值