Python Basics - Getting Started with Python
Learn Python programming from scratch. Master variables, data types, input/output, and write your first Python programs.
Introduction
What You'll Learn
- How to install and set up Python
- Python syntax and basic rules
- Variables and data types (strings, numbers, booleans)
- Input and output operations
- Basic operators and expressions
- Writing and running your first Python program
- Best practices for Python code
Why This Topic is Important
Python is one of the most popular and beginner-friendly programming languages. It's used in web development, data science, artificial intelligence, automation, and more. Python's simple syntax makes it an excellent first language, while its power makes it valuable for professional development.
Real-World Applications
- Web development (Django, Flask)
- Data science and analytics
- Machine learning and AI
- Automation and scripting
- Game development
- Desktop applications
- API development
Learning Objectives
- Set up Python development environment
- Understand Python syntax and indentation
- Work with variables and data types
- Perform input and output operations
- Use basic operators and expressions
- Write and execute Python programs
- Follow Python coding conventions
What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum and first released in 1991, Python emphasizes code readability and allows programmers to express concepts in fewer lines of code than languages like C++ or Java.
Python is an interpreted language, meaning code is executed line by line, making it great for learning and rapid development. It's also cross-platform, running on Windows, macOS, and Linux.
📝 Note
Python uses indentation to define code blocks, unlike many languages that use curly braces. This makes Python code more readable but requires careful attention to spacing.
Installing Python
Before you can write Python code, you need to install Python on your computer.
- Visit python.org/downloads
- Download the latest Python 3.x version for your operating system
- Run the installer and check "Add Python to PATH"
- Verify installation by opening terminal/command prompt and typing: `python --version`
# Check Python version
python --version
# Output: Python 3.11.0 (or similar)
# Run Python interactively
python
# This opens Python REPL (Read-Eval-Print Loop)After installation, verify Python is working by checking the version. You can also run Python interactively.
Your First Python Program
Let's start with the classic "Hello, World!" program. Create a file named `hello.py` and write:
# This is a comment
print("Hello, World!")
# Run this file with: python hello.pyThe `print()` function displays output. Comments start with `#`. Save this as a `.py` file and run it.
💡 Tip
Python files should have a `.py` extension. You can run them from the command line using `python filename.py`.
Variables and Data Types
Variables are containers for storing data. In Python, you don't need to declare variable types - Python figures it out automatically (this is called dynamic typing).
Creating Variables
# String variable
name = "Alice"
print(name) # Output: Alice
# Integer variable
age = 25
print(age) # Output: 25
# Float (decimal) variable
height = 5.6
print(height) # Output: 5.6
# Boolean variable
is_student = True
print(is_student) # Output: TrueVariables are created by assigning values. Python automatically determines the data type.
Data Types
# String (str)
text = "Hello, Python!"
print(type(text)) # <class 'str'>
# Integer (int)
number = 42
print(type(number)) # <class 'int'>
# Float (float)
decimal = 3.14
print(type(decimal)) # <class 'float'>
# Boolean (bool)
is_active = True
print(type(is_active)) # <class 'bool'>
# List (list)
fruits = ["apple", "banana", "orange"]
print(type(fruits)) # <class 'list'>
# Dictionary (dict)
person = {"name": "Alice", "age": 25}
print(type(person)) # <class 'dict'>Use `type()` to check the data type of a variable. Python has several built-in data types.
📊 Table:
Python Data Types Table: Columns are "Type", "Example", "Description". Rows: str - "Hello" - Text/string data, int - 42 - Whole numbers, float - 3.14 - Decimal numbers, bool - True/False - Boolean values, list - [1,2,3] - Ordered collection, dict - {"key":"value"} - Key-value pairs.
Alt text: Python data types reference table
Input and Output
Output with print()
# Basic print
print("Hello, World!")
# Print multiple values
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Formatted strings (f-strings) - Python 3.6+
print(f"Name: {name}, Age: {age}")
# Print with separator
print("Python", "is", "awesome", sep="-") # Output: Python-is-awesome
# Print without newline
print("Hello", end=" ")
print("World") # Output: Hello WorldThe `print()` function is versatile. You can print multiple values, use f-strings for formatting, and control separators and endings.
Input with input()
# Get user input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Input always returns a string
age = input("Enter your age: ")
print(type(age)) # <class 'str'>
# Convert input to number
age = int(input("Enter your age: "))
print(f"You are {age} years old")
print(type(age)) # <class 'int'>The `input()` function gets user input. It always returns a string, so convert to numbers when needed using `int()` or `float()`.
Operators
Arithmetic Operators
# Addition
result = 10 + 5
print(result) # 15
# Subtraction
result = 10 - 5
print(result) # 5
# Multiplication
result = 10 * 5
print(result) # 50
# Division (always returns float)
result = 10 / 5
print(result) # 2.0
# Floor division (integer division)
result = 10 // 3
print(result) # 3
# Modulus (remainder)
result = 10 % 3
print(result) # 1
# Exponentiation (power)
result = 2 ** 3
print(result) # 8Python supports all standard arithmetic operations. Division always returns a float, use `//` for integer division.
Comparison Operators
x = 10
y = 5
print(x == y) # False (equal)
print(x != y) # True (not equal)
print(x > y) # True (greater than)
print(x < y) # False (less than)
print(x >= y) # True (greater than or equal)
print(x <= y) # False (less than or equal)Comparison operators return boolean values (True or False).
Logical Operators
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # FalseLogical operators work with boolean values: `and`, `or`, and `not`.
String Operations
# String concatenation
first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name) # Alice Smith
# String repetition
greeting = "Hello! " * 3
print(greeting) # Hello! Hello! Hello!
# String methods
text = " Python Programming "
print(text.strip()) # Remove whitespace
print(text.upper()) # Uppercase
print(text.lower()) # Lowercase
print(text.replace("Python", "Java")) # Replace
# String formatting
name = "Alice"
age = 25
message = f"My name is {name} and I'm {age} years old"
print(message)Python provides many string operations. F-strings (formatted string literals) are the modern way to format strings.
Complete Example: Personal Information Program
# Get user information
print("=== Personal Information Form ===")
name = input("Enter your name: ")
age = int(input("Enter your age: "))
city = input("Enter your city: ")
# Process and display
print(f"\nHello, {name}!")
print(f"You are {age} years old.")
print(f"You live in {city}.")
# Calculate years until 100
years_to_100 = 100 - age
print(f"You will be 100 years old in {years_to_100} years!")This complete program demonstrates input, variables, type conversion, and formatted output.
✅ Best practice
Always validate user input in real applications. Use try-except blocks to handle errors when converting input to numbers.
Python Naming Conventions
- Use lowercase with underscores for variables: `user_name`, `total_count`
- Use uppercase for constants: `MAX_SIZE`, `PI`
- Use descriptive names: `age` not `a`, `user_name` not `un`
- Avoid Python keywords: don't use `print`, `if`, `for` as variable names
- Class names use PascalCase: `MyClass`, `UserAccount`
📊 Comparison:
Good vs Bad Variable Names: Left side shows "Good" with examples like user_name, total_price, is_active. Right side shows "Bad" with examples like u, tp, flag. Green checkmarks on good examples, red X marks on bad examples.
Alt text: Python variable naming conventions comparison
Practical Examples
Example 1: Hello World Program
print("Hello, World!")
print("Welcome to Python!")The simplest Python program - printing messages to the console.
Expected Output:
Hello, World! Welcome to Python!
Example 2: Variable Assignment and Types
name = "Python"
version = 3.11
is_awesome = True
print(f"{name} version {version} is awesome: {is_awesome}")Demonstrates different data types and f-string formatting.
Expected Output:
Python version 3.11 is awesome: True
Example 3: Simple Calculator
a = 10
b = 5
print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b}")Basic arithmetic operations with formatted output.
Expected Output:
Addition: 15 Subtraction: 5 Multiplication: 50 Division: 2.0
Example 4: User Input Program
name = input("What's your name? ")
age = int(input("How old are you? "))
print(f"Hello, {name}! You are {age} years old.")
print(f"Next year you'll be {age + 1}.")Getting user input and performing calculations with it.
Expected Output:
What's your name? [user input] How old are you? [user input] Hello, [name]! You are [age] years old. Next year you'll be [age+1].
Example 5: String Operations
text = "python programming"
print(text.upper())
print(text.capitalize())
print(text.replace("python", "Python"))
print(f"Length: {len(text)}")Common string methods and operations.
Expected Output:
PYTHON PROGRAMMING Python programming Python programming Length: 18
Quiz: Test Your Knowledge
1. What is the output of: print(10 // 3)?
2. What data type does input() always return?
3. Which operator is used for exponentiation in Python?
4. What is the correct way to format a string with variables in Python 3.6+?
5. What does Python use to define code blocks?
Practice Exercises
Exercise 1: Create a Greeting Program
Write a program that asks for the user's name and age, then greets them and tells them how old they are.
Show Hints
- Use input() to get user input
- Convert age to int using int()
- Use f-strings for formatting
- Print a personalized greeting
Show Solution
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")Exercise 2: Build a Simple Calculator
Create a program that takes two numbers and an operation (+, -, *, /) and performs the calculation.
Show Hints
- Get two numbers using input() and convert to float
- Get the operation as a string
- Use if-elif to check the operation
- Print the result
Exercise 3: Create a Temperature Converter
Write a program that converts Celsius to Fahrenheit. Formula: F = (C * 9/5) + 32
Show Hints
- Get Celsius temperature from user
- Convert to float
- Apply the formula
- Display the result
Exercise 4: Build a String Manipulator
Create a program that takes a string and displays it in uppercase, lowercase, and with first letter capitalized.
Show Hints
- Use input() to get a string
- Use .upper(), .lower(), and .capitalize() methods
- Print all three versions
Exercise 5: Create a Personal Information Form
Build a program that collects name, email, phone, and city, then displays a formatted summary.
Show Hints
- Get multiple inputs
- Use f-strings for formatting
- Create a nice output format
- Add some visual separators