Basics of Python

Introduction

Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in web development, data analysis, artificial intelligence, scientific computing, and more.

# This is a comment
print("Hello, World!")  # This prints a string to the console

Variables and Data Types

In Python, variables are used to store data. Python supports various data types including integers, floats, strings, and booleans.

# Integer
age = 21

# Float
pi = 3.14

# String
name = "Alice"

# Boolean
is_student = True

Operators

Operators are special symbols that perform operations on variables and values.

# Arithmetic Operators
a = 10
b = 5
print(a + b)  # Output: 15
print(a - b)  # Output: 5

# Comparison Operators
print(a == b)  # Output: False
print(a > b)   # Output: True

# Logical Operators
print(a > 5 and b < 10)  # Output: True
print(not(a > 5))       # Output: False

Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

age = 18

if age < 18:
    print("Minor")
elif age == 18:
    print("Just turned adult")
else:
    print("Adult")

Loops

Loops are used to execute a block of code repeatedly.

# For loop
for i in range(5):
    print(i)

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

Lists and Tuples

Lists and tuples are used to store multiple items in a single variable.

# List
fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # Output: apple

# Tuple
colors = ("red", "green", "blue")
print(colors[1])  # Output: green

Strings

Strings are sequences of characters. They are used to store text.

# String
greeting = "Hello, World!"
print(greeting)

# String concatenation
name = "Alice"
message = greeting + " " + name
print(message)  # Output: Hello, World! Alice

Dictionaries

Dictionaries are used to store data values in key:value pairs.

# Dictionary
student = {
    "name": "Alice",
    "age": 21,
    "is_student": True
}
print(student["name"])  # Output: Alice

Functions

Functions are reusable blocks of code that perform a specific task. They help in organizing code and avoiding repetition.

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))

File Handling

Python provides built-in functions to handle files. You can read from and write to files using these functions.

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, World!")

# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)