Python Programming: A Comprehensive Beginner's Guide

Introduction to Python

What is Python?

Python is a high-level, interpreted, object-oriented scripting language. Like Java, C/C++, and Go, Python is classified as a high-level programming language. As an interpreted language, Python executes more slowly than compiled languages such as C and C++. However, Python offers significant advantages: it comes with extensive built-in libraries (including os, urllib, and turtle), features simple and readable syntax, and has a vast ecosystem of third-party packages. This versatility has earned Python the nickname "glue language" among developers.

Python Creator and Background

Python was created by Guido van Rossum, a Dutch computer scientist. In 1989, Rossum began developing Python during his spare time at Centrum Wiskunde & Informatica (CWI) in the Netherlands. In 1995, he relocated to the United States, where he joined companies like Google and later Dropbox. His creation has since become one of the most popular programming languages worldwide.

Applications of Python

Python is used across virtually every domain:

  • System administration and automation
  • GUI application development
  • Scientific computing and numerical analysis
  • Text processing and natural language processing
  • Database programming
  • Network programming and web development
  • Multimedia applications
  • Cybersecurity and penetration testing
  • Web scraping and data extraction
  • Machine learning and artificial intelligence

Advantages and Disadvantages

Advantages:

  • Free and open-source with no licensing restrictions
  • Cross-platform compatibility
  • Extensive standard library and third-party packages
  • Simple, readable syntax requiring less code
  • Strong community support

Consider this comparison: achieving the same output in C requires multiple lines:

#include <stdio.h>
int main() {
    printf("Hello, World!\n");
    return 0;
}

While Python accomplishes the same task in a single line:

print("Hello, World!")

Disadvantages:

  • Slower execution speed compared to compiled languages
  • Global Interpreter Lock (GIL) limitations for CPU-bound multi-threading

Setting Up Python Development Environment

Windows Installation (Python 3.12)

Using IDLE:

  1. Visit the official Python website at https://www.python.org/downloads/
  2. Download Python 3.12 for Windows
  3. Choose the version matching your system architecture (32-bit or 64-bit)
  4. Run the installer and ensure "Add Python to PATH" is checked
  5. Follow the installation wizard

To verify installation, open Command Prompt and type:

python --version

If the installation succeeded, you should see the Python version displayed.

Using PyCharm:

  1. Navigate to https://www.jetbrains.com/pycharm/
  2. Download the Community edition (free and open-source)
  3. Run the installer
  4. During setup, configure the Python interpreter path
  5. Create a new project and begin coding

Linux Installation

Most Linux distributions come with Python pre-installed. Check your installation by running:

python3 --version

If Python 3 is not installed, update your package manager and install:

sudo apt-get update
sudo apt-get install python3.12

To install from source:

wget https://www.python.org/ftp/python/3.12.0/Python-3.12.0.tgz
tar -zxvf Python-3.12.0.tgz
cd Python-3.12.0
./configure --prefix=/usr/local
make && sudo make install

To set Python 3 as the default:

sudo unlink /usr/bin/python
sudo ln -s /usr/bin/python3.12 /usr/bin/python

macOS Installation

macOS typically includes Python 2.x by default. To install Python 3:

  1. Download the macOS installer from https://www.python.org/downloads/
  2. Run the .pkg installer
  3. Follow the installation wizard

Verify installation:

python3 --version

Python Data Types

Numeric Types

Python supports several numeric types: int (integers), float (floating-point), bool (Boolean), and complex (complex numbers).

Important Note: Unlike C, Python has only a single floatnig-point type (float). Regardless of decimal precision, all floating-point values use the float type.

Use the type() function to check numeric types:

a = 4 + 7j
b = 47.88
c = 47
d = 47.8

e = False

print(type(c), type(d), type(a), type(b), type(e))

Output:

<class 'int'> <class 'float'> <class 'complex'> <class 'float'> <class 'bool'>

The isinstance() function verifies type membership:

value = 42.5
print(isinstance(value, float))  # True

Arithmetic Operators

Python supports standard arithmetic operations:

Operator Description Example
+ Addition 5 + 3 = 8
- Subtraction 5 - 3 = 2
* Multiplication 5 * 3 = 15
/ Division 5 / 2 = 2.5
% Modulus 5 % 2 = 1
** Exponentiation 2 ** 3 = 8
// Floor Division 5 // 2 = 2

Example:

x = 100
y = 25

print(x + y, x - y, x * y, x / y, x % y, x ** y, x // y)

String Type

Strings in Python can be enclosed in single quotes, double quotes, or triple quotes for multi-line text.

message = 'Learning Python is enjoyable'
print(message)

String concatenation:

greeting = 'Hello'
target = 'World'
print(greeting + ', ' + target)

String indexing and slicing:

text = 'Python Programming'
print(text[0])      # First character: 'P'
print(text[-1])     # Last character: 'g'
print(text[0:6])    # 'Python'
print(text[7:])     # 'Programming'

Escape sequences use backslashes. To display literally:

print(r'C:\Users\Admin')  # Raw string: C:\Users\Admin

List Type

Lists are mutable, ordered collections that can hold items of different types.

fruits = ['apple', 'banana', 'cherry', 3]
numbers = [1, 2, 'hello', 'world', 5, 6]

print(fruits)
print(numbers)

List operations:

items = ['a', 'b', 'c', 1]
items[0:3] = ['X', 'Y', 'Z']  # Modify elements
print(items)

items.append(42)  # Add to end
print(items)

items[1] = []  # Remove element at index 1
print(items)

print('Length:', len(items))  # Get count

Nested lists:

matrix = [[1, 2], [3, 4]]
print(matrix[0][1])  # 2

Tuple Type

Tuples are immutable, ordered collections. They use parentheses instead of brackets.

coordinates = (10, 20, 30)
mixed = ('Python', 'Java', 3)

print(coordinates)
print(mixed)

Creating an empty tuple:

empty = ()

Tuple concatenation:

tuple1 = ('a', 'b')
tuple2 = ('c', 'd')
combined = tuple1 + tuple2
print(combined)  # ('a', 'b', 'c', 'd')

Deleting a tuple:

data = (1, 2, 3)
del data

Tuple operations:

sample = ('a', 'b', 'c', 'a')
print(len(sample))
print(sample * 2)
print('a' in sample)

for item in sample:
    print(item)

Built-in functions:

nums = (3, 6, 9)
print(max(nums))  # 9
print(min(nums))  # 3

Set Type

Sets are unordered collections of unique elements. They are useful for membership testing and eliminating duplicates.

letters = {'a', 'b', 'c', 'a'}
print(letters)  # Only prints unique: {'a', 'b', 'c'}

unique_chars = set('programming')
print(unique_chars)

Important: Create empty sets using set(), not {}, as {} creates an empty dictionary.

Set operations:

a = set('abcdef')
b = set('cdefgh')

print(a - b)  # Elements in a but not b
print(a | b)  # Elements in either a or b
print(a & b)  # Elements in both a and b
print(a ^ b)  # Elements in exactly one set

Adding and removing elements:

collection = set('abc')
collection.add('d')
collection.update(['e', 'f'])
print(collection)

collection.remove('a')  # Raises error if not found
collection.discard('b')  # Does not raise error if not found
collection.pop()  # Removes random element
collection.clear()  # Removes all elements

Dictionary Type

Dictionaries store key-value pairs and are unordered but mutable.

student = {
    'name': 'Alice',
    'age': 25,
    'course': 'Computer Science'
}
print(student)
print(student['name'])  # Access value

Modifying dictionaries:

info = {'a': 'Python', 'b': 'Java'}
info['b'] = 'C++'
print(info)

info['c'] = 'Ruby'  # Add new key-value
print(info)

Dictionary methods:

data = {'x': 100, 'y': 200}
print(data.keys())
print(data.values())
print(data.items())

data.clear()  # Remove all items
del data  # Delete entire dictionary

Code Style and Naming Conventions

Indentation

Python uses indentation to define code blocks. Unlike other languages that use braces, Python requires consistent indentation. Incorrect indentation results in syntax errors.

Incorrect:

message = 'Hello'
    print(message)  # IndentationError

Correct:

message = 'Hello'
print(message)

Naming Conventions

Hungarian Notation: Prefixes indicate variable type and scope (e.g., m_sName for member string).

Camel Case:

  • Small camelCase: first word lowercase, subsequent words capitalized (e.g., userName)
  • PascalCase: Each word capitalized (e.g., UserName)

Snake Case: Words separated by underscores (e.g., user_name). Python recommends snake_case for variables and functions.

Example:

user_name = 'John'
user_age = 30
is_active = True

def calculate_total():
    pass

class UserAccount:
    pass

Input and Output

The print() Function

The print() function outputs data to the console.

greeting = 'Welcome to Python'
number = 42

print(greeting)
print(number)
print(greeting, number)  # Multiple arguments

String formatting:

name = 'Alice'
age = 25

print(f"Name: {name}, Age: {age}")  # f-string
print("Name: {}, Age: {}".format(name, age))

The input() Function

The input() function reads user input as a string.

user_input = input("Enter something: ")
print("You entered:", user_input)

Converting input to other types:

age = int(input("Enter your age: "))
price = float(input("Enter price: "))
is_member = input("Are you a member? (yes/no): ") == 'yes'

Creating a simple calculator:

a = float(input("First number: "))
operator = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))

if operator == '+':
    print(a + b)
elif operator == '-':
    print(a - b)
elif operator == '*':
    print(a * b)
elif operator == '/':
    print(a / b)
else:
    print("Invalid operator")

Combining with data structures:

text = input("Enter text: ")
char_list = list(text)
tuple_data = tuple(text)
set_data = set(text)

print("String:", text)
print("List:", char_list)
print("Tuple:", tuple_data)
print("Set:", set_data)

Conditional Statements

The if Statement

score = 85

if score >= 60:
    print("Pass")

The if-else Statement

temperature = 25

if temperature > 30:
    print("Hot")
else:
    print("Comfortable")

The if-elif-else Statement

grade = 85

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
elif grade >= 60:
    print("D")
else:
    print("F")

Logical Operators

and: Both conditions must be true

age = 25
income = 50000

if age >= 18 and income > 30000:
    print("Eligible")
else:
    print("Not eligible")

or: At least one condition must be true

member = True
purchase = 100

if member or purchase > 50:
    print("Discount applied")
else:
    print("No discount")

Comparison Operators

Operator Meaning
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
== Equal to
!= Not equal to

Example:

num = 75

if num < 60:
    print("Fail")
elif 60 <= num < 70:
    print("Grade D")
elif 70 <= num < 80:
    print("Grade C")
elif 80 <= num < 90:
    print("Grade B")
else:
    print("Grade A")

Loop Statements

The for Loop

For loops iterate over sequences (lists, strings, ranges, etc.).

Iterating through a string:

text = "Python"
for char in text:
    print(char)

Using range():

for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

for i in range(1, 6):
    print(i)  # 1, 2, 3, 4, 5

for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

Iterating through a list:

languages = ['Python', 'Java', 'C++', 'Go']
for lang in languages:
    print(lang)

# With index
for index, lang in enumerate(languages):
    print(f"{index}: {lang}")

The while Loop

While loops continue as long as a condition is true.

count = 0
while count < 5:
    print(count)
    count += 1

Break and continue:

# Break: exit loop
for i in range(10):
    if i == 5:
        break
    print(i)

# Continue: skip iteration
for i in range(5):
    if i == 2:
        continue
    print(i)  # 0, 1, 3, 4

Infinite loop with break:

while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input == 'quit':
        break
    print("You entered:", user_input)

Note: Python does not have a do-while loop. Use an infinite loop with break instead.

Nested Loops

for i in range(3):
    for j in range(3):
        print(f"({i}, {j})", end=" ")
    print()

Output:

(0, 0) (0, 1) (0, 2) 
(1, 0) (1, 1) (1, 2) 
(2, 0) (2, 1) (2, 2) 

Tags: python programming Beginner Tutorial Data Types

Posted on Wed, 20 May 2026 18:50:26 +0000 by little_webspinner