Python has become one of the most popular programming languages for beginners and experienced developers.
Its simple syntax, vast standard library, and thriving ecosystem of open-source packages make Python a versatile language for building all kinds of applications. Python excels in many domains, from web apps and APIs to data science, machine learning, and automation.
This comprehensive guide covers the fundamentals of Python programming that you need to know as a beginner.
We will explore the key features of the language through examples and also see how to write complete Python programs for different tasks. By the end, you'll have the skills to build real-world projects. Let's get started!
Setting Up Python
Before we begin coding in Python, we need to install it on the machine. The latest stable version is Python 3, which has many improvements over Python 2.
Head to python.org and download the Python 3 installer for your operating system. This will include the Python interpreter, standard library, and development tools like the IDLE editor.
Be sure to check the box that adds Python to PATH during installation. After installation completes, open the command prompt or terminal and run:
python --version
This should print the installed Python version. Congrats, you now have Python ready for programming on your system!
Python Interpreter
The Python command launches the Python interpreter - an interactive shell that can execute code line by line.
For example, try this:
print("Hello World!")
This prints the famous starter message. The interpreter is great for testing snippets and modules in an exploratory manner.
You can do arithmetic like 2 + 3 and assign variables like x = 5. It's also helpful for debugging scripts one statement at a time. Just type Python in the terminal to start the interpreter.
But for larger programs, we'll want to write the code in a file that can be repeatedly executed.
Python Scripts
While the interactive shell is great, real applications are written as scripts saved in .py files. Open up your favorite text editor like VS Code, Atom, or Sublime, and create a file named first.py with these contents:
print("This is my first Python script!")
This is a simple Python script displaying a message. To execute it, open the terminal and run the following:
python
first.py
You should see the print message on the next line. By convention, Python scripts are named using lower_case_with_underscores. Make sure to include the .py extension.
Now that you know how to write and run scripts, let's review the Python programming concepts.
Python Syntax Basics
Python has a simple and elegant syntax that is easy to learn. Here are some of the key elements:
- Code is indented using whitespace instead of braces {}
- Colon: indicates the start of the code block
- Comments start with the # symbol
- Semicolons; are optional at the end of statements
- Parentheses () for function calls and expressions
Here's a simple example with these elements:
# This is a comment
x = 5 # Assign 5 to variable x
if x > 0: # Start if code block
print(x) # Indented - so part of if block
print("Done") # Runs after if block
Some other Python syntax basics:
- Variables don't need explicit declaration
- Newlines don't matter - one statement per line is the convention
- Has both single ' ' and double " " quoted strings
- Supports multiple variable assignment like x, y = 1, 2
Python has a clear visual layout, making the code easy to read and understand.
Variables and Data Types
Like most languages, Python has variables that can store values in memory for later use.
Variables are named labels that reference a value. For example:
message = "Hello" # String variable
count = 5 # Integer variable
price = 9.99 # Float variable
We can then use these variable names instead of values in the code.
Some rules for Python variables:
- Named using alphanumeric characters A-Z a-z 0-9 and underscores _
- Case-sensitive - message and Message are different variables
- Can reassign values to variables at any time
Python is a dynamically typed language. This means variables do not need explicit data type declaration. The interpreter infers and sets the type automatically based on value.
Some common Python data types:
- Integers - whole numbers like 10, 100, -50
- Floats - decimals like 3.14, 9.99
- Strings - text as a sequence of Unicode characters in 'single quotes' or "double quotes."
- Boolean - True or False value
- List - ordered collection in [square brackets]
- Tuple-ordered immutable collection in (parentheses)
- Set - unordered collection of unique objects in {curly braces}
- Dictionary - collection of key-value pairs like {"key1": "value1"}
Let's see some examples of different data types:
# Integer
num = 10
# Float
price = 9.99
# String
message = 'Hello World'
# Boolean
flag = True
# List
numbers = [1, 2, 3]
# Tuple
point = (2, 3)
# Set
unique = {1, 2, 3}
# Dictionary
info = {"name": "John", "age": 30}
Python is a dynamically typed language so we don't need to specify types explicitly. The interpreter handles that automatically.
Operators
Operators are special symbols that perform operations on variables and values. Python includes all standard arithmetic, comparison, logical, and bitwise operators:
- Arithmetic - +, -, , /, %, *, //
- Comparison - ==, !=, >, <, >=, <=
- Logical - and, or, not
- Bitwise - &, |, ~, ^, >>, <<
Let's see them in action through some examples:
# Arithmetic
print(2 + 3) # 5
print(10 - 3) # 7
# Comparison
print(5 == 5) # True
print(10 != 20) # True
# Logical
print(True and False) # False
print(not False) # True
# Bitwise
print(12 & 5) # 4
These operators allow for performing all types of mathematical, comparison, logical, and bitwise operations in Python.
Control Flow
Control flow refers to the order in which statements are executed in a program. Python includes several constructs for controlling the flow:
Conditionals - Perform different actions based on conditions:
age = 20
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible")
Loops - Repeat code block multiple times:
for i in range(5):
print(i) # Prints 0 1 2 3 4
x = 0
while x < 5:
print(x)
x = x + 1
Functions - Reuse code in modules:
def greet(name):
print("Hello "+ name)
greet("John")
Control flow statements like these allow complex and flexible programs in Python.
Strings
Text manipulation is an important aspect of any programming language. Python has a set of built-in methods for common string operations:
message = "Hello World"
# Length
print(len(message)) # 11
# Contains
print("Hello" in message) # True
# Concatenate
print("Hello " + "World") # Hello World
# Uppercase
print(message.upper()) # HELLO WORLD
# Lowercase
print(message.lower()) # hello world
# Startswith / Endswith
print(message.startswith("H")) # True
# Split into list
print(message.split(" ")) # ['Hello', 'World']
Some other common string methods include strip(), replace(), find(), index(), etc. Strings in Python are immutable - i.e., the operations return new strings rather than modifying the original.
Conditionals and Loops
Branching and looping constructs enable non-linear program flow based on conditions.
If-else statement checks a condition and executes different blocks:
age = 20
if age >= 18:
print("Eligible")
else:
print("Not eligible")</code></pre>
For loop iterates over items in a sequence:
<pre><code class="language-python">colors = ["red", "green", "blue"]
for color in colors:
print(color)
While the loop executes the block until the condition is false:
count = 5
while count > 0:
print(count)
count = count - 1
Break and continue statements can change loop execution. Conditionals and loops are found in almost every Python program.
Functions
Functions organize code into reusable blocks that perform specific tasks. They take parameters, operate on them, and return results.
In Python, we define functions using the def keyword:
def multiply(x, y):
return x * y
print(multiply(2, 3)) # 6
Function parameters have a local scope, while variables declared outside have a global scope. Functions can return multiple values as tuple:
def minmax(numbers):
return min(numbers), max(numbers)
mini, maxi = minmax([1, 2, 3, 4])
Functions make code modular and increase reusability.
Classes and Objects
Python is an object-oriented language, meaning it supports classes, inheritance, and polymorphism.
A class defines attributes and behaviors for an object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
p1 = Person("John", 30)
p1.greet()
init() constructor method initializes the object state while other methods define behaviors. Objects can access their attributes and invoke methods.
Classes can inherit from other classes:
class Student(Person):
pass
s1 = Student("Mary", 20)
s1.greet() # Inherited method
OOP allows the modeling of real-world entities and handles complexity through abstraction and polymorphism.
Modules
Python enables the modularization of code using modules. A module is simply a .py file containing related classes, functions, etc.
Modules can be imported using the import keyword:
# File: utils.py
def greet(name):
print("Hello "+ name)
# Main file
import utils
utils.greet("John")
The from keyword imports specific objects from a module:
from utils import greet
Modules make code more organized and improve reusability. The Python standard library provides many useful built-in modules.
Python Standard Library
Python ships batteries include a large standard library of modules for common tasks:
- sys - system functions and info
- os - operating system interfaces
- math - mathematics operations
- random - generate random numbers
- datetime - date and time handling
- JSON - encode and decode JSON
- re - regular expressions
- http - HTTP internet protocols access
- sqlite3 - database access
- zlib - compression
And many more! The full list is in the Python documentation.
Let's see an example of the OS module:
import os
print(os.getcwd()) # Prints current working directory
There is no need to install additional packages for common programming tasks.
External Libraries
While the standard library is extensive, Python developers rely on a vast ecosystem of open-source third-party libraries for more complex tasks.
Some popular ones:
- NumPy - foundational package for scientific computing
- Pandas - data analysis and manipulation
- Matplotlib - 2D plotting and visualization
- Seaborn - statistical data visualization
- OpenCV - image and video processing
- TensorFlow - machine learning
- Keras - neural networks
- Scrapy - web scraping framework
- Django - full-featured web framework
- Flask - micro web framework
- PyQt - GUI development
These libraries can be installed using Python's pip package manager. They extend Python's capabilities to specialized domains.
Virtual Environments
Python virtual environments allow you to isolate project dependencies locally.
They essentially create a self-contained space separate from the global packages for Python packages.
This allows the installation of different versions of libraries for different projects.
Environments can be created using the Venv module:
python -m venv projectenv
This will set up a new environment in the projectenv folder. Activate it:
source projectenv/bin/activate
Now pip will install packages into this virtual environment. Deactivate to exit the environment.
Environments ensure project dependencies don't conflict with each other.
File I/O
Reading and writing files is an integral operation in many programs. Python has a built-in open() function to access files.
Files must be opened in read r, write w, or append a mode.
To read a file:
file = open('data.txt', 'r')
content = file.read()
file.close()
To write a file:
file = open('data.txt', 'w')
file.write('Some content')
file.close()
Make sure to close files after accessing them. The with statement auto closes files even after exceptions.
CSV and JSON modules process these data formats. Overall, Python makes working with files very straightforward.
Exception Handling
Exceptions are errors that disrupt program flow, like missing files, network failure, etc.
Python has built-in exception classes, and we can define custom exceptions by inheriting from Exception.
Exceptions can be handled using try-except blocks:
try:
file = open('data.txt') # May raise IOError
content = file.read()
except IOError:
print("Could not open file")
This prevents the program from crashing. Multiple except blocks can handle different exceptions.
Finally, clause executes cleanup code regardless of exception. Proper exception handling makes programs robust.
Comprehensions
List, set, and dictionary comprehensions provide a concise way to create collections from sequences.
nums = [1, 2, 3]
squares = [x**2 for x in nums] # [1, 4, 9]
Set and dictionary comprehensions:
names = ["John", "Mary"]
unique = {name[0] for name in names} # {'J', 'M'}
person = {"name": "John", "age": 20}
copy = {k:v for k,v in person.items()}
Comprehensions are a clean way to transform and initialize collections.
Decorators
Python decorators are constructs that wrap a function to modify its behavior without permanently changing it.
def uppercase(func):
def wrapper():
original_result = func()
modified_result = original_result.upper()
return modified_result
return wrapper
@uppercase
def greet():
return "Hello!"
print(greet()) # HELLO!
The decorator @uppercase applies wrapper() function on greet() to convert the result to uppercase.
Decorators are commonly used to add logging, permissions, or caching to functions.
Conclusion
This concludes our comprehensive guide to Python programming for beginners. We started with syntax, data types, operators, variables, control flow, and functions.
Then, we covered more advanced topics like strings, modules, file and exception handling, classes, and objects. Finally, I saw some of Python's unique aspects - comprehension and decorators.
After reviewing these concepts with examples, you should feel comfortable reading and writing basic Python programs.
The next step is to apply these skills to build projects, contribute to open-source packages, and join the Python community!
The key is to keep practicing by coding regularly. Python has a vibrant ecosystem of frameworks and tools that enable you to build complex applications.
The Python documentation and communities like StackOverflow are great resources for troubleshooting errors and learning best practices.
I hope you enjoyed reading this guide and feel motivated to start your Python programming journey. If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.
Top comments (2)
thanku for this amazing post
most welcome