Python is a high-level, interpreted programming language created by Guido van Rossum and first released in 1991. Python’s design philosophy emphasizes code readability and simplicity, making it an excellent choice for beginners learning programming. The Python programming language supports multiple programming paradigms including procedural, object-oriented, and functional programming.
Python gets its name from the British comedy series “Monty Python’s Flying Circus,” reflecting the language’s fun and approachable nature. The Python language has gained massive popularity due to its versatility and ease of use across various domains including web development, data science, artificial intelligence, and automation.
Python’s syntax is designed to be intuitive and similar to English, making it perfect for beginners. The Python programming language uses indentation to define code blocks instead of curly braces, which enforces clean and readable code structure.
# Simple and readable syntax
if 5 > 3:
print("Five is greater than three")
Python is an interpreted language, meaning you don’t need to compile your code before running it. The Python interpreter executes code line by line, making debugging easier and development faster.
# You can run Python code directly
print("Hello, World!")
# This executes immediately without compilation
Python code can run on different operating systems including Windows, macOS, and Linux without modification. This cross-platform nature makes Python programming highly versatile.
Python comes with a comprehensive standard library that provides modules and functions for common programming tasks. This “batteries included” philosophy reduces the need for external dependencies.
# Built-in modules for various tasks
import datetime
import random
import os
# Get current date and time
current_time = datetime.datetime.now()
print(f"Current time: {current_time}")
Python uses dynamic typing, meaning you don’t need to declare variable types explicitly. The Python interpreter determines the type at runtime.
# No need to declare variable types
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
In Python programming, variables are created when you assign a value to them. Python supports various data types including integers, floats, strings, booleans, lists, tuples, and dictionaries.
# Integer
student_count = 30
# Float
average_score = 85.5
# String
course_name = "Python Programming"
# Boolean
is_active = True
# List
programming_languages = ["Python", "Java", "JavaScript"]
# Tuple
coordinates = (10, 20)
# Dictionary
student_info = {"name": "John", "age": 20, "grade": "A"}
Comments are essential for code documentation. Python supports both single-line and multi-line comments.
# This is a single-line comment
"""
This is a multi-line comment
spanning multiple lines
"""
def calculate_area(length, width):
"""
This is a docstring that describes
what this function does
"""
return length * width
Python uses indentation to define code blocks. This is a unique feature that enforces clean code structure.
# Correct indentation
if True:
print("This is properly indented")
if True:
print("This is nested indentation")
# Function with proper indentation
def greet_user(name):
if name:
print(f"Hello, {name}!")
else:
print("Hello, Guest!")
Python provides built-in functions for input and output operations.
# Output using print()
print("Welcome to Python!")
# Input using input()
user_name = input("Enter your name: ")
print(f"Hello, {user_name}!")
# Multiple values in print
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
Python supports three numeric types: integers, floats, and complex numbers.
# Integer
whole_number = 42
negative_number = -17
# Float
decimal_number = 3.14159
scientific_notation = 2.5e-4
# Complex
complex_number = 3 + 4j
# Type checking
print(type(whole_number)) # <class 'int'>
print(type(decimal_number)) # <class 'float'>
print(type(complex_number)) # <class 'complex'>
Strings in Python are sequences of characters enclosed in quotes.
# String creation
single_quoted = 'Hello, World!'
double_quoted = "Python Programming"
triple_quoted = """This is a
multi-line string"""
# String methods
message = "python programming"
print(message.upper()) # PYTHON PROGRAMMING
print(message.capitalize()) # Python programming
print(message.replace("python", "Python")) # Python programming
# String formatting
name = "Alice"
age = 25
formatted_string = f"My name is {name} and I am {age} years old"
print(formatted_string)
Python uses True
and False
for boolean values.
# Boolean values
is_python_fun = True
is_difficult = False
# Boolean operations
print(True and False) # False
print(True or False) # True
print(not True) # False
# Comparison operations
print(5 > 3) # True
print(10 == 10) # True
print("python" == "Python") # False
Python uses if
, elif
, and else
for conditional execution.
# Simple if statement
temperature = 25
if temperature > 30:
print("It's hot outside")
elif temperature > 20:
print("It's warm outside")
else:
print("It's cool outside")
# Nested conditions
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Your grade is: {grade}")
Python supports for
and while
loops for iteration.
# For loop with range
for i in range(5):
print(f"Iteration {i}")
# For loop with list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}")
# While loop
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
# Loop with break and continue
for num in range(10):
if num == 3:
continue # Skip 3
if num == 7:
break # Stop at 7
print(num)
Functions are reusable blocks of code that perform specific tasks.
# Basic function
def greet():
print("Hello, World!")
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
# Function with return value
def add_numbers(a, b):
return a + b
# Function with default parameters
def introduce(name, age=18):
print(f"My name is {name} and I am {age} years old")
# Function with multiple return values
def calculate_stats(numbers):
total = sum(numbers)
average = total / len(numbers)
return total, average
# Calling functions
greet()
greet_person("Alice")
result = add_numbers(5, 3)
print(f"Sum: {result}")
introduce("Bob")
introduce("Charlie", 25)
total, avg = calculate_stats([1, 2, 3, 4, 5])
print(f"Total: {total}, Average: {avg}")
Lists are ordered, mutable collections of items.
# Creating lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
# List operations
fruits = ["apple", "banana", "orange"]
fruits.append("grape") # Add to end
fruits.insert(1, "mango") # Insert at index
fruits.remove("banana") # Remove by value
last_fruit = fruits.pop() # Remove and return last
# List slicing
print(fruits[0]) # First element
print(fruits[-1]) # Last element
print(fruits[1:3]) # Elements from index 1 to 2
Tuples are ordered, immutable collections.
# Creating tuples
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_item = (42,) # Note the comma
# Tuple operations
point = (5, 10)
x, y = point # Tuple unpacking
print(f"X: {x}, Y: {y}")
# Tuple methods
numbers = (1, 2, 3, 2, 4, 2)
print(numbers.count(2)) # Count occurrences
print(numbers.index(3)) # Find index
Dictionaries store key-value pairs.
# Creating dictionaries
empty_dict = {}
student = {"name": "Alice", "age": 20, "grade": "A"}
# Dictionary operations
student["email"] = "alice@example.com" # Add new key-value
print(student["name"]) # Access value
print(student.get("phone", "Not found")) # Safe access
# Dictionary methods
print(student.keys()) # Get all keys
print(student.values()) # Get all values
print(student.items()) # Get key-value pairs
# Dictionary iteration
for key, value in student.items():
print(f"{key}: {value}")
Python uses try-except blocks to handle errors gracefully.
# Basic exception handling
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("Operation completed successfully!")
finally:
print("This always executes")
Python provides built-in functions for file handling.
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!\n")
file.write("This is a test file.\n")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
# Appending to a file
with open("example.txt", "a") as file:
file.write("This line is appended.\n")
Here’s a comprehensive example that demonstrates various Python concepts:
#!/usr/bin/env python3
"""
Student Grade Management System
A complete Python program demonstrating various concepts
"""
import datetime
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.grades = []
self.created_at = datetime.datetime.now()
def add_grade(self, subject, score):
"""Add a grade for a subject"""
if 0 <= score <= 100:
self.grades.append({"subject": subject, "score": score})
return True
return False
def calculate_average(self):
"""Calculate average grade"""
if not self.grades:
return 0
total = sum(grade["score"] for grade in self.grades)
return total / len(self.grades)
def get_grade_letter(self):
"""Get letter grade based on average"""
avg = self.calculate_average()
if avg >= 90:
return "A"
elif avg >= 80:
return "B"
elif avg >= 70:
return "C"
elif avg >= 60:
return "D"
else:
return "F"
def __str__(self):
return f"Student: {self.name}, Age: {self.age}, Average: {self.calculate_average():.2f}"
def main():
"""Main function to run the student management system"""
students = []
print("=== Student Grade Management System ===")
print("Welcome to the Python Student Management System!")
while True:
print("\nOptions:")
print("1. Add new student")
print("2. Add grade to student")
print("3. View all students")
print("4. Save data to file")
print("5. Load data from file")
print("6. Exit")
try:
choice = input("Enter your choice (1-6): ")
if choice == "1":
name = input("Enter student name: ")
age = int(input("Enter student age: "))
student = Student(name, age)
students.append(student)
print(f"Student {name} added successfully!")
elif choice == "2":
if not students:
print("No students found. Please add a student first.")
continue
print("Students:")
for i, student in enumerate(students):
print(f"{i + 1}. {student.name}")
try:
index = int(input("Select student number: ")) - 1
if 0 <= index < len(students):
subject = input("Enter subject: ")
score = float(input("Enter score (0-100): "))
if students[index].add_grade(subject, score):
print("Grade added successfully!")
else:
print("Invalid score. Please enter a score between 0 and 100.")
else:
print("Invalid student number.")
except ValueError:
print("Please enter a valid number.")
elif choice == "3":
if not students:
print("No students found.")
else:
print("\n=== Student Reports ===")
for student in students:
print(f"\n{student}")
print(f"Letter Grade: {student.get_grade_letter()}")
print(f"Enrolled: {student.created_at.strftime('%Y-%m-%d')}")
if student.grades:
print("Grades:")
for grade in student.grades:
print(f" - {grade['subject']}: {grade['score']}")
else:
print(" No grades recorded")
elif choice == "4":
if students:
data = []
for student in students:
student_data = {
"name": student.name,
"age": student.age,
"grades": student.grades,
"created_at": student.created_at.isoformat()
}
data.append(student_data)
with open("students.json", "w") as file:
json.dump(data, file, indent=2)
print("Data saved to students.json")
else:
print("No students to save.")
elif choice == "5":
try:
with open("students.json", "r") as file:
data = json.load(file)
students = []
for student_data in data:
student = Student(student_data["name"], student_data["age"])
student.grades = student_data["grades"]
student.created_at = datetime.datetime.fromisoformat(student_data["created_at"])
students.append(student)
print(f"Loaded {len(students)} students from file.")
except FileNotFoundError:
print("No saved data found.")
except json.JSONDecodeError:
print("Error reading data file.")
elif choice == "6":
print("Thank you for using the Student Management System!")
break
else:
print("Invalid choice. Please enter a number between 1 and 6.")
except KeyboardInterrupt:
print("\nProgram interrupted by user.")
break
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
When you run the complete program above, you’ll see:
=== Student Grade Management System ===
Welcome to the Python Student Management System!
Options:
1. Add new student
2. Add grade to student
3. View all students
4. Save data to file
5. Load data from file
6. Exit
Enter your choice (1-6): 1
Enter student name: Alice Johnson
Enter student age: 20
Student Alice Johnson added successfully!
Options:
1. Add new student
2. Add grade to student
3. View all students
4. Save data to file
5. Load data from file
6. Exit
Enter your choice (1-6): 2
Students:
1. Alice Johnson
Select student number: 1
Enter subject: Mathematics
Enter score (0-100): 95
Grade added successfully!
Options:
1. Add new student
2. Add grade to student
3. View all students
4. Save data to file
5. Load data from file
6. Exit
Enter your choice (1-6): 3
=== Student Reports ===
Student: Alice Johnson, Age: 20, Average: 95.00
Letter Grade: A
Enrolled: 2025-07-10
Grades:
- Mathematics: 95
To start your Python programming journey, visit the official Python website to download and install Python on your system. The Python interpreter comes with IDLE (Integrated Development and Learning Environment), which is perfect for beginners.
For more advanced development, consider using IDEs like PyCharm, Visual Studio Code, or Jupyter Notebooks. The Python documentation provides comprehensive guides and references for all Python features.
This Python tutorial covered the essential concepts of Python introduction including syntax, data types, control flow, functions, and practical examples. As you continue your Python programming journey, practice writing code regularly and explore Python’s extensive ecosystem of libraries and frameworks.
Remember, Python programming is about writing clean, readable code that solves real-world problems. Start with simple programs and gradually build more complex applications as you become comfortable with the language fundamentals covered in this Python introduction tutorial.