Python for Beginners

"A beginner-friendly guide to Python covering essential concepts with examples."

By Samir Niroula

28 October 2024
Python for Beginners

Python for Beginners: A Quick Guide

Python is a versatile, beginner-friendly language known for its readability and extensive libraries. Whether you're interested in web development, data science, or automation, Python is a great starting point. Here’s a compact guide covering Python basics.


Variables and Data Types

Variables store data, and Python supports several types like integers, floats, strings, and booleans.

Example:

name = "Alice"
age = 25
height = 5.6  # Float
is_student = True  # Boolean

Basic Operations

Python has standard arithmetic and comparison operators for calculations and logical checks.

Example:

 
x = 5 + 3  # Addition
y = 10 / 2  # Division
is_greater = x > y  # Comparison

Strings

Strings are text data enclosed in quotes. You can concatenate, slice, and format them.

Example:

greeting = "Hello, " + name
print(greeting[0:5])  # Output: Hello

Lists

Lists are ordered, mutable collections. They allow indexing, slicing, and various operations.

Example:

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")  # Adds orange
print(fruits[1])  # Output: banana

Dictionaries

Dictionaries store data as key-value pairs, making them useful for labeled data.

Example:

person = {"name": "Alice", "age": 25}
print(person["name"])  # Output: Alice

Conditionals

Conditionals help control the flow of the program using if, elif, and else.

Example:

if age > 18:
    print("Adult")
else:
    print("Minor")

Loops

Loops repeat code. for is used for iterating over sequences, while while repeats based on a condition.

Example:

 
for fruit in fruits:
    print(fruit)
 
i = 0
while i < 5:
    print(i)
    i += 1
 

Functions

Functions allow code reuse. Define functions with def, and use return to output results.

Example:

def greet(name):
    return "Hello, " + name
 
print(greet("Alice"))  # Output: Hello, Alice

Classes and Objects

Python is an object-oriented language, allowing for defining classes and creating instances (objects).

Example:

class Dog:
    def __init__(self, name):
        self.name = name
 
    def bark(self):
        return "Woof!"
 
my_dog = Dog("Buddy")
print(my_dog.bark())  # Output: Woof!

Modules and Libraries

Python has many built-in modules and third-party libraries. Import them with import.

Example:

import math
print(math.sqrt(16))  # Output: 4.0

File Handling

You can read and write files in Python with open.

Example:

with open("file.txt", "w") as file:
    file.write("Hello, world!")
 
with open("file.txt", "r") as file:
    print(file.read())

Conclusion

Python’s simplicity and versatility make it an excellent choice for beginners. Practice these basics to build a solid foundation for further exploration.