Introduction to Basic Python Programming

1. Introduction to Python

Python is a high-level programming language known for its simplicity, readability, and powerful features. It is widely used in various fields such as web development, data analysis, artificial intelligence, and automation scripts. The syntax of Python is similar to English, making it easy to learn and understand, which is suitable for beginners starting their programming journey.

2. Installing Python

1. Visit the official website: Go to the Python official website and find the installation package suitable for your operating system in the download section on the homepage.

2. Installation process:

– For Windows users, after downloading the installer, run it and ensure to check the “Add Python to PATH” option, so you can use Python directly from the command line.

– For Mac users, Python usually comes pre-installed with the system, but it is recommended to install the latest version. The installation process is similar to that of Windows.

– For Linux users, Python can be installed via package managers (like `apt`, `yum`, etc.). For example, on Ubuntu, you can use the command `sudo apt-get install python3`.

After installation, you can verify if it was successful by entering `python –version` (Windows) or `python3 –version` (Mac/Linux) in the command line.

3. Basic Python Syntax

(1) Comments

Comments are parts of the code used for explanation and are not executed. In Python, single-line comments are added using the `#` symbol.

“`python

# This is a single-line comment

print(“Hello, World!”) # This is a comment for the print statement

“`

(2) Variables and Data Types

1. Variables: Variables are used to store data. In Python, you do not need to declare the type of a variable; you can assign a value directly.

“`python

name = “Kimi” # String type

age = 25 # Integer type

height = 1.75 # Float type

is_student = True # Boolean type

“`

2. Data Types:

– String (str): A sequence of characters enclosed in single `’` or double `”` quotes.

“`python

greeting = “Hello, Kimi!”

print(greeting[0]) # Outputs ‘H’

“`

– Integer (int): A number without a decimal part.

“`python

num1 = 10

num2 = 20

print(num1 + num2) # Outputs 30

“`

– Float (float): A number with a decimal part.

“`python

price = 99.99

print(price * 2) # Outputs 199.98

“`

– Boolean (bool): Has only two values, `True` and `False`, commonly used for logical conditions.

“`python

is_valid = True

if is_valid:

print(“Valid”)

“`

(3) Basic Operations

1. Arithmetic Operations:

– Addition: `+`

– Subtraction: `-`

– Multiplication: `*`

– Division: `/` (result is always a float)

– Modulus: `%`

– Floor Division: `//`

– Exponentiation: `**`

“`python

result = 10 + 5 * 2

print(result) # Outputs 20

“`

2. Comparison Operations:

– Equal: `==`

– Not Equal: `!=`

– Greater Than: `>`

– Less Than: `<`

– Greater Than or Equal: `>=`

– Less Than or Equal: `<=`

“`python

if 10 > 5:

print(“10 is greater than 5”)

“`

(4) Control Structures

1. if Statement: Used for conditional checks.

“`python

score = 85

if score >= 90:

print(“A”)

elif score >= 80:

print(“B”)

else:

print(“C or below”)

“`

2. Loops:

– for Loop: Used to iterate over sequences (like lists, strings, etc.).

“`python

fruits = [“apple”, “banana”, “cherry”]

for fruit in fruits:

print(fruit)

“`

– while Loop: Repeats a block of code as long as the condition is true.

“`python

count = 0

while count < 5:

print(count)

count += 1

“`

(5) Functions

A function is a reusable block of code that performs a specific task.

“`python

def greet(name):

return f”Hello, {name}!”

print(greet(“Kimi”)) # Outputs Hello, Kimi!

“`

4. Common Data Structures

1. List:

– An ordered collection that can store multiple elements.

“`python

my_list = [1, 2, 3, “four”, True]

print(my_list[1]) # Outputs 2

my_list.append(“five”)

print(my_list) # Outputs [1, 2, 3, ‘four’, True, ‘five’]

“`

2. Tuple:

– Similar to a list, but a tuple cannot be modified once created.

“`python

my_tuple = (1, 2, 3)

print(my_tuple[0]) # Outputs 1

“`

3. Dictionary:

– A collection of key-value pairs, accessed via keys.

“`python

my_dict = {“name”: “Kimi”, “age”: 25}

print(my_dict[“name”]) # Outputs Kimi

my_dict[“height”] = 1.75

print(my_dict) # Outputs {‘name’: ‘Kimi’, ‘age’: 25, ‘height’: 1.75}

“`

5. Input and Output

1. Input: Use the `input()` function to get input from the user.

“`python

user_name = input(“Enter your name: “)

print(f”Hello, {user_name}!”)

“`

2. Output: Use the `print()` function to output content to the console.

“`python

print(“Hello, World!”)

“`

6. Practical Examples

Example 1: Calculate Fibonacci Sequence

“`python

def fibonacci(n):

a, b = 0, 1

result = []

while len(result) < n:

result.append(a)

a, b = b, a + b

return result

print(fibonacci(10)) # Outputs the first 10 numbers of the Fibonacci sequence

“`

Example 2: File Read and Write

1. Writing to a file:

“`python

with open(“example.txt”, “w”) as file:

file.write(“Hello, World!”)

“`

2. Reading from a file:

“`python

with open(“example.txt”, “r”) as file:

content = file.read()

print(content)

“`

7. Recommended Learning Resources

1. Official Documentation: The Python official documentation is an authoritative resource for learning Python.

2. Online Tutorials: Platforms like Codecademy and Coursera offer a wealth of Python courses.

3. Books: “Python Programming: An Introduction to Computer Science” and “Fluent Python” are excellent learning books.

Through the study of the above content, you have mastered the basic knowledge of Python. Continue to practice and explore, and you will be able to write more complex programs to solve real-world problems. Wishing you great success on your Python programming journey!

Leave a Comment