Python สุดยอดสูตรโกง

Jan 04 2023
บทนำ Python เป็นภาษาการเขียนโปรแกรมระดับสูงที่ตีความซึ่งใช้กันอย่างแพร่หลายสำหรับการพัฒนาเว็บ ปัญญาประดิษฐ์ การวิเคราะห์ข้อมูล และการคำนวณทางวิทยาศาสตร์ เป็นภาษาที่ใช้งานทั่วไป ซึ่งหมายความว่าสามารถใช้สร้างซอฟต์แวร์ได้เกือบทุกชนิด ตั้งแต่แอปพลิเคชันเดสก์ท็อปไปจนถึงเว็บเซิร์ฟเวอร์และเฟรมเวิร์ก
ภาพถ่ายโดย Hitesh Choudhary บน Unsplash

บทนำ

Python เป็นภาษาโปรแกรมระดับสูงที่ถูกตีความซึ่งใช้กันอย่างแพร่หลายสำหรับการพัฒนาเว็บ ปัญญาประดิษฐ์ การวิเคราะห์ข้อมูล และการคำนวณทางวิทยาศาสตร์ เป็นภาษาที่ใช้งานทั่วไป ซึ่งหมายความว่าสามารถใช้สร้างซอฟต์แวร์ได้เกือบทุกชนิด ตั้งแต่แอปพลิเคชันเดสก์ท็อปไปจนถึงเว็บเซิร์ฟเวอร์และเฟรมเวิร์ก

ข้อดีหลักประการหนึ่งของ Python คือความเรียบง่ายและอ่านง่าย มันใช้การเยื้องเพื่อกำหนดบล็อกของโค้ด และไวยากรณ์นั้นตรงไปตรงมาและง่ายต่อการเรียนรู้ สิ่งนี้ทำให้เป็นภาษาที่ยอดเยี่ยมสำหรับผู้เริ่มต้น เช่นเดียวกับมืออาชีพที่ต้องการสร้างต้นแบบแนวคิดหรือสร้างต้นแบบอย่างรวดเร็ว

นอกจากความเรียบง่ายแล้ว Python ยังทรงพลังมากอีกด้วย มีไลบรารีมาตรฐานขนาดใหญ่ ซึ่งหมายความว่าคุณสามารถทำงานทั่วไปหลายอย่างได้โดยไม่ต้องติดตั้งไลบรารีเพิ่มเติม นอกจากนี้ยังมีไลบรารีของบุคคลที่สามที่ทรงพลังจำนวนมาก เช่น NumPy และ Pandas ซึ่งสามารถใช้สำหรับการคำนวณทางวิทยาศาสตร์ การวิเคราะห์ข้อมูล และการเรียนรู้ของเครื่อง

โดยรวมแล้ว Python เป็นภาษาที่หลากหลายและเป็นที่นิยมซึ่งเหมาะสำหรับงานที่หลากหลาย ไม่ว่าคุณจะเป็นมือใหม่ที่ต้องการเรียนรู้การเขียนโปรแกรมหรือมืออาชีพที่ต้องการสร้างซอฟต์แวร์ที่มีประสิทธิภาพ Python เป็นตัวเลือกที่ยอดเยี่ยม

ตัวอย่างโค้ด

การพิมพ์ไปยังคอนโซล:

print("Hello, World!")

ตัวแปร:

x = 5
y = 10
z = x + y
print(z)

ลูป

for i in range(5):
    print(i)

ข้อความเงื่อนไข:

x = 5
if x > 0:
    print("x is positive")
else:
    print("x is not positive")

ฟังก์ชั่น:

def greet(name):
  print("Hello, " + name + "!")

greet("Alice")
greet("Bob")

อาร์เรย์:

names = ["Alice", "Bob", "Charlie"]
for name in names:
    print(name)

การเขียนโปรแกรมเชิงวัตถุ:

class Dog:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def bark(self):
    print("Woof!")

dog1 = Dog("Fido", 3)
dog2 = Dog("Buddy", 5)

print(dog1.name)
print(dog2.age)

dog1.bark()
dog2.bark()

นำเข้าโมดูล:

import math

x = math.pi
print(x)

การอ่านและเขียนไฟล์:

# Open a file for writing
f = open("test.txt", "w")

# Write to the file
f.write("Hello, World!")

# Close the file
f.close()

# Open the file for reading
f = open("test.txt", "r")

# Read the contents of the file
contents = f.read()

# Print the contents
print(contents)

# Close the file
f.close()

ข้อยกเว้น:

try:
  x = 5 / 0
except ZeroDivisionError:
  print("Division by zero!")

พจนานุกรม:

# Create a dictionary
person = {
  "name": "John Smith",
  "age": 30,
  "city": "New York"
}

# Access an element of the dictionary
print(person["name"])

# Modify an element of the dictionary
person["age"] = 35

# Add a new element to the dictionary
person["country"] = "USA"

# Delete an element from the dictionary
del person["city"]

รายการ:

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

# Access an element of the list
print(numbers[0])

# Modify an element of the list
numbers[0] = 10

# Add a new element to the list
numbers.append(6)

# Delete an element from the list
del numbers[4]

สิ่งอันดับ:

# Create a tuple
point = (1, 2)

# Access an element of the tuple
print(point[0])

# Tuples are immutable, so you cannot modify or add elements

# Unpack a tuple
x, y = point
print(x)
print(y)

ชุด:

# Create a set
s = set([1, 2, 3, 4, 5])

# Add an element to the set
s.add(6)

# Remove an element from the set
s.remove(5)

# Check if an element is in the set
if 3 in s:
  print("3 is in the set")

# Find the intersection of two sets
s2 = set([4, 5, 6, 7, 8])
s3 = s.intersection(s2)
print(s3)

สตริง:

# Create a string
s = "Hello, World!"

# Get the length of a string
n = len(s)

# Access an element of the string
c = s[0]

# Modify an element of the string (strings are immutable, so this will create a new string)
s2 = s[:5] + "world" + s[11:]

# Find the index of a substring
i = s.find("World")

# Split a string into a list of substrings
l = s.split(",")

คลาสและการสืบทอด:

class Pet:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def speak(self):
    print("I don't know what to say")

class Cat(Pet):
  def speak(self):
    print("Meow")

class Dog(Pet):
  def speak(self):
    print("Woof")

pets = [Cat("Fluffy", 3), Dog("Buddy", 5)]
for pet in pets:
  pet.speak()

โมดูล:

# math.py

def add(x, y):
  return x + y

def subtract(x, y):
  return x - y

# main.py

import math

result = math.add(5, 3)
print(result)

result = math.subtract(5, 3)
print(result)

รายการความเข้าใจ:

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)

เครื่องกำเนิดไฟฟ้า:

def count_up_to(max):
  count = 1
  while count <= max:
    yield count
    count += 1

for number in count_up_to(5):
  print(number)

ฟังก์ชันแลมบ์ดา:

add = lambda x, y: x + y
result = add(5, 3)
print(result)

แผนที่และตัวกรอง:

numbers = [1, 2, 3, 4, 5]

# Use map to apply a function to each element
squares = list(map(lambda x: x**2, numbers))
print(squares)

# Use filter to select elements that meet a condition
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)

มัณฑนากร:

def my_decorator(func):
  def wrapper():
    print("Something is happening before the function is called.")
    func()
    print("Something is happening after the function is called.")
  return wrapper

@my_decorator
def say_hi():
  print("Hi!")

say_hi()

แจกแจง:

colors = ["red", "green", "blue"]

for i, color in enumerate(colors):
  print(f"{i}: {color}")

การเรียงลำดับ

numbers = [3, 1, 4, 2, 5]

# Sort the list in ascending order
numbers.sort()
print(numbers)

# Sort the list in descending order
numbers.sort(reverse=True)
print(numbers)

# Use the sorted function to return a new sorted list
numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)

ผู้จัดการบริบท:

with open("test.txt", "w") as f:
  f.write("Hello, World!")

นิพจน์ทั่วไป:

import re

# Find all the occurrences of a pattern
pattern = r"\d+"
string = "There are 3 dogs and 4 cats."
matches = re.findall(pattern, string)
print(matches)

# Find the first occurrence of a pattern
pattern = r"\d+"
string = "There are 3 dogs and 4 cats."
match = re.search(pattern, string)
print(match.group())

# Replace all the occurrences of a pattern
pattern = r"\d+"
replacement = "NUMBER"
string = "There are 3 dogs and 4 cats."
new_string = re.sub(pattern, replacement, string)
print(new_string)

การอ่านและเขียนไฟล์ CSV:

import csv

# Write to a CSV file
with open("test.csv", "w", newline="") as f:
  writer = csv.writer(f)
  writer.writerow(["Name", "Age"])
  writer.writerow(["Alice", 25])
  writer.writerow(["Bob", 30])

# Read from a CSV file
with open("test.csv", "r", newline="") as f:
  reader = csv.reader(f)
  for row in reader:
    print(row)

การเขียนและการอ่านไฟล์ JSON:

การเขียน

import json

# Data to be written to a JSON file
data = {
  "name": "Alice",
  "age": 25,
  "city": "New York"
}

# Open the file for writing
with open("test.json", "w") as f:
  # Write the data to the file
  json.dump(data, f)

import json

# Open the file for reading
with open("test.json", "r") as f:
  # Load the data from the file
  data = json.load(f)

# Print the data
print(data)

ติดตาม แชร์ และสมัครรับเนื้อหาแบบโต้ตอบเพิ่มเติม