Python Basics: A Beginner’s Guide to Getting Started

Discover Python basics with this beginner-friendly guide. Learn essential programming concepts, data types, and functions to kickstart your coding journey!
code
python
Author

Steven P. Sanderson II, MPH

Published

May 23, 2025

Keywords

Programming, python programming, learn python, python for beginners, python variables, python functions, python data types, python control structures, python input and output, python string manipulation, python error handling, how to learn Python programming for beginners, basic Python programming concepts explained, introduction to Python coding for new programmers, step-by-step guide to Python variables and data types, understanding Python functions and control structures

As a beginner learning Python alongside you, I’m excited to share what I learn as I write this series. I’ve been trying to get on the Python bandwagon for a long time now and I am finally doing it.

Introduction to Python Basics

Python is one of the most beginner-friendly programming languages available today. Its clean syntax and readability make it an excellent first language for anyone starting out programming. As I learn Python myself, I’ve found that understanding the fundamentals provides a solid foundation for tackling more complex projects later on. I also think it helps if you have previous programming background.

Setting Up Your Python Environment

Before diving into coding, you need to have Python installed on your computer. The latest version can be downloaded from the official Python website (python.org). Once installed, you can write Python code using a simple text editor or an Integrated Development Environment (IDE) like Mu, which is particularly beginner-friendly.

To verify your installation, open a command prompt or terminal and type:

python --version

This should display the version of Python you’ve installed, confirming that everything is set up correctly.

Python Variables and Data Types

Variables in Python are like containers that store data. One of the great things about Python is that you don’t need to declare the type of variable explicitly—Python figures this out automatically based on the value you assign.

Basic Data Types

Let’s look at the fundamental data types in Python:

# Integer (whole number)
age = 25
print(f"Integer example (age): {age}")
print(f"Type of age: {type(age)}")

# Float (decimal number)
height = 5.9
print(f"Float example (height): {height}")
print(f"Type of height: {type(height)}")

# String (text)
name = "Alice"
print(f"String example (name): {name}")
print(f"Type of name: {type(name)}")

# Boolean (True/False)
is_student = True
print(f"Boolean example (is_student): {is_student}")
print(f"Type of is_student: {type(is_student)}")

When you run this code, you’ll see:

Integer example (age): 25
Type of age: <class 'int'>        
Float example (height): 5.9       
Type of height: <class 'float'>   
String example (name): Alice      
Type of name: <class 'str'>       
Boolean example (is_student): True
Type of is_student: <class 'bool'>

Understanding these basic data types is crucial as they form the building blocks of more complex operations in Python .

Basic Operations in Python

Python supports various operations that allow you to manipulate data. Let’s explore some common operations:

Arithmetic Operations

a = 10
b = 3
print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")
print(f"Integer Division: {a} // {b} = {a // b}")
print(f"Modulus: {a} % {b} = {a % b}")
print(f"Exponentiation: {a} ** {b} = {a ** b}")

The output will be:

Addition: 10 + 3 = 13
Subtraction: 10 - 3 = 7
Multiplication: 10 * 3 = 30
Division: 10 / 3 = 3.3333333333333335
Integer Division: 10 // 3 = 3
Modulus: 10 % 3 = 1
Exponentiation: 10 ** 3 = 1000

Key Insight: Notice that regular division (/) always returns a float in Python 3, while integer division (//) discards the decimal part and returns an integer.

String Operations

Strings in Python are versatile and support various operations:

first_name = "John"
last_name = "Doe"

# String concatenation (joining)
full_name = first_name + " " + last_name
print(f"Full name: {full_name}")

# String repetition
repeated = "Python! " * 3
print(f"Repeated string: {repeated}")

# String methods
message = "hello, world"
print(f"Uppercase: {message.upper()}")
print(f"Capitalize: {message.capitalize()}")
print(f"Replace: {message.replace('world', 'Python')}")

Output:

Full name: John Doe
Repeated string: Python! Python! Python! 
Uppercase: HELLO, WORLD
Capitalize: Hello, world
Replace: hello, Python

Control Structures in Python

Control structures allow you to direct the flow of your program based on conditions or repeat actions multiple times.

Conditional Statements (if-elif-else)

Conditional statements help your program make decisions:

x = 15
print("Testing if statement with x =", x)
if x > 10:
    print("x is greater than 10")
elif x == 10:
    print("x equals 10")
else:
    print("x is less than 10")

Output:

Testing if statement with x = 15
x is greater than 10

Loops

Loops allow you to repeat actions multiple times:

For Loop

print("For loop example:")
for i in range(3):
    print(f"Loop iteration {i}")

Output:

For loop example:
Loop iteration 0
Loop iteration 1
Loop iteration 2

While Loop

print("While loop example:")
count = 0
while count < 3:
    print(f"Count is {count}")
    count += 1

Output:

While loop example:
Count is 0
Count is 1
Count is 2

Functions in Python

Functions are reusable blocks of code that perform specific tasks. They help organize your code and make it more modular.

Defining and Calling Functions

# Defining a function
def greet(name):
    """Simple greeting function"""
    return f"Hello, {name}!"

# Calling the function
result = greet("World")
print(f"Function test: {result}")

Output:

Function test: Hello, World!

Function with Multiple Parameters

Let’s create a more practical example, a temperature converter:

def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit"""
    return (celsius * 9/5) + 32

# Test the function with different values
test_celsius = 25
fahrenheit = celsius_to_fahrenheit(test_celsius)
print(f"Converting {test_celsius}°C to Fahrenheit")
print(f"{test_celsius}°C = {fahrenheit:.1f}°F")

Output:

Converting 25°C to Fahrenheit
25°C = 77.0°F

Common Python Mistakes and How to Avoid Them

Let’s examine some potential mistakes and how to avoid them:

1. Indentation Errors

Python uses indentation to define the scope of loops, functions, and conditionals. Inconsistent indentation leads to errors:

# Correct indentation
for i in range(2):
    print(f"  Properly indented line {i}")

Output:

  Properly indented line 0
  Properly indented line 1

2. Mixing Data Types Incorrectly

One common mistake is trying to combine different data types without proper conversion:

age = 25
print("\nCorrect string formatting:")
print(f"I am {age} years old")  # Correct way using f-strings

# This will cause an error:
try:
    print("I am " + age)
except TypeError as e:
    print(f"Error caught: {e}")
    print("Solution: Convert number to string first:")
    print("I am " + str(age))

Output:

Correct string formatting:
I am 25 years old
Error caught: can only concatenate str (not "int") to str
Solution: Convert number to string first:
I am 25

3. Mutable Default Arguments

Using mutable objects (like lists) as default function arguments can lead to unexpected behavior :

# Problematic function with mutable default argument
def add_to_list(value, my_list=[]):
    my_list.append(value)
    return my_list

# First call
print(add_to_list(1))  # [1]

# Second call - notice the list isn't empty!
print(add_to_list(2))  # [1, 2]

# Better approach
def add_to_list_fixed(value, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(value)
    return my_list

# First call
print(add_to_list_fixed(1))  # [1]

# Second call - now we get a fresh list
print(add_to_list_fixed(2))  # [2]

Practical Example: Temperature Converter

Let’s build a more complete temperature converter that demonstrates several Python concepts working together:

def celsius_to_fahrenheit(celsius):
    """Convert Celsius to Fahrenheit"""
    return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit):
    """Convert Fahrenheit to Celsius"""
    return (fahrenheit - 32) * 5/9

# Demonstrate the program with test values
print("=== Temperature Converter Demo ===")

# Example 1: Converting Celsius to Fahrenheit
test_celsius = 25
fahrenheit = celsius_to_fahrenheit(test_celsius)
print(f"\nExample 1: Converting {test_celsius}°C to Fahrenheit")
print(f"{test_celsius}°C = {fahrenheit:.1f}°F")

# Example 2: Converting Fahrenheit to Celsius
test_fahrenheit = 98.6
celsius = fahrenheit_to_celsius(test_fahrenheit)
print(f"\nExample 2: Converting {test_fahrenheit}°F to Celsius")
print(f"{test_fahrenheit}°F = {celsius:.1f}°C")

# Example 3: Multiple Conversions
print("\nExample 3: Multiple Conversions")
temperatures_c = [0, 25, 100]
print("\nConverting multiple Celsius temperatures:")
for temp in temperatures_c:
    converted = celsius_to_fahrenheit(temp)
    print(f"{temp}°C = {converted:.1f}°F")

Output:

=== Temperature Converter Demo ===

Example 1: Converting 25°C to Fahrenheit
25°C = 77.0°F

Example 2: Converting 98.6°F to Celsius
98.6°F = 37.0°C

Example 3: Multiple Conversions

Converting multiple Celsius temperatures:
0°C = 32.0°F
25°C = 77.0°F
100°C = 212.0°F

This practical example demonstrates several Python concepts:

  • Function definitions with docstrings
  • Calling functions with arguments
  • Formatted string literals (f-strings)
  • Looping through lists
  • Temperature conversion formulas

Error Handling in Python

When writing code, things don’t always go as planned. Python provides a way to handle errors gracefully using try-except blocks:

def divide_numbers(a, b):
    """Demonstrate error handling with division"""
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        return "Error: Cannot divide by zero"
    except TypeError:
        return "Error: Please use numbers only"

# Test error handling
print("Testing division function:")
print(f"10 / 2 = {divide_numbers(10, 2)}")
print(f"10 / 0 = {divide_numbers(10, 0)}")

Output:

Testing division function:
10 / 2 = 5.0
10 / 0 = Error: Cannot divide by zero

Error handling is critical for building robust programs that can handle unexpected situations without crashing.

Python Lists and Collections

Collections are foundational to Python programming. Let’s explore the most commonly used collection type—lists:

Working with Lists

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

# Creating a list
fruits = ["apple", "banana", "cherry"]
print(f"Original list: {fruits}")

# Accessing elements (indexing starts at 0)
print(f"First fruit: {fruits[0]}")
print(f"Last fruit: {fruits[-1]}")

# Adding elements
fruits.append("orange")
print(f"After append: {fruits}")

# Modifying elements
fruits[1] = "blueberry"
print(f"After modification: {fruits}")

# Slicing lists
print(f"First two fruits: {fruits[:2]}")

# List operations
vegetables = ["carrot", "spinach"]
food = fruits + vegetables
print(f"Combined list: {food}")

Output:

Original list: ['apple', 'banana', 'cherry']
First fruit: apple
Last fruit: cherry
After append: ['apple', 'banana', 'cherry', 'orange']
After modification: ['apple', 'blueberry', 'cherry', 'orange']
First two fruits: ['apple', 'blueberry']
Combined list: ['apple', 'blueberry', 'cherry', 'orange', 'carrot', 'spinach']

Lists are versatile and widely used in Python programs for storing and manipulating collections of data, lists are also powerful tools in R.

Your Turn!

Now that you’ve learned about Python basics, let’s practice with a simple exercise. Try to create a function that takes a list of numbers and returns a new list with only the even numbers:

# Your task: Write a function that filters even numbers from a list
def filter_even_numbers(numbers):
    # Write your code here
    pass  # Replace this with your solution

# Test with this list
test_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
See Solution
def filter_even_numbers(numbers):
    even_numbers = []
    for number in numbers:
        if number % 2 == 0:
            even_numbers.append(number)
    return even_numbers

# Test the function
test_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = filter_even_numbers(test_numbers)
print(f"Original list: {test_numbers}")
print(f"Even numbers only: {result}")

Output:

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even numbers only: [2, 4, 6, 8, 10]

You could also use a list comprehension for a more elegant solution:

def filter_even_numbers(numbers):
    return [num for num in numbers if num % 2 == 0]

Key Takeaways

  • Python is beginner-friendly with a simple, readable syntax that makes it ideal for learning programming.
  • Variables in Python don’t require explicit type declarations; the type is determined by the assigned value.
  • Basic data types include integers, floats, strings, and booleans.
  • Control structures like conditional statements and loops help direct program flow.
  • Functions are reusable blocks of code that make your programs modular and maintainable.
  • Error handling with try-except blocks helps create robust programs.
  • Lists and other collections store and manipulate groups of values.
  • Common mistakes include indentation errors, type mixing issues, and mutable default arguments.
  • Practical applications like our temperature converter demonstrate how these concepts work together.

Conclusion

Python’s simplicity and readability make it an excellent choice for beginners much like myself. In this guide, we covered Python concepts that every beginner should know, from variables and data types to control structures, functions, and common pitfalls. The practical examples demonstrate how these concepts work in real code.

Remember that programming is a skill that improves with practice. Don’t be discouraged by errors or challenges—they’re a natural part of the learning process. Each mistake is an opportunity to deepen your understanding.

Stay tuned for the next article in this series, where we’ll explore more advanced Python topics and build on the foundation we’ve established here.

Frequently Asked Questions

1. Is Python a good first programming language to learn?

Yes, Python is widely considered one of the best first programming languages due to its readable syntax, gentle learning curve, and versatility. It allows beginners to focus on programming concepts rather than complex syntax.

2. How long does it take to learn Python basics?

Most beginners can grasp the basics of Python in about 2-4 weeks with regular practice. However, becoming proficient takes longer and depends on your background, dedication, and practice time.

3. Do I need special software to write Python code?

You only need a text editor and the Python interpreter. While simple text editors work fine, many beginners benefit from using beginner-friendly IDEs like Mu, Thonny, or IDLE (which comes bundled with Python).

4. What are common applications of Python?

Python is used in web development, data analysis, artificial intelligence, machine learning, automation, scientific research, game development, and more. Its versatility makes it valuable across numerous fields.

5. How do I continue learning Python after mastering the basics?

After learning the basics, challenge yourself with small projects like simple games, file manipulation tools, or web scrapers. Online courses, tutorials, and coding challenges can help you progress. Consider joining coding communities to learn from others.

I’ll create a well-organized References section with working hyperlinks to supplement our Python Basics article.

References Section

Official Documentation

The official Python documentation is the most authoritative source for learning Python:

  1. Python Documentation - The complete reference for Python language and standard libraries
  2. Python Tutorial - The comprehensive tutorial for beginners from Python.org
  3. Python Control Flow - Learn about control structures and function definitions
  4. Python Error Handling - Understanding exceptions and error handling in Python

Python Community Resources

  1. Python.org - The official Python community website
  2. Stack Overflow - Python - Q&A forum for Python programming
  3. r/learnpython - Reddit community for Python beginners

I’d love to hear about your Python learning journey! Share your experiences, questions, or project ideas in the comments below. If you found this guide helpful, please share it with other beginning programmers who might benefit.


Happy Coding! 🚀

Python: The Beginning

You can connect with me at any one of the below:

Telegram Channel here: https://t.me/steveondata

LinkedIn Network here: https://www.linkedin.com/in/spsanderson/

Mastadon Social here: https://mstdn.social/@stevensanderson

RStats Network here: https://rstats.me/@spsanderson

GitHub Network here: https://github.com/spsanderson

Bluesky Network here: https://bsky.app/profile/spsanderson.com

My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ

You.com Referral Link: https://you.com/join/EHSLDTL6