What is Python? Python is a high-level programming language that is widely used for web development, data analysis, artificial intelligence, and more.

01-1 What is Python?

From those taking their first steps into the world of programming to experienced developers, Python is one of the programming languages that everyone loves. In this course, we will delve into the basics of Python, including its definition, history, key features, and why many developers use Python.

Definition and History of Python

Python was developed by Dutch programmer Guido van Rossum in the late 1980s and was first released in 1991. He designed Python based on the ABC language, focusing on enhancing code readability and productivity.

Interesting Fact: The name Python does not come from the snake. Guido van Rossum chose this name because he was a fan of the British comedy group Monty Python.

It Wasn’t Always Like This!

Initially, Python was not widely used. However, over time, the language’s simple and clear syntax made Python more attractive to a larger audience. By the early 2000s, Python began gaining recognition in various fields such as scientific computing, data analysis, and web development.

Key Features of Python

1. Simplicity and Readability of Syntax

One of the greatest strengths of Python is its clear and concise syntax. This helps in writing code that is easy to read and maintain. Python’s syntax is intuitive, much like English sentences, making it easy for beginners to learn.

print("Hello, World!")

The example above is the simplest ‘Hello, World!’ program in Python. Python’s intuitive syntax is more descriptive and has less unnecessary syntax compared to other languages.

2. Rich Standard Library

Python comes with a variety of standard libraries that allow for easy implementation of numerous functionalities. For example, it has libraries for string manipulation, file I/O, mathematical calculations, and communication with web services.

import os
print(os.getcwd())

The code above uses Python’s os library to print the current working directory. With many built-in modules available, you can use commonly needed functions without having to implement them yourself.

3. Cross-Platform Support

Python can run on almost all operating systems, including Windows, macOS, and Linux. Being a cross-platform language, it allows developers to create programs that operate consistently across multiple environments with a single codebase.

Applications of Python

The versatility and flexibility of Python allow it to be used in various fields. Here are a few major applications:

1. Web Development

Python is widely used in web application development through powerful web frameworks like Django and Flask. These frameworks support rapid web development and make maintenance easier.

2. Data Science and Analysis

Thanks to libraries like Pandas, NumPy, Matplotlib, SciPy, and Scikit-learn, Python is a popular choice for performing data science and analysis. It allows for efficient execution of various tasks, such as data visualization and building machine learning models.

3. Artificial Intelligence and Machine Learning

Python is widely used in the fields of artificial intelligence and machine learning through libraries like TensorFlow, Keras, and PyTorch. These libraries enable easy construction of complex neural networks.

4. Scripting and Automation

Python’s simple syntax and powerful libraries make it an excellent choice for writing scripts to automate various tasks. It simplifies scripting tasks in system administration, data processing, and file management.

Reasons Why Learning Python Is Important

Despite many programming languages, Python is recommended for both new programmers starting out and experienced developers for the following reasons:

1. Easy Learning Curve

Python’s clear syntax allows beginners to easily understand and apply the basic concepts of programming. This is especially advantageous for programming newcomers.

2. Active Community

Python has a large developer community, making it easy to find resources or guides for help. This is a significant aid in problem-solving.

3. Applications in Various Fields

The ability to apply Python in fields like data science, web development, and artificial intelligence makes it usable across a broader range of applications than many other languages.

Conclusion

Python is a powerful, flexible, and easy-to-learn programming language. Its applicability in diverse fields ensures that Python will continue to be a language of prominence. Through this course series, we encourage you to explore Python in depth and learn practical applications. This HTML format can be copied and pasted into WordPress to complete an in-depth course article on what Python is. This article is designed to help readers understand and get started with Python.

Understanding Python Data Types and NumPy Arrays: From Basics

Understanding Python Data Types and NumPy Arrays: From Basics to Advanced

Python provides various data types to effectively manage and manipulate data. Additionally, it offers a powerful library called NumPy for efficient handling of numeric data. In this course, we will explore the basic data types in Python along with NumPy arrays.

1. Basic Data Types in Python

Python offers a variety of data types, allowing developers to manipulate data in different ways. Here, we will examine a few commonly used basic data types.

  • Integer (int): Stores integer values. For example, a = 10 stores the integer 10 in the variable a.
  • Floating-Point (float): Stores real numbers and can include a decimal point. For example, pi = 3.14 stores 3.14 in the variable pi.
  • String (str): Stores text data and is enclosed in single (' ') or double quotes (" "). Example: name = 'Alice'.
  • List (list): A mutable sequence that can store multiple values in order. Example: numbers = [1, 2, 3, 4].
  • Tuple (tuple): Similar to a list, but once created, a tuple cannot be modified. Example: point = (10, 20).
  • Dictionary (dict): Stores data in key-value pairs. Example: student = {'name': 'John', 'age': 25}.

2. NumPy Arrays

NumPy is a Python library that provides high-performance multidimensional array objects and various functions to handle them. It plays an essential role in almost all Python codes for scientific computing and numerical analysis.

Creating NumPy Arrays

import numpy as np

# Create a 1-dimensional array
arr1 = np.array([1, 2, 3, 4, 5])
print("1-dimensional array:", arr1)

# Create a 2-dimensional array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("2-dimensional array:\n", arr2)

Basic Array Operations

NumPy arrays provide convenient mathematical operations.

# Operations on array elements
result = arr1 + 10
print("Adding 10 to each element:", result)

# Operations between arrays
result = arr1 * 2
print("Multiplying each element by 2:", result)

NumPy vectorizes these operations, allowing them to be performed quickly over the entire array. This enables much faster processing of large amounts of numeric data compared to Python’s built-in lists.

3. Conclusion

In this course, we introduced the basic data types in Python and NumPy arrays. Basic data types like integers, floating-point numbers, strings, lists, tuples, and dictionaries are useful for storing and manipulating various data. Additionally, we learned how to use NumPy arrays for more efficient processing of numeric data.

Since NumPy plays a crucial role in data science and machine learning, it will be very beneficial to continue learning how to use it. Try to familiarize yourself with different data types and functions by using them directly!

Using Dynamic Objects in Python (Adding Attributes Dynamically Without Declaring a Class)

There is a way to dynamically add attributes without declaring an object in Python. A representative method is using `types.SimpleNamespace`. However, if you want to use the basic `object`, you need to declare a class. Here is a summary of how to use `types.SimpleNamespace` and how to use the basic `object`.

### Method 1: Using `types.SimpleNamespace`

Using `types.SimpleNamespace`, you can dynamically add attributes to an object without declaring a class:

Python Data Types – Pandas DataFrame

Pandas DataFrame

Pandas is a library widely used for data analysis in Python, and among its features, DataFrame is a two-dimensional structure consisting of rows and columns. A DataFrame can store and manipulate data in a format similar to an Excel spreadsheet, making it very useful for data analysis tasks.

import pandas as pd

# Create a DataFrame
data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data)
print(df)

Key Features of DataFrame

1. Creating a DataFrame

A DataFrame can be created from various data structures, such as dictionaries, lists, and Numpy arrays. For example, you can create a DataFrame using a dictionary.

data = {
    "Product": ["Apple", "Banana", "Cherry"],
    "Price": [100, 200, 300]
}
df = pd.DataFrame(data)
print(df)

2. Accessing Columns and Rows in a DataFrame

To access columns or rows in a DataFrame, you can use the loc or iloc methods. loc accesses based on labels, while iloc accesses based on integer indices.

# Access a column
print(df["Product"])

# Access a row (using loc)
print(df.loc[0])

# Access a row (using iloc)
print(df.iloc[1])

3. Adding and Removing Data

You can add new columns or rows to a DataFrame or delete existing data. To add a new column, you write as follows.

# Adding a new column
df["Discounted Price"] = df["Price"] * 0.9
print(df)

To delete a row, use the drop() method.

# Deleting a row
df = df.drop(1)
print(df)

4. Data Analysis Functions

Pandas provides various functions useful for data analysis. For example, the describe() function provides basic statistical information about the DataFrame.

print(df.describe())

Additionally, you can use functions like mean() and sum() to calculate the average or sum of a specific column.

average_price = df["Price"].mean()
print("Average Price:", average_price)

5. Filtering a DataFrame

You can filter data in a DataFrame based on specific conditions. For example, to select only products priced at 150 or more, write as follows.

filtered_df = df[df["Price"] >= 150]
print(filtered_df)

6. Sorting a DataFrame

To sort a DataFrame based on a specific column, use the sort_values() method.

# Sort in descending order by price
sorted_df = df.sort_values(by="Price", ascending=False)
print(sorted_df)

Summary

  • Variables are spaces for storing data, and when values are assigned, their data type is automatically determined.
  • You can use the type() function to check the data type of a variable.
  • Python variables use dynamic typing, allowing different types of values to be assigned to the same variable.
  • You can assign values to multiple variables at once or assign the same value to several variables.
  • You can use functions like int(), float(), and str() to convert data types.
  • Pandas DataFrame is a two-dimensional data structure consisting of rows and columns and is very useful for data analysis.
  • A DataFrame can be created in various forms such as dictionaries or lists, and you can access columns and rows as well as add and delete data.
  • You can efficiently analyze data using filtering, sorting, and statistical functions of a DataFrame.

Variables and Pandas DataFrames are essential tools for handling data in Python. Understand and apply them well to achieve effective data processing!

Python Data Types – Sets

Python Set Data Type

In Python, a Set is an unordered data type that represents a collection of unique values. Sets are defined using curly braces {}, and each element is unique. For example:

my_set = {1, 2, 3, 4, 5}

Characteristics of Sets

1. No Duplicates Allowed

Since sets do not allow duplicate values, if the same value is added multiple times, only one instance is stored.

my_set = {1, 2, 2, 3, 4}
print(my_set)  # {1, 2, 3, 4}

2. Unordered

Since sets are an unordered type, they do not support indexing or slicing. To access elements of a set, you must use a loop.

my_set = {"apple", "banana", "cherry"}
for item in my_set:
    print(item)

3. Adding and Removing Elements in a Set

Sets are mutable, which means you can add or remove elements. You can use the add() method to add elements, and remove() or discard() methods to remove them.

my_set = {1, 2, 3}
my_set.add(4)            # {1, 2, 3, 4}
my_set.remove(2)         # {1, 3, 4}
my_set.discard(5)        # {1, 3, 4} (no error when removing a non-existent element)
print(my_set)

4. Set Operations

Sets support various operations such as union, intersection, and difference. These operations can be performed using the |, &, and - operators or methods.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Union
union_set = set1 | set2
print(union_set)  # {1, 2, 3, 4, 5, 6}

# Intersection
intersection_set = set1 & set2
print(intersection_set)  # {3, 4}

# Difference
difference_set = set1 - set2
print(difference_set)  # {1, 2}

5. Set Methods

Sets offer various methods for easy manipulation of elements:

  • set.add(x): Adds an element to the set.
  • set.remove(x): Removes a specific element from the set, and raises an error if the element is not present.
  • set.discard(x): Removes a specific element from the set, and does not raise an error if the element is not present.
  • set.union(other_set): Returns the union of two sets.
  • set.intersection(other_set): Returns the intersection of two sets.
  • set.difference(other_set): Returns the difference of two sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}

set1.add(6)
print(set1)  # {1, 2, 3, 6}

set1.discard(2)
print(set1)  # {1, 3, 6}

union = set1.union(set2)
print(union)  # {1, 3, 4, 5, 6}

intersection = set1.intersection(set2)
print(intersection)  # {3}

6. Applications of Sets

Sets are useful in various situations such as removing duplicate values or finding common elements through operations between multiple sets. For example, to remove duplicates from a list, you can convert it to a set.

my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set)  # {1, 2, 3, 4, 5}

Summary

  • Sets represent a collection of unique values and do not allow duplicate values.
  • Sets are unordered, so they do not support indexing or slicing.
  • You can manipulate set elements using methods such as add(), remove(), and discard().
  • Sets support operations such as union, intersection, and difference, which allow for easy analysis of data relationships.
  • Sets can be used to remove duplicate values or find common elements, among other tasks.

Sets are one of the most useful data types in Python, particularly suited for handling duplicate data or performing set operations. Utilize the various features of sets to manage data efficiently!