Python 变得简单:从初学者到高级 |博客

WBOY
发布: 2024-08-31 06:00:32
原创
781 人浏览过

Python Made Simple: Beginner to Advanced | Blog

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 List and For Loops

A 2D list (or 2D array) in Python is essentially a list of lists, where each sublist represents a row of the matrix. You can use nested for loops to iterate over elements in a 2D list. Here’s how you can work with 2D lists and for loops:

# 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)
登录后复制

This is how we can use 2D List and For Loops.

以上是Python 变得简单:从初学者到高级 |博客的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!