Background
HOME / IT / PYTHON-101

Python 101: Introduction to Python Programming

A beginner's guide to Python programming, covering basic syntax, input/output operations, and getting started with Python development

rnrran's profile picture
rnrran
Jan 29, 202518 min read
rnrran's avatar

Written by

rnrran

Feature added soon

Python 101: Introduction to Python Programming

Introduction

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 has become one of the most popular programming languages for beginners and professionals alike.

This guide will introduce you to Python fundamentals, focusing on basic syntax, input/output operations, and essential concepts to get you started with Python programming.

Python Programming

What is Python?

Python is:

  • Interpreted: Code is executed line by line (no compilation needed)
  • High-Level: Easy to read and write
  • Dynamically Typed: Variable types determined at runtime
  • Multi-Paradigm: Supports procedural, object-oriented, and functional programming
  • Cross-Platform: Works on Windows, Linux, macOS

Python Versions

  • Python 2.x: Legacy version (end of life in 2020)
  • Python 3.x: Current version (Python 3.8+ recommended)
  • Check version: python3 --version or python --version

Getting Started

Installing Python

Linux:

# Most distributions include Python 3
python3 --version

# Install if needed
sudo apt install python3 python3-pip  # Debian/Ubuntu
sudo yum install python3 python3-pip  # RHEL/CentOS

macOS:

# Usually pre-installed
python3 --version

# Or install via Homebrew
brew install python3

Windows:

  • Download from python.org
  • Or use Microsoft Store
  • Make sure to check "Add Python to PATH" during installation

Running Python

Interactive Mode (REPL):

python3
# or
python

Script Mode:

python3 script.py
# or
python script.py

Basic Syntax

Hello, World!

# Simple print statement
print("Hello, World!")

# Print multiple items
print("Hello", "World", "!")

# Print with separator
print("Hello", "World", sep="-")  # Output: Hello-World

# Print without newline
print("Hello", end="")
print("World")  # Output: HelloWorld

Comments

# This is a single-line comment

"""
This is a multi-line comment
or docstring
"""

# Comments are ignored by Python interpreter

Indentation

Python uses indentation (spaces or tabs) to define code blocks:

if True:
    print("This is indented")
    print("This too")
print("This is not indented")

Important: Use consistent indentation (4 spaces recommended, never mix tabs and spaces)

Variables and Data Types

Variables

# Variables don't need type declaration
name = "John"
age = 30
height = 5.9
is_student = True

# Variable names rules:
# - Start with letter or underscore
# - Can contain letters, numbers, underscores
# - Case-sensitive
# - Cannot use Python keywords

# Good variable names
user_name = "john"
total_count = 100
is_active = True

# Bad variable names
# 2name = "john"  # Cannot start with number
# class = "A"     # Cannot use keyword

Basic Data Types

# Integer
age = 25
count = -10
big_number = 1000000

# Float (decimal)
price = 19.99
pi = 3.14159
temperature = -5.5

# String
name = "John"
message = 'Hello, World!'
multiline = """This is
a multi-line
string"""

# Boolean
is_active = True
is_complete = False

# None (null value)
value = None

Type Checking

# Check variable type
type(age)        # <class 'int'>
type(name)      # <class 'str'>
type(is_active) # <class 'bool'>

# Type conversion
str(age)        # Convert to string: "25"
int("25")       # Convert to integer: 25
float("3.14")   # Convert to float: 3.14
bool(1)         # Convert to boolean: True

Input and Output

Output (Print)

The print() function is used to display output:

# Basic print
print("Hello, World!")

# Print variables
name = "John"
print("Hello,", name)

# Print with formatting
print(f"Hello, {name}")  # f-string (Python 3.6+)
print("Hello, {}".format(name))  # .format() method
print("Hello, %s" % name)  # Old style (not recommended)

# Print multiple values
print("Name:", name, "Age:", age)

# Print with separator
print("Python", "is", "great", sep="-")  # Output: Python-is-great

# Print without newline
print("Hello", end=" ")
print("World")  # Output: Hello World

# Print to file
with open("output.txt", "w") as f:
    print("Hello, World!", file=f)

Input

The input() function is used to get user input:

# Basic input
name = input()
print("Hello,", name)

# Input with prompt
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Input always returns 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")

# Handle conversion errors
try:
    age = int(input("Enter your age: "))
    print(f"Age: {age}")
except ValueError:
    print("Invalid input! Please enter a number.")

Input Examples

# Example 1: Simple greeting
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")

# Example 2: Calculator input
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 + num2
print(f"Sum: {result}")

# Example 3: Multiple inputs
first_name = input("First name: ")
last_name = input("Last name: ")
full_name = first_name + " " + last_name
print(f"Full name: {full_name}")

# Example 4: Input validation
while True:
    try:
        age = int(input("Enter your age (0-120): "))
        if 0 <= age <= 120:
            break
        else:
            print("Age must be between 0 and 120!")
    except ValueError:
        print("Please enter a valid number!")
print(f"Your age is {age}")

String Operations

String Basics

# String creation
text = "Hello, World!"
text = 'Hello, World!'
text = """Multi-line
string"""

# String concatenation
first = "Hello"
second = "World"
greeting = first + " " + second  # "Hello World"

# String repetition
text = "Python " * 3  # "Python Python Python "

# String length
length = len("Hello")  # 5

# String indexing
text = "Python"
print(text[0])    # 'P'
print(text[-1])   # 'n' (last character)
print(text[1:4])  # 'yth' (slicing)

# String methods
text = "hello world"
text.upper()      # "HELLO WORLD"
text.lower()      # "hello world"
text.capitalize() # "Hello world"
text.title()      # "Hello World"
text.strip()      # Remove whitespace
text.replace("world", "Python")  # "hello Python"

String Formatting

# f-strings (recommended, Python 3.6+)
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old")

# Format with expressions
print(f"Next year I will be {age + 1}")

# Format with formatting
pi = 3.14159
print(f"Pi is approximately {pi:.2f}")  # "Pi is approximately 3.14"

# .format() method
print("My name is {} and I am {} years old".format(name, age))
print("My name is {0} and I am {1} years old".format(name, age))
print("My name is {name} and I am {age} years old".format(name=name, age=age))

Basic Operations

Arithmetic Operations

# Addition
result = 10 + 5      # 15

# Subtraction
result = 10 - 5     # 5

# Multiplication
result = 10 * 5     # 50

# Division
result = 10 / 3     # 3.333... (float)

# Floor division
result = 10 // 3    # 3 (integer)

# Modulus (remainder)
result = 10 % 3     # 1

# Exponentiation
result = 2 ** 3     # 8 (2 to the power of 3)

# Order of operations
result = 2 + 3 * 4  # 14 (multiplication first)
result = (2 + 3) * 4  # 20 (parentheses first)

Comparison Operations

# Equal
5 == 5      # True

# Not equal
5 != 3      # True

# Greater than
5 > 3       # True

# Less than
3 < 5       # True

# Greater than or equal
5 >= 5      # True

# Less than or equal
3 <= 5      # True

Logical Operations

# AND
True and True   # True
True and False  # False

# OR
True or False   # True
False or False  # False

# NOT
not True        # False
not False       # True

# Combined
(5 > 3) and (10 > 5)  # True
(5 > 10) or (10 > 5)  # True

Control Flow

If Statements

# Basic if
if age >= 18:
    print("You are an adult")

# If-else
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

# If-elif-else
if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
else:
    print("Adult")

Loops

# For loop
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

# Loop through list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

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

# Break and continue
for i in range(10):
    if i == 5:
        break      # Exit loop
    if i % 2 == 0:
        continue   # Skip to next iteration
    print(i)

Simple Programs

Program 1: Greeting Program

#!/usr/bin/env python3
# greeting.py - Simple greeting program

# Get user input
name = input("What is your name? ")
age = input("How old are you? ")

# Display greeting
print(f"Hello, {name}!")
print(f"You are {age} years old.")
print("Nice to meet you!")

Program 2: Simple Calculator

#!/usr/bin/env python3
# calculator.py - Simple calculator

# Get numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Perform operations
print(f"\nResults:")
print(f"Addition: {num1} + {num2} = {num1 + num2}")
print(f"Subtraction: {num1} - {num2} = {num1 - num2}")
print(f"Multiplication: {num1} * {num2} = {num1 * num2}")
print(f"Division: {num1} / {num2} = {num1 / num2}")

Program 3: Temperature Converter

#!/usr/bin/env python3
# temp_converter.py - Convert Celsius to Fahrenheit

# Get temperature
celsius = float(input("Enter temperature in Celsius: "))

# Convert to Fahrenheit
fahrenheit = (celsius * 9/5) + 32

# Display result
print(f"{celsius}°C = {fahrenheit}°F")

Program 4: Number Guessing Game

#!/usr/bin/env python3
# guess.py - Simple number guessing game

import random

# Generate random number
secret = random.randint(1, 100)

print("I'm thinking of a number between 1 and 100.")
print("Can you guess it?")

# Game loop
while True:
    guess = int(input("Your guess: "))
    
    if guess == secret:
        print("Congratulations! You guessed it!")
        break
    elif guess < secret:
        print("Too low! Try again.")
    else:
        print("Too high! Try again.")

Best Practices

  1. Use Meaningful Names: Clear variable and function names
  2. Add Comments: Explain complex logic
  3. Follow PEP 8: Python style guide
  4. Use f-strings: For string formatting (Python 3.6+)
  5. Handle Errors: Use try-except blocks
  6. Keep It Simple: Python emphasizes readability
  7. Use Functions: Organize code into functions
  8. Test Your Code: Verify it works correctly
  9. Read Documentation: Python has excellent docs
  10. Practice Regularly: Programming improves with practice

Next Steps

After mastering basics:

  1. Data Structures: Lists, dictionaries, tuples, sets
  2. Functions: Creating and using functions
  3. Modules: Importing and creating modules
  4. File Handling: Reading and writing files
  5. Error Handling: Try-except blocks
  6. Object-Oriented Programming: Classes and objects
  7. Libraries: NumPy, Pandas, Requests, etc.

Conclusion

Python is an excellent language for beginners due to its simplicity and readability. This guide covered:

  • Basic Python syntax and data types
  • Input and output operations
  • Variables and basic operations
  • Control flow (if statements, loops)
  • Simple program examples

Continue learning by:

  • Practicing with exercises
  • Building small projects
  • Reading Python documentation
  • Joining Python communities
  • Exploring Python libraries

Python's simplicity makes it perfect for automation, data analysis, web development, and much more. Start coding and enjoy your Python journey!