PYTHON Tutorial

Syntax and Semantics

Python is a high-level programming language known for its readability and simplicity. Let's break down the key concepts and syntax:

Variables

  • Variables store values and are created without specifying their data type.
  • Assignment operator (=) assigns values to variables.
  • Example: my_name = "John"

Data Types

  • Python dynamically determines data types.
  • Common types include:
    • Integers (e.g., 123)
    • Floats (e.g., 12.34)
    • Strings (e.g., "Hello")
    • Booleans (e.g., True, False)

Conditional Statements

  • if statements evaluate conditions and execute code if True.
  • elif and else clauses provide alternative paths.
  • Example:
    if my_age > 18:
        print("You are an adult.")
    elif my_age < 18:
        print("You are a minor.")
    else:
        print("You are 18 years old.")
    

Loop Statements

  • for loops iterate over sequences.
  • while loops execute until a condition becomes False.
  • Example:
    for item in my_list:
        print(item)
    

Functions

  • Functions encapsulate reusable code blocks.
  • Defined using the def keyword.
  • Arguments are passed within parentheses.
  • Example:
    def greet(name):
        print("Hello, " + name)
    greet("John")
    

Classes

  • Classes define templates for creating objects.
  • Objects have attributes and methods.
  • Example:
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    person1 = Person("John", 30)
    print(person1.name)  # Prints "John"
    

Basic Example:

# Create a variable
my_name = "John"

# Print the variable
print("Hello, " + my_name)

# Check if the name is "John"
if my_name == "John":
    print("You are John!")