Table of contents

Syntax and Operations

In this section, we’ll cover the fundamental aspects of Python syntax and operations. Understanding these basics is crucial for building more complex programs and developing a solid foundation in Python.

1. Python Syntax

Python uses indentation to define the scope of loops, functions, and classes. Unlike other programming languages that use curly braces {} to mark code blocks, Python relies on indentation levels.

if True: print("This is inside the if block") if 2 > 1: print("This is inside the nested if block") print("This is outside the if block")

Comments are lines in the code that are not executed. They are used to explain the code and make it more readable. Python supports both single-line and multi-line comments.

  • Single-line comment: Use the # symbol.
# This is a single-line comment print("Hello, World!") # This is an inline comment
  • Multi-line comment: Use triple quotes ''' or """.
""" This is a multi-line comment It can span multiple lines """ print("Hello, World!")

Variables are used to store data values. Python has various data types including integers, floats, strings, and booleans.

Integer: Whole numbers

x = 10 print(x) # Output: 10

Float: Numbers with a decimal point

y = 3.14 print(y) # Output: 3.14

String: Sequence of characters

name = "Alice" print(name) # Output: Alice

Boolean: Represents True or False

is_active = True print(is_active) # Output: True

Here’s a quick comparison table of common data types in Python:

Data Type Example Description
Integer 10 Whole numbers
Float 3.14 Decimal numbers
String "Hello" Sequence of characters
Boolean True Logical value (True or False)

Python supports various arithmetic operations like addition, subtraction, multiplication, division, and more.

a = 5 b = 2 print(a + b) # Addition, Output: 7 print(a - b) # Subtraction, Output: 3 print(a * b) # Multiplication, Output: 10 print(a / b) # Division, Output: 2.5 print(a // b) # Floor Division, Output: 2 print(a % b) # Modulus, Output: 1 print(a ** b) # Exponentiation, Output: 25

Assignment operators are used to assign values to variables. Python supports various assignment operators such as =, +=, -=, *=, /=, and more.

x = 5 x += 3 # Equivalent to x = x + 3 print(x) # Output: 8 x -= 2 # Equivalent to x = x - 2 print(x) # Output: 6 x *= 4 # Equivalent to x = x * 4 print(x) # Output: 24 x /= 2 # Equivalent to x = x / 2 print(x) # Output: 12.0

Comparison operators are used to compare two values and return a boolean result (True or False).

a = 5 b = 3 print(a == b) # Equal to, Output: False print(a != b) # Not equal to, Output: True print(a > b) # Greater than, Output: True print(a < b) # Less than, Output: False print(a >= b) # Greater than or equal to, Output: True print(a <= b) # Less than or equal to, Output: False

Logical operators are used to combine conditional statements. Python supports and, or, and not operators.

a = True b = False print(a and b) # Logical AND, Output: False print(a or b) # Logical OR, Output: True print(not a) # Logical NOT, Output: False

Bitwise operators perform operations on the binary representations of integers. Python supports & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).

a = 5 # Binary: 0101 b = 3 # Binary: 0011 print(a & b) # Bitwise AND, Output: 1 (Binary: 0001) print(a | b) # Bitwise OR, Output: 7 (Binary: 0111) print(a ^ b) # Bitwise XOR, Output: 6 (Binary: 0110) print(~a) # Bitwise NOT, Output: -6 (Binary: 1010) print(a << 1) # Left shift, Output: 10 (Binary: 1010) print(a >> 1) # Right shift, Output: 2 (Binary: 0010)

Here’s a quick comparison table of common operators in Python:

Operator Type Example Description
Arithmetic `+`, `-`, `*`, `/`, `//`, `%`, `**` Basic mathematical operations
Assignment `=`, `+=`, `-=`, `*=`, `/=`, `//=`, `%=` Assign values to variables
Comparison `==`, `!=`, `>`, `<`, `>=`, `<=` Compare two values and return `True` or `False`
Logical `and`, `or`, `not` Combine conditional statements
Bitwise `&`, `|`, `^`, `~`, `<<`, `>>` Perform operations on binary representations

Create a simple calculator that performs basic arithmetic operations.

# Basic Calculator def calculator(a, b, operation): if operation == "add": return a + b elif operation == "subtract": return a - b elif operation == "multiply": return a * b elif operation == "divide": return a / b else: return "Invalid operation" # User input num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) op = input("Enter operation (add, subtract, multiply, divide): ") # Calculate and print result result = calculator(num1, num2, op) print("Result:", result)

Use logical operators to check if a number is within a specified range.

# Check if a number is within range def is_within_range(num, lower, upper): return lower <= num <= upper # User input number = int(input("Enter a number: ")) low = int(input("Enter the lower bound: ")) up = int(input("Enter the upper bound: ")) # Check and print result if is_within_range(number, low, up): print(f"{number} is within the range {low} to {up}.") else: print(f"{number} is not within the range {low} to {up}.")

Write a program to check if a number is even or odd.

# Check if a number is even or odd num = int(input("Enter a number: ")) if num % 2 == 0: print(f"{num} is even.") else: print(f"{num} is odd.")

Write a program to check if a year is a leap year.

# Check if a year is a leap year year = int(input("Enter a year: ")) if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(f"{year} is a leap year.") else: print(f"{year} is not a leap year.")

Conclusion

In this section, we’ve covered the fundamental aspects of Python syntax and basic operations, including arithmetic, assignment, comparison, logical, and bitwise operations. These are the building blocks of Python programming and are essential for writing more complex code. Make sure to practice these concepts with the provided examples and exercises to strengthen your understanding. In the next section, we will delve into control structures such as loops and conditional