Skip to content

Understanding Basic Python Programs, With Examples

Python is an enormously popular open-source programming language that was first released in 1991 by its creator Guido van Rossum. Since then, Python has gone on to become one of the most widely used and fastest growing programming languages in the world.

So what sets Python apart from other languages, and why is it so beginner-friendly compared to alternatives like Java or C++?

Why Learn Python?

Here are some key advantages of Python that explain its surge in popularity:

  • Easy to learn syntax: Python code reads a lot like regular English, with clear structure and simple commands. This makes it very intuitive for beginners coming from other languages.

  • Very versatile: Python can be used to build virtually any type of application – web apps, data science projects, AI tools, automation scripts, games, IoT devices, and much more!

  • Huge community support: As one of the most popular languages, Python has enormous community resources, libraries, and tools available for free. Getting help when you get stuck is easy.

  • Productive and readsble code: Python allows you to accomplish a lot in fewer lines of code than many other languages. Code written in Python aims to be readable and explicit about its intentions.

For these reasons, Python is the #1 recommended programming language for new coders and a go-to tool for many industry professionals. Understanding the basics puts a powerful skillset within reach!

Python Syntax Basics

Python is what‘s known as an interpreted language. This means that unlike compiled languages like C or Java, Python code runs line by line rather than needing to be converted beforehand.

Here‘s an overview of essential Python building blocks:

Variables

Variables are used to store data in memory to reference later in your code:

# Assign values to variables
name = "John"
age = 30 

print(name) # Print variables 
# Output: John

Python is dynamically typed, meaning variables take on the appropriate data type automatically based on value assigned.

Data Types

Common data types in Python include:

  • Integers: Whole numbers like 1, 15, 209. Used for math operations.
  • Floats: Decimal numbers like 1.5, 3.456, 10.349. Also used in math.
  • Strings: Sets of characters surrounded by quotes. Used for text manipulation.
  • Booleans: True or false values often used in conditionals and logic.
  • More advanced types also exist like lists, tuples, dicts.

Operators

Operators allow you to perform actions on variables and data:

x = 10
y = 3

# Arithmetic 
print(x + y) # Addition 
print(x - y) # Subtraction
print(x * y) # Multiplication 

# Comparison
print(x > y) # True
print(x < y) # False

Some other Python operators include /, %, //, ** for more advanced math.

Conditional Logic

Conditionals allow you to build logic that executes different code blocks based on results:

age = 17

if age >= 18:
   print("You can vote!")
else:
   print("You cannot vote yet.") 

The if/else syntax is vital for controlling program flow based on input.

Loops

Loops allow you to repeat the same code over and over:

# Print 0 through 4  
for x in range(5):
   print(x) 

# Prints x 10 times   
for i in range(10):
   print(x)

Loops form the backbone of many algorithms and data tasks you‘ll tackle as a Python programmer!

This whirlwind tour covers building blocks that you‘ll use in nearly all Python programs, whether simple scripts or complex applications. These elements come together to allow you to store data, make decisions, repeat tasks, and output results.

Now let‘s see how we can take these pieces to the next level…

Functions for Code Reuse

A key concept in programming is don‘t repeat yourself! Writing the same code over and over is inefficient and error-prone.

In Python, we can define reusable blocks of code called functions so we can easily call them whenever needed:

# Define function
def sayHello(name):
  print("Hello " + name)

# Call function  
sayHello("Bob") # Hello Bob
sayHello("Maria") # Hello Maria

Functions allow passing in arguments to generalize behavior, and even return a value back:

def square(x):
   return x * x

num = square(5) 
print(num) # 25

This makes functions extremely powerful for reducing duplicated code.

Object Oriented Programming

While less complex Python programs don‘t require OOP, it becomes important in larger codebases.

The basic idea behind OOP is bundling data and functions into units called classes:

# Dog class
class Dog:

    # Class attribute
    species = ‘mammal‘

    # Initializer / Instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old"

    # Instance method
    def speak(self, sound):
        return f"{self.name} says {sound}"

# Instantiate Dog object
mikey = Dog("Mikey", 6)

print(mikey.species) # mammal  
print(mikey.description()) # Mikey is 6 years old
print(mikey.speak("Gruff Gruff")) # Mikey says Gruff Gruff

OOP allows logically grouping attributes and behaviors into reusable components that can mimic real-world objects or systems. This becomes very important in building robust, scalable programs as complexity increases.

Core Python Data Structures

Beyond simple data types like strings and integers, Python comes equipped with specialized data structures that add more functionality:

Lists allow storing collections of items or values:

# List of numbers
nums = [5, 1, 2, 8, 4]  

# Print second item  
print(nums[1]) # 1

Lists have tons of useful methods built-in like sorting, appending new items, inserting, counting instances, and more!

Dictionaries are similar to lists but are composed of unique keys mapped to values:

# Dictionary of favorites  
favorites = {
  "color": "blue",
  "fruit": "watermelon" 
}

print(favorites["fruit"]) # watermelon

Dicts allow ultra fast look ups directly by key rather than needing to loop through all items like a list. This makes them very efficient for many use cases.

These structures and others like tuples empower you to work with practical data beyond flat variables. Mastering them unlocks the ability to manipulate real-world data programmatically.

Handling Input/Output

Virtually all programs involve some sort of user I/O, whether getting inputted data that changes its behavior or outputs like printing messages to console or logging to files. Python makes handling I/O simple.

name = input("Enter your name: ") # Get input
print("Hello " + name) # Output message 

with open("file.txt") as file:
   contents = file.read() # Read file

with open("logs.txt", "w") as file: 
   file.write("Activity log") # Write file

Here we see examples of console/terminal I/O, reading external files, and writing to external files. Python has great built-in tools for various types of I/O you may need.

Real World Python Programs

At this point, you understand all the major building blocks of Python programs. Let‘s see how these might come together with some examples demonstrating Python in action!

Simple Dice Rolling Game

Let‘s start super simple – here is code for a dice rolling guessing game:

import random 

roll = random.randint(1, 6) 

guess = int(input("Guess the dice roll: "))

if guess == roll:
    print("Matched!")
else:
    print("Wrong - it was " + str(roll))

Here we:

  1. Import Python‘s random library
  2. Generate random integer from 1 to 6
  3. Take user‘s guess as input
  4. Compare guess to actual roll
  5. Output appropriate message

This quick 6 line game already showcases importing libraries, generating random data, getting user input, using conditionals, and outputting results!

Web Scraper

Another fun beginner Python program is a simple web scraper like this:

import requests
from bs4 import BeautifulSoup 

url = "https://en.wikipedia.org/wiki/Data_science"   

# Get HTML   
html = requests.get(url).text

# Parse HTML
soup = BeautifulSoup(html, "html.parser")   

# Print article title
print(soup.find("h1").text)

Here‘s what‘s happening above:

  1. Import requests and beautifulsoup4 libraries
  2. Choose url to scrape from
  3. Use requests to download page HTML
  4. Pass HTML to BeautifulSoup to parse it
  5. Find & print article title

And just like that in 8 lines you‘ve built a web scraper to extract information you want from a site! Python makes scraping the web easy.

I hope these real-world example shed light on how the core language features come together to build legitimate programs. They only scratch the surface of applications – check out the bonus section for more ideas!

Python Versions

As Python has evolved over 30+ years of life, there have been a few major versions:

  • Python 1 and 2: Initial versions released in 1991. Python 2 remained dominant until 2008
  • Python 3: Potentially breaking changes but with many improvements. Released 2008.
  • Python 3.9+: Modern Python with best practices and new features preferred for current development

When working on Python in 2023, Python 3 is the clear standard – with latest 3.9 or even 3.10 being ideal if starting fresh. Avoid legacy Python 2!

Make sure to verify Python version installed on your development machine to build apps aligned with industry best practices.

Virtual Environments

When installing Python, it‘s also recommended to utilize virtual environments for your projects rather than just installing packages globally.

Virtual environments allow creating isolated dependencies on a per-project basis:

python3 -m venv env 

source env/bin/activate

pip install pandas

Now any libraries added will be sandboxed for just that project environment.

This prevents version conflicts as you work on diverse Python projects using varying dependencies. Use venv liberally!

Where To Go From Here

You should now have a solid grasp of core Python programming concepts, common tools and data structures, techniques for handling I/O, and even examples of full Python programs in action.

I encourage you to continue growing your skills by:

The world of programming in Python holds endless opportunities. Equipped with the fundamentals from this post, you have what it takes to continue expanding your Python chops.

Happy coding! Please leave any Python questions below.