Python Basics

Python is a versatile, high-level programming language known for its readability and ease of use. Here, we’ll cover essential Python concepts, including variables, data types, operators, control flow, functions, and more.

1. Variables and Data Types

In Python, variables are used to store data values. You don’t need to declare the type explicitly, as Python infers it from the assigned value.

Variable Assignment

name = "Alice"      # String
age = 30            # Integer
height = 5.5        # Float
is_student = True   # Boolean

In this example:
name stores a string.
age stores an integer.
height stores a float (decimal value).
is_student stores a boolean (True/False).


Basic Data Types

1. String (`str`): A sequence of characters. Defined with quotes.
text = "Hello, World!"

2. Integer (`int`): Whole numbers, positive or negative, without a decimal.
count = 10

3. Float (`float`): Numbers with decimal points.
temperature = 98.6

4. Boolean (`bool`): Represents True or False values.
is_active = True

2. Operators

Operators are symbols that perform operations on variables and values. They include arithmetic, comparison, logical, and more.

Arithmetic Operators

a = 10
b = 3
print(a + b)    # Addition
print(a - b)    # Subtraction
print(a * b)    # Multiplication
print(a / b)    # Division
print(a % b)    # Modulus (remainder)
print(a ** b)   # Exponentiation
print(a // b)   # Floor division

Comparison Operators

print(a == b)   # Equal to
print(a != b)   # Not equal to
print(a > b)    # Greater than
print(a < b)    # Less than
print(a >= b)   # Greater than or equal to
print(a <= b)   # Less than or equal to

Logical Operators

Used for combining conditions:
x = True
y = False
print(x and y)  # Logical AND
print(x or y)   # Logical OR
print(not x)    # Logical NOT

3. Control Flow

Control flow statements manage the execution flow of the program, including conditionals and loops.

Conditional Statements

Conditionals allow you to run code based on conditions using `if`, `elif`, and `else`.

age = 18
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

Loops

Loops allow you to repeat a block of code multiple times. Python has `for` and `while` loops. - For Loop: Iterates over a sequence.
for i in range(5):  # range(5) generates 0, 1, 2, 3, 4
    print(i)

- While Loop: Runs as long as a condition is true.
count = 0
while count < 5:
    print(count)
    count += 1

4. Functions

Functions are reusable blocks of code that perform a specific task. You can define functions with `def`.

Defining and Calling a Function

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

print(greet("Alice"))

Output:
Hello, Alice!


Function Parameters and Return Values

- Parameters: Variables that a function accepts as inputs.
- Return Value: Value that a function sends back to the caller with `return`.

Example:
def add(a, b):
    return a + b

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

Output:
8

5. Data Structures

Python provides several built-in data structures for storing and organizing data, such as lists, tuples, sets, and dictionaries.

Lists

Lists are ordered collections that are mutable (modifiable) and allow duplicate values.
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits)

Output:
['apple', 'banana', 'cherry', 'date']

Tuples

Tuples are ordered, immutable collections that allow duplicates.
coordinates = (10, 20)
print(coordinates)

Sets

Sets are unordered collections of unique values, meaning duplicates are not allowed.

unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers)

Output:
{1, 2, 3, 4}

Dictionaries

Dictionaries store data as key-value pairs and are unordered. Each key must be unique.
person = {"name": "Alice", "age": 30}
print(person["name"])

6. Input and Output

Use the `input()` function to get user input and `print()` to display output.

Getting User Input

name = input("Enter your name: ")
print("Hello, " + name + "!")

Output:
Enter your name: Alice
Hello, Alice!


7. Importing Modules

Python has a wide range of built-in modules that you can import to extend functionality. You can also install third-party modules.

Using the `math` Module

import math
print(math.sqrt(16))

Output:
4.0


8. Exception Handling

Use `try` and `except` to handle potential errors in your code gracefully.
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Output:
Cannot divide by zero!


9. Comments

Comments are ignored by Python and used to explain code. Single-line comments use `#`, while multi-line comments can use triple quotes (`"""`).
# This is a single-line comment

"""
This is a
multi-line comment
"""

Summary

Understanding these basic concepts will give you a solid foundation to explore more complex Python programming. Practice each topic individually to build confidence!

Previous: Your First Python Program | Next: Python PIP

<
>