Technical Writer
Python has rapidly become one of the most popular programming languages in the world, and for good reason. Its clean syntax, versatility, and an ever-growing ecosystem of libraries make it an excellent choice for beginners and professionals alike. Whether you’re diving into web development, data analysis, automation, or artificial intelligence, Python offers the tools and community support to get you started quickly and effectively.
To give you an idea of just how popular Python has become, the plot below shows its growing interest over the years based on Google Trends data. This consistent upward trajectory reflects its widespread adoption across industries and its relevance in today’s tech landscape.
This beginner-friendly tutorial is designed to help you take your first steps with Python programming. We’ll walk you through the basics, from installing Python and writing your first lines of code to understanding variables, data types, conditionals, loops, and functions. No prior programming experience is needed, just curiosity and a willingness to learn.
python --version
in your terminal or command prompt.Here are a few of the basic commands you can start with once Python is installed on your system.
Hello World: The first step in any language, printing a message to the console.
Print(“Hello World!”)
Variables and Data Types: Explains strings ("Alice"
), integers (25
), floats (5.7
), and booleans (True
).
name = "Alice" # String
age = 25 # Integer
height = 5.7 # Float
is_student = True # Boolean
Comments: Helps document your code. #
is for single-line, """ """
for multi-line.
# This is a single-line comment
"""
This is a
multi-line comment
"""
Input/Output: Using input()
to take user input and print()
to display output.
name = input("Enter your name: ")
print("Hello,", name)
Conditional Statements: These statements use if
, elif
, and else
to perform actions based on conditions.
if age > 18:
print("Adult")
elif age == 18:
print("Just turned adult")
else:
print("Minor")
In Python, there are two types of Loops, namely:
for
loop: Repeats for a set number of times (e.g., range(5)
).while
loop: Repeats as long as a condition is true.# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Functions are code blocks used to declare code which are reusable, and the keyword “def” is used to define a function.
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
These arguments allow flexible function calls (e.g., greet(name="Guest")
).
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Bob")
Lambda functions in Python are small, anonymous functions defined using the lambda
keyword. They are typically used for short, throwaway functions that are not reused elsewhere. A lambda function can take any number of arguments but must have a single expression. It’s often used in situations like sorting or with functions like map()
or filter()
.
square = lambda x: x * x
print(square(5))
Data structures are like containers used to organize and store data efficiently in Python. They allow developers to access and manipulate data in structured and useful ways. Python provides several built-in data structures, such as lists, tuples, dictionaries, and sets, each suited for different use cases.
Lists are ordered, mutable collections of items that can store elements of different data types. You can add, remove, or change items in a list using built-in methods. They are commonly used when you need to work with sequences of data.
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
print(fruits[0])
Tuples are ordered, immutable collections that can also store elements of various data types. Once created, the contents of a tuple cannot be changed, making them useful for storing constant data or ensuring data integrity.
colors = ("red", "green", "blue")
print(colors[1])
Dictionaries are unordered collections of key-value pairs, allowing for fast data lookup and retrieval. Each key must be unique, and values can be of any data type. They’re ideal for storing related data, such as attributes of an object.
person = {"name": "Alice", "age": 25}
print(person["name"])
Sets are unordered collections of unique elements. They are commonly used for membership testing and eliminating duplicate entries. Sets support mathematical operations like union, intersection, and difference.
unique_numbers = {1, 2, 3, 4}
unique_numbers.add(5)
print(unique_numbers)
File handling in Python allows you to read from and write to files on your system. This is useful for tasks such as saving data, logging events, or reading configuration files. Python makes file operations simple and efficient using built-in functions like open()
, and context managers with with
for safe file access.
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, file!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Error handling in Python is done using try
, except
, and finally
blocks to catch and manage exceptions gracefully. This helps prevent programs from crashing unexpectedly and allows you to respond appropriately to different error types. It’s an essential part of writing robust and reliable code.
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("This block always executes.")
Modules are pre-written pieces of code that you can import and reuse in your program. Python comes with a standard library of modules like math
, datetime
, and os
, which provide useful functions for a variety of tasks. You can also install third-party modules or write your own.
import math
print(math.sqrt(16))
You can create your own Python module by saving functions in a .py
file and importing it into other scripts. This promotes code reusability and organization, especially in larger projects. Custom modules work just like built-in or third-party ones. Create a file mymodule.py
:
def add(a, b):
return a + b
Then import it:
import mymodule
print(mymodule.add(2, 3))
Python’s ecosystem is rich with libraries that simplify complex tasks and extend the language’s capabilities. These libraries are widely used in fields like data science, machine learning, web development, and automation. Below are a few essential libraries that every beginner should get familiar with.
NumPy (Numerical Python) is a library used for working with arrays and performing numerical computations. It provides support for large, multi-dimensional arrays and a wide range of mathematical operations. NumPy is foundational in scientific computing and is used extensively in data analysis and machine learning.
import numpy as np
array = np.array([1, 2, 3])
print(array * 2)
Pandas is a powerful data manipulation and analysis library built on top of NumPy. It provides two primary data structures: Series and DataFrame, making it easy to load, analyze, and visualize data. It’s a go-to tool for data scientists and analysts dealing with tabular data.
import pandas as pd
data = {"name": ["Alice", "Bob"], "age": [25, 30]}
df = pd.DataFrame(data)
print(df)
Matplotlib is a plotting library that enables you to create static, animated, and interactive visualizations in Python. It is particularly useful for generating line graphs, bar charts, histograms, and scatter plots. It’s often used in conjunction with Pandas and NumPy for data visualization.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Requests is a simple and intuitive HTTP library used to send all kinds of HTTP requests in Python. It abstracts the complexities of making web requests behind a simple API, making it easy to interact with RESTful APIs and web services.
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
This Python guide offers a strong foundation for exploring the language. However, consistent practice is essential to truly master and become confident in using Python. Python is a beginner-friendly, versatile, and powerful programming language that will help you in numerous domains, from data science and machine learning to web development and automation. In this tutorial, we have provided a comprehensive walkthrough of Python fundamentals, including syntax, data structures, control flow, functions, file and error handling, and essential libraries. By mastering these foundational concepts, you equip yourself with the tools to solve real-world problems and advance into more specialized areas. Keep practicing by building small projects, exploring more libraries, and contributing to open-source projects. This is the best way to grow your skills and confidence as a Python programmer. Keep practicing and building projects to deepen your understanding. Happy coding!
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
With a strong background in data science and over six years of experience, I am passionate about creating in-depth content on technologies. Currently focused on AI, machine learning, and GPU computing, working on topics ranging from deep learning frameworks to optimizing GPU-based workloads.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi Pankaj, Thanks for sharing this. I am new to python, this is definitely helpful
- Vishwam Sirikonda
Hi Pankaj, Thanks much for details… will help us clearly as I’m new to python
- diva karan
This is a really great blog for python learning as everything is explained very clearly. I would really appreciate if you could include linked lists and trees in your list of topics. Thank you.
- Riya Jain
Hi Pankaj, Thanks and it helps me a lot. Could you please share the video link or Pdf for the same. Most appreciated!! Thanks, Hari Kumar S
- Hari Kumar
This page probably attracts major amount of your audience. Great efforts on managing to keep this page comprehensive yet simple. Thanks!!
- Nandan Adeshara
Hi Pankaj, Thank you so much for all of this detailed training material on Python. What would make it super is adding exercises for the reader to try. Or perhaps suggest that the reader make up his own because you really learn when you practice it.
- Harvey Wise
hi pankaj can you help me to get some of my queries like image processing to get the barcode or QR code out of an image and For Data transfer with SAP?
- parshant vashishtha
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.