Python Programming: Getting Started Guide
1. How to Install Python
Python is a versatile programming language used for web development, data analysis, AI, and more. Follow these steps to install Python:
- Visit the official Python website
- Download the latest version (or Python 3.12+ recommended for beginners)
- Run the installer and check "Add Python to PATH" during installation
- Verify installation by opening a terminal/command prompt and running:bash1
python --version
Alternatively, you can use Anaconda or Miniconda for a more comprehensive Python distribution that includes many data science packages.
2. Python Basics
Let's start with a simple "Hello, World!" program:
1print('Hello, World!')
Python uses indentation to define code blocks. Here's a simple example:
1if 5 > 2:
2print("Five is greater than two!")
3print("This is still part of the if block")
4print("This is outside the if block")
Comments in Python start with a # character:
1# This is a comment
2print("Hello, World!") # This is an inline comment
Python is case-sensitive, so variable
and Variable
are different variables.
3. Python Data Types
Python has several built-in data types:
Numeric Types
1# Integer
2x = 10
3print(x, type(x))
45# Float
6y = 10.5
7print(y, type(y))
89# Complex
10z = 1j
11print(z, type(z))
Text Type
1# String
2name = "Python"
3print(name, type(name))
45# String methods
6print(name.upper())
7print(name.lower())
8print(len(name))
Sequence Types
1# List (mutable)
2fruits = ["apple", "banana", "cherry"]
3print(fruits, type(fruits))
4fruits.append("orange")
5print(fruits)
67# Tuple (immutable)
8coordinates = (10, 20)
9print(coordinates, type(coordinates))
1011# Range
12numbers = range(5)
13print(list(numbers), type(numbers))
Mapping Type
1# Dictionary
2person = {
3"name": "John",
4"age": 30,
5"city": "New York"
6}
7print(person, type(person))
8print(person["name"])
Set Types
1# Set (unordered, no duplicates)
2fruits_set = {"apple", "banana", "cherry", "apple"}
3print(fruits_set, type(fruits_set)) # Note: duplicates are removed
Boolean Type
1# Boolean
2is_python_fun = True
3print(is_python_fun, type(is_python_fun))
4. Control Flow in Python
If-Else Statements
1age = 18
23if age < 18:
4print("You are a minor")
5elif age == 18:
6print("You just became an adult")
7else:
8print("You are an adult")
For Loops
1# Looping through a list
2fruits = ["apple", "banana", "cherry"]
3for fruit in fruits:
4print(fruit)
56# Looping through a range
7for i in range(5):
8print(i) # Prints 0, 1, 2, 3, 4
While Loops
1# While loop
2count = 0
3while count < 5:
4print(count)
5count += 1 # Increment count
Break and Continue
1# Break statement
2for i in range(10):
3if i == 5:
4break # Exit the loop when i is 5
5print(i)
67# Continue statement
8for i in range(10):
9if i % 2 == 0:
10continue # Skip even numbers
11print(i) # Prints only odd numbers
5. Functions in Python
Functions are defined using the def
keyword:
1# Simple function
2def greet(name):
3return f"Hello, {name}!"
45# Call the function
6message = greet("Python Learner")
7print(message)
89# Function with default parameter
10def greet_with_time(name, time="morning"):
11return f"Good {time}, {name}!"
1213print(greet_with_time("Alice"))
14print(greet_with_time("Bob", "evening"))
Lambda Functions
1# Lambda (anonymous) function
2multiply = lambda x, y: x * y
3print(multiply(5, 3)) # Outputs: 15
45# Lambda with built-in functions
6numbers = [1, 2, 3, 4, 5]
7squared = list(map(lambda x: x**2, numbers))
8print(squared) # Outputs: [1, 4, 9, 16, 25]
*args and **kwargs
1# *args for variable number of arguments
2def sum_all(*args):
3return sum(args)
45print(sum_all(1, 2, 3, 4, 5)) # Outputs: 15
67# **kwargs for variable keyword arguments
8def print_info(**kwargs):
9for key, value in kwargs.items():
10print(f"{key}: {value}")
1112print_info(name="Alice", age=25, country="Wonderland")
6. Working with Modules
Python modules are files containing Python code that can be imported and used in other Python programs:
Built-in Modules
1# Import the math module
2import math
34# Use functions from the module
5print(math.sqrt(16)) # Square root: 4.0
6print(math.pi) # Pi: 3.141592653589793
78# Import specific functions
9from random import randint
10print(randint(1, 10)) # Random integer between 1 and 10
1112# Import with alias
13import datetime as dt
14now = dt.datetime.now()
15print(now)
Creating Your Own Module
Create a file named mymodule.py
:
1# mymodule.py
2def greeting(name):
3return f"Hello, {name}!"
45def add(a, b):
6return a + b
78PI = 3.14159
Then import and use it in another file:
1# main.py
2import mymodule
34print(mymodule.greeting("Python User"))
5print(mymodule.add(5, 3))
6print(mymodule.PI)
Installing External Packages
Use pip to install external packages:
1pip install requests
Then use the package in your code:
1import requests
23response = requests.get("https://api.github.com")
4print(response.status_code)
5print(response.json())
7. Example of Creating a Simple Python Program
Let's create a simple temperature converter program:
1def celsius_to_fahrenheit(celsius):
2"""Convert Celsius to Fahrenheit."""
3return (celsius * 9/5) + 32
45def fahrenheit_to_celsius(fahrenheit):
6"""Convert Fahrenheit to Celsius."""
7return (fahrenheit - 32) * 5/9
89def main():
10print("Temperature Converter")
11print("1. Celsius to Fahrenheit")
12print("2. Fahrenheit to Celsius")
13
14choice = input("Enter your choice (1/2): ")
15
16if choice == '1':
17celsius = float(input("Enter temperature in Celsius: "))
18fahrenheit = celsius_to_fahrenheit(celsius)
19print(f"{celsius}°C is equal to {fahrenheit:.2f}°F")
20elif choice == '2':
21fahrenheit = float(input("Enter temperature in Fahrenheit: "))
22celsius = fahrenheit_to_celsius(fahrenheit)
23print(f"{fahrenheit}°F is equal to {celsius:.2f}°C")
24else:
25print("Invalid choice")
2627if __name__ == "__main__":
28main()
Save this code to a file (e.g., temp_converter.py
) and run it with:
1python temp_converter.py
8. Object-Oriented Programming in Python
Python supports object-oriented programming with classes and objects:
1class Person:
2# Class attribute
3species = "Homo sapiens"
4
5# Constructor method
6def __init__(self, name, age):
7# Instance attributes
8self.name = name
9self.age = age
10
11# Instance method
12def introduce(self):
13return f"Hi, I'm {self.name} and I'm {self.age} years old."
14
15# Instance method
16def celebrate_birthday(self):
17self.age += 1
18return f"Happy Birthday! Now I'm {self.age} years old."
1920# Create objects of the Person class
21alice = Person("Alice", 25)
22bob = Person("Bob", 30)
2324# Access attributes and call methods
25print(alice.name) # Alice
26print(bob.age) # 30
27print(alice.species) # Homo sapiens
28print(bob.introduce()) # Hi, I'm Bob and I'm 30 years old.
29print(alice.celebrate_birthday()) # Happy Birthday! Now I'm 26 years old.
Inheritance
1class Student(Person):
2# Constructor method
3def __init__(self, name, age, student_id):
4# Call the parent class constructor
5super().__init__(name, age)
6self.student_id = student_id
7
8# Override the introduce method
9def introduce(self):
10return f"Hi, I'm {self.name}, a student with ID {self.student_id}."
11
12# New method specific to Student
13def study(self, subject):
14return f"{self.name} is studying {subject}."
1516# Create a Student object
17charlie = Student("Charlie", 20, "S12345")
1819# Access attributes and call methods
20print(charlie.name) # Charlie
21print(charlie.student_id) # S12345
22print(charlie.introduce()) # Hi, I'm Charlie, a student with ID S12345.
23print(charlie.study("Python")) # Charlie is studying Python.