Basics of Python

Basics of Python

This article explains the basics of Python.

YouTube Video

Running "Hello World!"

1print("Hello World!")

Variables in Python

In Python, variables are named storage spaces for holding and using data and information within a program. Variables can hold various data types and be reassigned as needed. Below, we provide several sample codes to demonstrate the basic usage of variables in Python.

 1# 1. Assigning values to variables
 2# Integer type variable
 3age = 25
 4print("Age:", age)  # Output: Age: 25
 5
 6# Floating-point type variable
 7height = 175.5
 8print("Height:", height, "cm")  # Output: Height: 175.5 cm
 9
10# String type variable
11name = "John"
12print("Name:", name)  # Output: Name: John
13
14# Boolean type variable
15is_student = True
16print("Are you a student?", is_student)  # Output: Are you a student? True
17
18# 2. Assigning values to multiple variables simultaneously
19# You can assign multiple variables at once
20x, y, z = 5, 10, 15
21print("x =", x, ", y =", y, ", z =", z)  # Output: x = 5 , y = 10 , z = 15
22
23# 3. Updating the value of a variable
24# The value of a variable can be updated by reassignment
25age = 26
26print("Updated age:", age)  # Output: Updated age: 26
27
28# 4. Updating multiple variables at once
29# Example of swapping values between variables
30a, b = 1, 2
31a, b = b, a
32print("a =", a, ", b =", b)  # Output: a = 2 , b = 1
33
34# 5. Type conversion
35# Type conversion allows operations between different types
36count = "5"  # String "5"
37count = int(count)  # Convert to integer type
38print("Handling count as an integer:", count * 2)  # Output: Handling count as an integer: 10
39
40# Conversion to floating-point number
41pi_approx = "3.14"
42pi_approx = float(pi_approx)
43print("Approximation of pi:", pi_approx)  # Output: Approximation of pi: 3.14

As shown, variables in Python can be used flexibly. Variables can be used without specifying their type and can be reassigned as needed. Furthermore, type conversion makes it easy to switch between different data types.

Data Types in Python

Python has several basic data types. Below, we provide explanations and sample code for each.

Integer Type

The integer type is used to handle whole numbers without a decimal point.

1# Example of integer type
2x = 10
3print(x)        # Output: 10
4print(type(x))  # Output: <class 'int'>

Floating-Point Type

The floating-point type is used to handle numbers with a decimal point.

1# Floating Point Number Example
2y = 3.14
3print(y)        # Output: 3.14
4print(type(y))  # Output: float

String Type

The string type represents a sequence of characters. Strings can be enclosed in single quotes ' or double quotes ".

1# Example of String
2s = "Hello, World!"
3print(s)        # Output: Hello, World!
4print(type(s))  # Output: <class 'str'>

Boolean Type

The boolean type has two values: true (True) and false (False).

1# Example of Boolean
2b = True
3print(b)        # Output: True
4print(type(b))  # Output: <class 'bool'>

List Type

The list type is a mutable sequence that can store multiple elements, and the elements can be of different data types.

1# Example of List
2lst = [1, 2, 3, "four", 5.0]
3print(lst)        # Output: [1, 2, 3, 'four', 5.0]
4print(type(lst))  # Output: <class 'list'>

Tuple Type

A tuple is a sequence that can contain multiple elements, and its contents cannot be modified once created.

1# Example of Tuple
2tup = (1, "two", 3.0)
3print(tup)        # Output: (1, 'two', 3.0)
4print(type(tup))  # Output: <class 'tuple'>

Dictionary Type

The dictionary type is a collection that holds key-value pairs. Keys must be unique.

1# Example of Dictionary
2dct = {"one": 1, "two": 2, "three": 3}
3print(dct)        # Output: {'one': 1, 'two': 2, 'three': 3}
4print(type(dct))  # Output: <class 'dict'>

Set Type

The set type is a collection that holds unique elements. Duplicate values cannot be included.

1# Example of Set
2st = {1, 2, 2, 3}
3print(st)        # Output: {1, 2, 3}
4print(type(st))  # Output: <class 'set'>

These data types are fundamental ones commonly used for handling data in Python. By using them appropriately, you can meet various requirements in your programs.

Python Overview

Python is a high-level programming language developed by Guido van Rossum in 1991. Its design philosophy emphasizes 'simplicity,' 'clarity,' and 'readability,' resulting in code that is intuitive, easy to write, and easy to read. Below is an overview of Python's main features.

  1. Easy to read and simple:

    • With a clear structure and expressions close to natural language, it is an easy language for beginners to learn.
    • Blocks are defined with indentation, which automatically formats the code and increases readability.
  2. Rich Libraries and Frameworks:

    • It has a rich standard library, allowing many tasks to be performed easily.
    • There are specialized libraries and frameworks available for various fields, such as numerical computation (NumPy), data analysis (Pandas), machine learning (scikit-learn, TensorFlow), and web development (Django, Flask).
  3. Versatility:

    • Python is suitable both as a scripting language and for full-feature application development. It is used in various applications such as web applications, desktop applications, scientific computing, machine learning, data analysis, and IoT.
  4. Cross-platform:

    • It is platform-independent and can be run on many operating systems, including Windows, macOS, and Linux.
  5. Open Source and Community:

    • Python is an open-source project supported by an active community. Because of this, frequent updates, library development, and support are provided.
  6. Dynamic Typing and Automatic Memory Management:

    • Dynamic typing eliminates the need for declaring variable types, enabling faster development.
    • Garbage collection performs automatic memory management, making memory management simple.

With these features, Python is used widely across various fields, including education, industry, and academia.

Escape Characters in Python

In Python, escape characters are used to include specific control characters or characters with special meaning within strings. Escape characters are special symbols used to add specific meanings to regular strings. Let's take a closer look at escape characters in Python.

Basics of Escape Characters

In Python, escape characters are defined using a backslash (\). Escape characters indicate specific behavior within a regular string. For example, \n represents a newline, and \t represents a tab space.

You can define a string containing escape characters as follows:.

1# Example of escape characters
2print("Hello\nWorld")  # A newline is inserted after "Hello"
3
4# Output:
5# Hello
6# World

List of Main Escape Characters

The main escape characters used in Python are as follows:.

  • \\: Represents a backslash itself.
  • \': Includes a single quote in a string.
  • \": Includes a double quote in a string.
  • \n: Newline
  • \t: Tab
  • \r: Carriage return
  • \b: Backspace
  • \f: Form feed
  • \a: Alert sound (bell)
  • \v: Vertical tab
  • \N{name}: Character by name in the Unicode database
  • \uXXXX: 16-bit Unicode character (specified with 4 hexadecimal digits)
  • \UXXXXXXXX: 32-bit Unicode character (specified with 8 hexadecimal digits)
  • \xXX: Character specified in hexadecimal

Examples of Commonly Used Escape Characters

Here are some specific examples of how to use escape characters.

Double Quotes and Single Quotes

To include double quotes or single quotes within a string, use escape characters.

 1# String containing double quotes
 2quote = "He said, \"Python is amazing!\""
 3print(quote)
 4
 5# String containing single quotes
 6single_quote = 'It\'s a beautiful day!'
 7print(single_quote)
 8
 9# Output:
10# He said, "Python is amazing!"
11# It's a beautiful day!

Newlines and Tabs

Newlines and tabs are commonly used to format text.

 1# Example using newline
 2multiline_text = "First line\nSecond line"
 3print(multiline_text)
 4
 5# Example using tab
 6tabbed_text = "Column1\tColumn2\tColumn3"
 7print(tabbed_text)
 8
 9# Output:
10# First line
11# Second line
12# Column1	Column2	Column3

Unicode Escape Characters

In Python, Unicode characters are represented using \u or \U. This is particularly useful when handling non-English characters.

1# Example of Unicode escape
2japanese_text = "\u3053\u3093\u306B\u3061\u306F"  # Hello in Japanese
3print(japanese_text)
4# Output:
5# こんにちは(Hello in Japanese)

Cautions with Special Escape Characters

There are a few cautions to keep in mind when using escape characters.

  1. Raw string: If you want to display a string containing backslashes as-is, prefix the string with r.
1raw_string = r"C:\Users\name\Documents"
2print(raw_string)
3# Output:
4# C:\Users\name\Documents

In raw strings, the backslash is not interpreted as an escape character and is output as-is.

  1. Using Unicode: When using Unicode escape characters, ensure that the specified hexadecimal codes are correct. Incorrect specifications will result in incorrect character display.

Escaping Backslashes

To include a backslash itself in a string, use double backslashes.

1# Example containing backslash
2path = "C:\\Program Files\\Python"
3print(path)
4# Output:
5# C:\Program Files\Python

Advanced Example: Complex String Formatting

It is also possible to combine escape characters to format complex strings.

 1# Example of formatting a message
 2message = "Dear User,\n\n\tThank you for your inquiry.\n\tWe will get back to you shortly.\n\nBest Regards,\nCustomer Support"
 3print(message)
 4# Output:
 5# Dear User,
 6#
 7#     Thank you for your inquiry.
 8#     We will get back to you shortly.
 9#
10#     Best Regards,
11#     Customer Support

Summary

Python's escape characters are a powerful tool for including specific control characters or special characters within strings. Understanding how to use them and applying them appropriately as needed enables more flexible string processing.

Python Versions

Let’s briefly review the major Python releases and their features.

  1. Python 1.0 (1994)
1# Sample code that works in Python 1.0
2def greet(name):
3    print "Hello, " + name  # print was a statement
4
5greet("World")

The first official release. Python's basic syntax and standard library were established.

  1. Python 2.0 (2000)
1# Sample code that works in Python 2.0
2
3# List comprehension
4squares = [x * x for x in range(5)]
5print squares
6
7# Unicode string (u"...")
8greet = u"Hello"
9print greet

Important features, such as list comprehensions, full garbage collection, and the start of Unicode support, were added. Python 2 was used for a long time but reached the end of its support in 2020.

  1. Python 3.0 (2008)
1# Sample code that works in Python 3.0
2
3# print is now a function
4print("Hello, world!")
5
6# Unicode text is handled natively
7message = "Hello"
8print(message)

A major update with no backward compatibility. print was made into a function, Unicode became the default string type, and integers were unified, greatly improving Python's consistency and usability. Python 3 is the current mainstream version.

  1. Python 3.5 (2015)
1# Sample code that works in Python 3.5
2import asyncio
3
4async def say_hello():
5    await asyncio.sleep(1)
6    print("Hello, async world!")
7
8asyncio.run(say_hello())

The async/await syntax was introduced, making asynchronous programming simpler to write.

  1. Python 3.6 (2016)
1# Sample code that works in Python 3.6
2
3name = "Alice"
4age = 30
5print(f"{name} is {age} years old.")  # f-string makes formatting simple

Formatted String Literals (f-strings) were added, making string formatting more convenient. Additionally, type hints were expanded.

  1. Python 3.7 (2018)
 1# Sample code that works in Python 3.7
 2
 3from dataclasses import dataclass
 4
 5@dataclass
 6class Person:
 7    name: str
 8    age: int
 9
10p = Person("Bob", 25)
11print(p)

Dataclasses were introduced, making it easier to define struct-like classes. Support for async/await was also enhanced.

  1. Python 3.8 (2019)
1# Sample code that works in Python 3.8
2
3# Assignment inside an expression
4if (n := len("hello")) > 3:
5    print(f"Length is {n}")

The Walrus Operator (:=) was added, allowing the use of assignment expressions. Positional-only parameters were also introduced, improving flexibility in function arguments.

  1. Python 3.9 (2020)
1# Sample code that works in Python 3.9
2
3a = {"x": 1}
4b = {"y": 2}
5c = a | b  # merge two dicts
6print(c)   # {'x': 1, 'y': 2}

Improvements to type hints and the addition of a merge operator (|) for lists and dictionaries were made. The standard library was also reorganized.

  1. Python 3.10 (2021)
 1# Sample code that works in Python 3.10
 2
 3def handle(value):
 4    match value:
 5        case 1:
 6            return "One"
 7        case 2:
 8            return "Two"
 9        case _:
10            return "Other"
11
12print(handle(2))

Pattern matching was added, allowing more powerful conditional statements. Error messages were improved, and the type system was further strengthened.

  1. Python 3.11 (2022)
1# Sample code that works in Python 3.11
2
3# Improved performance (up to 25% faster in general)
4# More informative error messages
5try:
6    eval("1/0")
7except ZeroDivisionError as e:
8    print(f"Caught an error: {e}")
**Significant performance improvements** were made, resulting in faster execution compared to previous versions. Additionally, improvements were made to exception handling and type checking.
  1. Python 3.12 (2023)
 1# Sample code that works in Python 3.12
 2
 3# Automatically shows exception chains with detailed traceback
 4def f():
 5    raise ValueError("Something went wrong")
 6
 7def g():
 8    try:
 9        f()
10    except Exception:
11        raise RuntimeError("Higher level error")  # Automatically chained
12
13try:
14    g()
15except Exception as e:
16    import traceback
17    traceback.print_exception(type(e), e, e.__traceback__)
Error messages have been further improved, and performance has been enhanced. Additionally, exception chaining is automatically displayed, enabling more detailed debugging. New syntax features and enhancements to the standard library have also been added, improving developer productivity.
  1. Python 3.13 (2024)
 1# Sample code that works in Python 3.13
 2
 3# Using the new 'except*' syntax for handling multiple exceptions in parallel
 4import asyncio
 5
 6async def raise_errors():
 7    raise ExceptionGroup("Multiple errors", [
 8        ValueError("Invalid value"),
 9        TypeError("Wrong type"),
10    ])
11
12async def main():
13    try:
14        await raise_errors()
15    except* ValueError as e:
16        print("Caught ValueError(s):", e.exceptions)
17    except* TypeError as e:
18        print("Caught TypeError(s):", e.exceptions)
19
20asyncio.run(main())

In Python 3.13, the ExceptionGroup and except* syntax have been further refined, allowing multiple exceptions in asynchronous processing to be caught in parallel. This makes debugging and error handling in applications that utilize parallel processing or asyncio more intuitive and powerful. In addition, improvements to type hints and updates to the standard library have enhanced maintainability and expressiveness.

Python version 3 is continuously evolving, with the latest versions featuring performance enhancements, improvements to the type system, and new features.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video