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:

  1. Visit the official Python website
  2. Download the latest version (or Python 3.12+ recommended for beginners)
  3. Run the installer and check "Add Python to PATH" during installation
  4. Verify installation by opening a terminal/command prompt and running:
    bash
    1python --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:

python
1print('Hello, World!')

Python uses indentation to define code blocks. Here's a simple example:

python
1if 5 > 2:
2 print("Five is greater than two!")
3 print("This is still part of the if block")
4print("This is outside the if block")

Comments in Python start with a # character:

python
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

python
1# Integer
2x = 10
3print(x, type(x))
4
5# Float
6y = 10.5
7print(y, type(y))
8
9# Complex
10z = 1j
11print(z, type(z))

Text Type

python
1# String
2name = "Python"
3print(name, type(name))
4
5# String methods
6print(name.upper())
7print(name.lower())
8print(len(name))

Sequence Types

python
1# List (mutable)
2fruits = ["apple", "banana", "cherry"]
3print(fruits, type(fruits))
4fruits.append("orange")
5print(fruits)
6
7# Tuple (immutable)
8coordinates = (10, 20)
9print(coordinates, type(coordinates))
10
11# Range
12numbers = range(5)
13print(list(numbers), type(numbers))

Mapping Type

python
1# Dictionary
2person = {
3 "name": "John",
4 "age": 30,
5 "city": "New York"
6}
7print(person, type(person))
8print(person["name"])

Set Types

python
1# Set (unordered, no duplicates)
2fruits_set = {"apple", "banana", "cherry", "apple"}
3print(fruits_set, type(fruits_set)) # Note: duplicates are removed

Boolean Type

python
1# Boolean
2is_python_fun = True
3print(is_python_fun, type(is_python_fun))

4. Control Flow in Python

If-Else Statements

python
1age = 18
2
3if age < 18:
4 print("You are a minor")
5elif age == 18:
6 print("You just became an adult")
7else:
8 print("You are an adult")

For Loops

python
1# Looping through a list
2fruits = ["apple", "banana", "cherry"]
3for fruit in fruits:
4 print(fruit)
5
6# Looping through a range
7for i in range(5):
8 print(i) # Prints 0, 1, 2, 3, 4

While Loops

python
1# While loop
2count = 0
3while count < 5:
4 print(count)
5 count += 1 # Increment count

Break and Continue

python
1# Break statement
2for i in range(10):
3 if i == 5:
4 break # Exit the loop when i is 5
5 print(i)
6
7# Continue statement
8for i in range(10):
9 if i % 2 == 0:
10 continue # Skip even numbers
11 print(i) # Prints only odd numbers

5. Functions in Python

Functions are defined using the def keyword:

python
1# Simple function
2def greet(name):
3 return f"Hello, {name}!"
4
5# Call the function
6message = greet("Python Learner")
7print(message)
8
9# Function with default parameter
10def greet_with_time(name, time="morning"):
11 return f"Good {time}, {name}!"
12
13print(greet_with_time("Alice"))
14print(greet_with_time("Bob", "evening"))

Lambda Functions

python
1# Lambda (anonymous) function
2multiply = lambda x, y: x * y
3print(multiply(5, 3)) # Outputs: 15
4
5# 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

python
1# *args for variable number of arguments
2def sum_all(*args):
3 return sum(args)
4
5print(sum_all(1, 2, 3, 4, 5)) # Outputs: 15
6
7# **kwargs for variable keyword arguments
8def print_info(**kwargs):
9 for key, value in kwargs.items():
10 print(f"{key}: {value}")
11
12print_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

python
1# Import the math module
2import math
3
4# Use functions from the module
5print(math.sqrt(16)) # Square root: 4.0
6print(math.pi) # Pi: 3.141592653589793
7
8# Import specific functions
9from random import randint
10print(randint(1, 10)) # Random integer between 1 and 10
11
12# Import with alias
13import datetime as dt
14now = dt.datetime.now()
15print(now)

Creating Your Own Module

Create a file named mymodule.py:

python
1# mymodule.py
2def greeting(name):
3 return f"Hello, {name}!"
4
5def add(a, b):
6 return a + b
7
8PI = 3.14159

Then import and use it in another file:

python
1# main.py
2import mymodule
3
4print(mymodule.greeting("Python User"))
5print(mymodule.add(5, 3))
6print(mymodule.PI)

Installing External Packages

Use pip to install external packages:

bash
1pip install requests

Then use the package in your code:

python
1import requests
2
3response = 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:

python
1def celsius_to_fahrenheit(celsius):
2 """Convert Celsius to Fahrenheit."""
3 return (celsius * 9/5) + 32
4
5def fahrenheit_to_celsius(fahrenheit):
6 """Convert Fahrenheit to Celsius."""
7 return (fahrenheit - 32) * 5/9
8
9def main():
10 print("Temperature Converter")
11 print("1. Celsius to Fahrenheit")
12 print("2. Fahrenheit to Celsius")
13
14 choice = input("Enter your choice (1/2): ")
15
16 if choice == '1':
17 celsius = float(input("Enter temperature in Celsius: "))
18 fahrenheit = celsius_to_fahrenheit(celsius)
19 print(f"{celsius}°C is equal to {fahrenheit:.2f}°F")
20 elif choice == '2':
21 fahrenheit = float(input("Enter temperature in Fahrenheit: "))
22 celsius = fahrenheit_to_celsius(fahrenheit)
23 print(f"{fahrenheit}°F is equal to {celsius:.2f}°C")
24 else:
25 print("Invalid choice")
26
27if __name__ == "__main__":
28 main()

Save this code to a file (e.g., temp_converter.py) and run it with:

bash
1python temp_converter.py

8. Object-Oriented Programming in Python

Python supports object-oriented programming with classes and objects:

python
1class Person:
2 # Class attribute
3 species = "Homo sapiens"
4
5 # Constructor method
6 def __init__(self, name, age):
7 # Instance attributes
8 self.name = name
9 self.age = age
10
11 # Instance method
12 def introduce(self):
13 return f"Hi, I'm {self.name} and I'm {self.age} years old."
14
15 # Instance method
16 def celebrate_birthday(self):
17 self.age += 1
18 return f"Happy Birthday! Now I'm {self.age} years old."
19
20# Create objects of the Person class
21alice = Person("Alice", 25)
22bob = Person("Bob", 30)
23
24# 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

python
1class Student(Person):
2 # Constructor method
3 def __init__(self, name, age, student_id):
4 # Call the parent class constructor
5 super().__init__(name, age)
6 self.student_id = student_id
7
8 # Override the introduce method
9 def introduce(self):
10 return f"Hi, I'm {self.name}, a student with ID {self.student_id}."
11
12 # New method specific to Student
13 def study(self, subject):
14 return f"{self.name} is studying {subject}."
15
16# Create a Student object
17charlie = Student("Charlie", 20, "S12345")
18
19# 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.