当前位置:首页 > 文章列表 > 文章 > python教程 > Python 代码片段 |文档

Python 代码片段 |文档

来源:dev.to 2024-09-03 17:45:55 0浏览 收藏

在文章实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Python 代码片段 |文档》,聊聊,希望可以帮助到正在努力赚钱的你。

Python 代码片段 |文档

python 课程代码示例

这是我使用和创建的 python 代码的文档,用于学习 python。
它易于理解和学习。欢迎从这里学习。
我很快就会用更多高级主题更新博客。

目录

  1. 第一个节目
  2. 变量和数据类型
  3. 字符串
  4. 数字
  5. 获取用户的输入
  6. 构建一个基本计算器
  7. 第一个 madlibs
  8. 列表
  9. 列出函数
  10. 元组
  11. 功能
  12. 退货声明
  13. if 语句
  14. 如果比较
  15. 猜谜游戏2
  16. for 循环
  17. 指数函数
  18. 二维列表和 for 循环

第一个节目

此程序用于展示 print() 命令如何工作。

# this is a simple "hello world" program that demonstrates basic print statements

# print the string "hello world" to the console
print("hello world")

# print the integer 1 to the console
print(1)

# print the integer 20 to the console
print(20)

变量和数据类型

python 中的变量是用于存储值的保留内存位置。
数据类型定义变量可以保存的数据类型,即整数、浮点、字符串等

# this program demonstrates the use of variables and string concatenation

# assign the string "dipsan" to the variable _name
_name = "dipsan"

# assign the integer 20 to the variable _age
_age = 20

# assign the string "piano" to the variable _instrument
_instrument = "piano"

# print a sentence using string concatenation with the _name variable
print("my name is" + _name + ".")

# print a sentence using string concatenation, converting _age to a string
print("i'm" + str(_age) + "years old")  # converting int to string for concatenation

# print a simple string
print("i dont like hanging out")

# print a sentence using string concatenation with the _instrument variable
print("i love " + _instrument + ".")

弦乐

用于存储和操作文本的字符序列。它们是通过将文本括在单引号 ('hello')、双引号 ("hello") 或多行字符串的三引号 ('''hello''') 中来创建的。示例:“你好,世界!”。

# this script demonstrates various string operations

# assign a string to the variable 'phrase'
phrase = "dipsansacademy"

# print a simple string
print("this is a string")

# concatenate strings and print the result
print('this' + phrase + "")

# convert the phrase to uppercase and print
print(phrase.upper())

# convert the phrase to lowercase and print
print(phrase.lower())

# check if the uppercase version of phrase is all uppercase and print the result
print(phrase.upper().isupper())

# print the length of the phrase
print(len(phrase))

# print the first character of the phrase (index 0)
print(phrase[0])

# print the second character of the phrase (index 1)
print(phrase[1])

# print the fifth character of the phrase (index 4)
print(phrase[4])

# find and print the index of 'a' in the phrase
print(phrase.index("a"))

# replace "dipsans" with "kadariya" in the phrase and print the result
print(phrase.replace("dipsans", "kadariya"))

数字

数字用于各种数字运算和数学函数:

# import all functions from the math module
from math import *  # importing math module for additional math functions

# this script demonstrates various numeric operations and math functions

# print the integer 20
print(20)

# multiply 20 by 4 and print the result
print(20 * 4)

# add 20 and 4 and print the result
print(20 + 4)

# subtract 4 from 20 and print the result
print(20 - 4)

# perform a more complex calculation and print the result
print(3 + (4 - 5))

# calculate the remainder of 10 divided by 3 and print the result
print(10 % 3)

# assign the value 100 to the variable _num
_num = 100

# print the value of _num
print(_num)

# convert _num to a string, concatenate with other strings, and print
print(str(_num) + " is my fav number")  # converting int to string for concatenation

# assign -10 to the variable new_num
new_num = -10

# print the absolute value of new_num
print(abs(new_num))  # absolute value

# calculate 3 to the power of 2 and print the result
print(pow(3, 2))     # power function

# find the maximum of 2 and 3 and print the result
print(max(2, 3))     # maximum

# find the minimum of 2 and 3 and print the result
print(min(2, 3))     # minimum

# round 3.2 to the nearest integer and print the result
print(round(3.2))    # rounding

# round 3.7 to the nearest integer and print the result
print(round(3.7))

# calculate the floor of 3.7 and print the result
print(floor(3.7))    # floor function

# calculate the ceiling of 3.7 and print the result
print(ceil(3.7))     # ceiling function

# calculate the square root of 36 and print the result
print(sqrt(36))      # square root

获取用户的输入

此程序用于演示如何使用 input() 函数获取用户输入:

# this script demonstrates how to get user input and use it in string concatenation

# prompt the user to enter their name and store it in the 'name' variable
name = input("enter your name : ")

# prompt the user to enter their age and store it in the 'age' variable
age = input("enter your age. : ")

# print a greeting using the user's input, concatenating strings
print("hello " + name + " youre age is " + age + " .")

构建一个基本计算器

该程序创建一个简单的计算器,将两个数字相加:

# this script creates a basic calculator that adds two numbers

# prompt the user to enter the first number and store it in 'num1'
num1 = input("enter first number : ")

# prompt the user to enter the second number and store it in 'num2'
num2 = input("enter second number: ")

# convert the input strings to integers and add them, storing the result
result = int(num1) + int(num2)

# print the result of the addition
print(result)

第一疯狂

这个程序创建了一个简单的 mad libs 游戏:

# this program is used to create a simple mad libs game.

# prompt the user to enter an adjective and store it in 'adjective1'
adjective1 = input("enter an adjective: ")

# prompt the user to enter an animal and store it in 'animal'
animal = input("enter an animal: ")

# prompt the user to enter a verb and store it in 'verb'
verb = input("enter a verb: ")

# prompt the user to enter another adjective and store it in 'adjective2'
adjective2 = input("enter another adjective: ")

# print the first sentence of the mad libs story using string concatenation
print("i have a " + adjective1 + " " + animal + ".")

# print the second sentence of the mad libs story
print("it likes to " + verb + " all day.")

# print the third sentence of the mad libs story
print("my " + animal + " is so " + adjective2 + ".")

列表

列表是python中有序且可更改的项目的集合。列表中的每个项目(或元素)都有一个索引,从 0 开始。列表可以包含不同数据类型的项目(如整数、字符串,甚至其他列表)。
列表使用方括号 [] 定义,每个项目用逗号分隔。

# this script demonstrates basic list operations

# create a list of friends' names
friends = ["roi", "alex", "jimmy", "joseph"]

# print the entire list
print(friends)

# print the first element of the list (index 0)
print(friends[0])

# print the second element of the list (index 1)
print(friends[1])

# print the third element of the list (index 2)
print(friends[2])

# print the fourth element of the list (index 3)
print(friends[3])

# print the last element of the list using negative indexing
print(friends[-1])

# print a slice of the list from the second element to the end
print(friends[1:])

# print a slice of the list from the second element to the third (exclusive)
print(friends[1:3])

# change the second element of the list to "kim"
friends[1] = "kim"

# print the modified list
print(friends)

列表功能

此脚本展示了各种列表方法:

# this script demonstrates various list functions and methods

# create a list of numbers
numbers = [4, 6, 88, 3, 0, 34]

# create a list of friends' names
friends = ["roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"]

# print both lists
print(numbers)
print(friends)

# add all elements from 'numbers' to the end of 'friends'
friends.extend(numbers)

# add "hulk" to the end of the 'friends' list
friends.append("hulk")

# insert "mikey" at index 1 in the 'friends' list
friends.insert(1, "mikey")

# remove the first occurrence of "roi" from the 'friends' list
friends.remove("roi")

# print the index of "mikey" in the 'friends' list
print(friends.index("mikey"))

# remove and print the last item in the 'friends' list
print(friends.pop())

# print the current state of the 'friends' list
print(friends)

# remove all elements from the 'friends' list
friends.clear()

# print the empty 'friends' list
print(friends)

# sort the 'numbers' list in ascending order
numbers.sort()

# print the sorted 'numbers' list
print(numbers)

元组

元组是python中有序但不可更改(不可变)的项目的集合。一旦创建了元组,就无法添加、删除或更改其元素。与列表一样,元组可以包含不同数据类型的项目。
元组使用括号 () 定义,每个项目用逗号分隔。

# this script introduces tuples and their immutability

# create a tuple with two elements
values = (3, 4)

# print the entire tuple
print(values)

# print the second element of the tuple (index 1)
print(values[1])

# the following line would cause an indexerror if uncommented:
# print(values[2])  # this would cause an indexerror

# the following line would cause a typeerror if uncommented:
# values[1] = 30    # this would cause a typeerror as tuples are immutable

# the following line would print the modified tuple if the previous line worked:
# print(values)

功能

函数是执行特定任务的可重用代码块。函数可以接受输入(称为参数)、处理它们并返回输出。函数有助于组织代码,使其更加模块化,并避免重复。
在 python 中,函数是使用 def 关键字定义的,后跟函数名、括号 () 和冒号 :。函数内的代码是缩进的。
此代码演示了如何定义和调用函数:

# this script demonstrates how to define and call functions

# define a function called 'greetings' that prints two lines
def greetings():
    print("hi, welcome to programming world of python")
    print("keep learning")

# print a statement before calling the function
print("this is first statement")

# call the 'greetings' function
greetings()

# print a statement after calling the function
print("this is last statement")

# define a function 'add' that takes two parameters and prints their sum
def add(num1, num2):
    print(int(num1) + int(num2))

# call the 'add' function with arguments 3 and 4
add(3, 4)

退货声明

return 语句在函数中用于向调用者发送回(或“返回”)一个值。当执行return时,函数结束,return后指定的值被发送回函数调用的地方。

此程序展示了如何在函数中使用 return 语句:

# this script demonstrates the use of return statements in functions

# define a function 'square' that returns the square of a number
def square(num):
    return num * num
    # any code after the return statement won't execute

# call the 'square' function with argument 2 and print the result
print(square(2))

# call the 'square' function with argument 4 and print the result
print(square(4))

# call the 'square' function with argument 3, store the result, then print it
result = square(3)
print(result)

如果语句

if 语句计算一个条件(返回 true 或 false 的表达式)。
如果条件为 true,则执行 if 语句下的代码块。
elif :“else if”的缩写,它允许您检查多个条件。
当您有多个条件需要评估,并且您想要执行第一个 true 条件的代码块时,可以使用它。
else:如果前面的 if 或 elif 条件都不为 true,则 else 语句将运行一段代码。

# this script demonstrates the use of if-elif-else statements

# set boolean variables for conditions
is_boy = true
is_handsome = false

# check conditions using if-elif-else statements
if is_boy and is_handsome:
    print("you are a boy & youre handsome")
    print("hehe")
elif is_boy and not (is_handsome):
    print("youre a boy but sorry not handsome")
else:
    print("youre not a boy")

如果比较

此代码演示了 if 语句中的比较操作:

# this script demonstrates comparison operations in if statements

# define a function to find the maximum of three numbers
def max_numbers(num1, num2, num3):
    if num1 >= num2 and num1 >= num3:
        return num1
    elif num2 >= num1 and num2 >= num3:
        return num2
    else:
        return num3

# test the max_numbers function with different inputs
print(max_numbers(20, 40, 60))
print(max_numbers(30, 14, 20))
print(max_numbers(3, 90, 10))

print("for min_number")

# define a function to find the minimum of three numbers
def min_numbers(num1, num2, num3):
    if num1 <= num2 and num1 <= num3:
        return num1
    elif num2 <= num1 and num2 <= num3:
        return num2
    else:
        return num3

# test the min_numbers function with different inputs
print(min_numbers(20, 40, 60))
print(min_numbers(30, 14, 20))
print(min_numbers(3, 90, 10))

猜谜游戏2

此脚本通过更多功能改进了猜谜游戏:

# this script improves the guessing game with more features

import random

# generate a random number between 1 and 20
secret_number = random.randint(1, 20)

# initialize the number of attempts and set a limit
attempts = 0
attempt_limit = 5

# loop to allow the user to guess the number
while attempts < attempt_limit:
    guess = int(input(f"guess the number (between 1 and 20). you have {attempt_limit - attempts} attempts left: "))
    if guess == secret_number:
        print("congratulations! you guessed the number!")
        break
    elif guess < secret_number:
        print("too low!")
    else:
        print("too high!")
    attempts += 1

# if the user does not guess correctly within the attempt limit, reveal the number
if guess != secret_number:
    print(f"sorry, the correct number was {secret_number}.")

for循环

for 循环用于迭代元素序列,例如列表、元组、字符串或范围。
这段代码引入了for循环:

# list of numbers
numbers = [1, 2, 3, 4, 5]

# iterate over each number in the list
for number in numbers:
    # print the current number
    print(number)

# output:
# 1
# 2



# 3
# 4
# 5

# list of friends
friends = ["roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"]

# iterate over each friend in the list
for friend in friends:
    # print the name of the current friend
    print(friend)

# output:
# roi
# alex
# jimmy
# joseph
# kevin
# tony
# jimmy

# use range to generate numbers from 0 to 4
for num in range(5):
    print(num)

# output:
# 0
# 1
# 2
# 3
# 4

指数函数

指数函数是一种数学函数,其中恒定基数被提升为可变指数。
此脚本展示了如何使用 math.pow 函数:

# this script demonstrates the use of the exponential function
def exponentialfunction(base,power):
    result = 1
    for index in range(power):
        result = result * base
    return result

print(exponentialfunction(3,2))
print(exponentialfunction(4,2))
print(exponentialfunction(5,2))

#or you can power just by
print(2**3) #number *** power

2d 列表和 for 循环

python 中的 2d 列表(或 2d 数组)本质上是列表的列表,其中每个子列表代表矩阵的一行。您可以使用嵌套的 for 循环来迭代 2d 列表中的元素。以下是使用 2d 列表和 for 循环的方法:

# This script demonstrates the use of 2D List and For Loops
# Define a 2D list (list of lists)
num_grid = [
    [1, 2, 3],  # Row 0: contains 1, 2, 3
    [4, 5, 6],  # Row 1: contains 4, 5, 6
    [7, 8, 9],  # Row 2: contains 7, 8, 9
    [0]         # Row 3: contains a single value 0
]

# Print specific elements in num_grid
print(num_grid[0][0])   # Print value in the zeroth row, zeroth column (value: 1)
print(num_grid[1][0])   # Print value in the first row, zeroth column (value: 4)
print(num_grid[2][2])   # Print value in the second row, second column (value: 9)


print("using nested for loops")
for row in num_grid :
   for col in row:
    print(col)

这就是我们如何使用 2d 列表和 for 循环。

理论要掌握,实操不能落!以上关于《Python 代码片段 |文档》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
Java函数内存优化策略有哪些?Java函数内存优化策略有哪些?
上一篇
Java函数内存优化策略有哪些?
win10怎么关闭应用使用相机 win10禁止应用使用相机教程
下一篇
win10怎么关闭应用使用相机 win10禁止应用使用相机教程
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    511次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    498次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 千音漫语:智能声音创作助手,AI配音、音视频翻译一站搞定!
    千音漫语
    千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
    151次使用
  • MiniWork:智能高效AI工具平台,一站式工作学习效率解决方案
    MiniWork
    MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
    143次使用
  • NoCode (nocode.cn):零代码构建应用、网站、管理系统,降低开发门槛
    NoCode
    NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
    158次使用
  • 达医智影:阿里巴巴达摩院医疗AI影像早筛平台,CT一扫多筛癌症急慢病
    达医智影
    达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
    151次使用
  • 智慧芽Eureka:更懂技术创新的AI Agent平台,助力研发效率飞跃
    智慧芽Eureka
    智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
    160次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码