Understanding Python Basics: A Starter's Guide

Search for a command to run...

No comments yet. Be the first to comment.
Hold onto your keyboards, folks, because the universe decided to throw everything at the wall this week to see what would stick. We had courtroom drama worthy of a season finale, sci-fi headlines coming to life, and a study that basically confirmed y...
Remember that feeling when you’ve had a week so wild, you need a week to recover from it? Well, the tech world just had one of those. From courtroom dramas to AI getting a memory upgrade, the first week of August 2024 was a rollercoaster. So, grab yo...
Hey readers!! I am Brahma 👋 a passionate software engineer. I will be sharing my insights on the chapters of the famous Introduction to Statistical Learning with R aka ISLR. So, here we are and I will be sharing the insights on Chapter 1. I would hi...

Welcome to the Intro on ML! I'm Brahma 👋, a passionate software developer. I am documenting my learning journey through a series of blog posts. Stay tuned!! Introduction Machine Learning and Artificial Intelligence have been the talk of the town for...

Welcome to an interesting package, Gradio, in Python! I'm Brahma 👋, a passionate software developer. I am documenting my learning journey through a series of blog posts. Stay tuned!! Introduction Gradio is an open-source Python package that allows u...
Welcome to a beginner's guide to Python programming! I'm Brahma 👋, a passionate software developer. I am documenting my learning journey through a series of blog posts. Stay tuned!!
At its core, Python emphasizes code readability and simplicity, making it an ideal choice for beginners diving into the world of programming. Whether you aspire to become a data scientist, web developer, or software engineer, learning Python basics provides a solid foundation upon which to build your programming skills.
In this article, we'll embark on a journey to explore the essential concepts of Python programming, laying the groundwork for your continued learning and growth as a programmer. So, without further ado, let's dive into the exciting world of Python and unlock the secrets of this powerful language together.
Now, enough of this literature. Let's get to the real stuff 😉.
Installation:
Python is supported on various operating systems, including Windows, macOS, and Linux. Here's how to install it on each platform:
Windows: Visit the Python official website and download the latest version of Python for Windows. Run the installer and follow the on-screen instructions to complete the installation.
macOS: macOS typically comes with Python pre-installed. However, it's recommended to install the latest version using Homebrew. Open Terminal and enter the command brew install python. This will install Python alongside the system version.
Linux: Most Linux distributions include Python by default. However, you can install it via your package manager if needed. For example, on Ubuntu, you can use sudo apt-get install python3.
Interactive Mode:
Once Python is installed, you can start experimenting with it using the interactive mode. Here's how to access it:
Windows: Open the Command Prompt or PowerShell and type python to launch the Python interpreter.
macOS and Linux: Open Terminal and type python3.
You should see a prompt (typically >>>), indicating that you're in Python's interactive mode. Here, you can execute Python code line by line, making it ideal for simple calculations and experimentation.
For example, try entering 2 + 3 and pressing Enter. Python will evaluate the expression and display the result (5). [Anyways who uses python as a calculator😂]
Now that you have Python up and running, let's dive deeper into its syntax and features.
The syntax for python is as simple as write English. If you know how to write in English, congrats!! you know 20% of python already.
Let's see a small python code:
x=10
print(x)
That's it. Yeah, you read that right you are already eligble to put python as skill on your LinkedIn😂.
So, let's know what I just wrote. x=5 means there we stored the number 5 in the variable x.
If that sounded alien to you, then understand this like you have a container labelled x and you have put the number 5 into it. Sounds kinda weird but it is what it is😌.
Now let's know some serious jargons of Python (typically all languages have similar ones):
=). Variable names should be descriptive and follow certain rules, such as starting with a letter or underscore and consisting of letters, numbers, and underscores.# Example of variable assignment
x = 10
name = "Brahma"
is_active = True
# Examples of different data types
age = 25 # integer
height = 1.75 # float
name = "Bob" # string
is_student = False # boolean
Basic Operations: Python provides a set of basic operations for manipulating data. These include arithmetic operations (addition, subtraction, multiplication, division), comparison operations (equal to, not equal to, greater than, less than), and logical operations (and, or, not).
# Examples of basic operations
# Arithmetic operations
result = 10 + 5 # addition
difference = 20 - 8 # subtraction
product = 3 * 4 # multiplication
quotient = 15 / 3 # division
# Comparison operations
is_equal = (10 == 5) # equal to
not_equal = (10 != 5) # not equal to
greater_than = (20 > 10) # greater than
less_than = (15 < 20) # less than
# Logical operations
is_valid = True and False # logical AND
is_active = True or False # logical OR
not_active = not True # logical NOT
Oh!! That's a lot to know in one go but yeah you already got in the 40% club😏.
Another jargon🥲. But chill you have me!! Let me break that for you.
Control Flow basically means your mom asking you to bring something from the supermarket and if you don't bring that don't come home. [Yeah we all have been through this 🫠.] But chill python control flow is easier than that. I promise!!
In Python, control flow statements allow you to dictate the order in which your code is executed based on certain conditions or criteria. Two fundamental control flow structures are conditional statements (if, elif, else) and loops (for and while).
Conditional Statements: Conditional statements enable you to execute different blocks of code based on whether a condition evaluates to true or false. The syntax for an if statement is straightforward:
if condition:
# Code block to execute if condition is True
elif another_condition:
# Code block to execute if another_condition is True
else:
# Code block to execute if neither condition nor another_condition is True
Here's an example to illustrate how conditional statements work:
x = 10
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
In this example, if the value of x is greater than 0, it prints "x is positive". If x is less than 0, it prints "x is negative". Otherwise, if neither condition is met, it prints "x is zero".
Loops: Loops are used to repeatedly execute a block of code as long as a specified condition is true. Python supports two main types of loops: the for loop and the while loop.
for loop iterates over a sequence (such as a list, tuple, or string) and executes the block of code for each item in the sequence. The syntax for a for loop is as follows:for item in sequence:
# Code block to execute for each item in the sequence
Here's an example of a for loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This loop iterates over the fruits list and prints each fruit on a separate line.
while loop repeats a block of code as long as a specified condition is true. The syntax for a while loop is as follows:while condition:
# Code block to execute as long as the condition is True
Here's an example of a while loop:
count = 0
while count < 5:
print(count)
count += 1
This loop prints the values of count from 0 to 4, incrementing count by 1 in each iteration, until the condition count < 5 becomes false.
You might be wondering what if I want to perform some task repeatedly so do I need to write same thing again and again. Ofc NOT!! We are programmers not Ctrl+C & Ctrl+V guys. [Ofc we are 😂]
So, functions help us to perform some repeatative easily.
Functions play a crucial role in Python programming by allowing you to organize and reuse code effectively. They encapsulate a set of instructions that can be executed multiple times with different inputs, promoting code modularity and maintainability.
def keyword followed by the function name and parameters (if any). The function body contains the code to be executed when the function is called.def greet():
print("Hello, world!")
def add_numbers(a, b):
return a + b
The first function greet() simply prints "Hello, world!" when called. The second function add_numbers(a, b) takes two parameters a and b, adds them together, and returns the result.
greet() # Output: Hello, world!
result = add_numbers(5, 3)
print(result) # Output: 8
In this example, greet() is called without any parameters, while add_numbers(5, 3) is called with a set to 5 and b set to 3.
def greet(name):
print("Hello, " + name + "!")
def exponentiate(base, exponent=2):
return base ** exponent
In the greet(name) function, name is a required parameter. In the exponentiate(base, exponent=2) function, base is a required parameter, while exponent has a default value of 2.
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
result1 = exponentiate(2) # Uses default exponent (2)
result2 = exponentiate(3, 4) # Specifies exponent as 4
print(result1) # Output: 4
print(result2) # Output: 81
return statement. This allows the function to compute a result and pass it back to the caller.def add_numbers(a, b):
return a + b
sum = add_numbers(3, 5)
print(sum) # Output: 8
In this example, the add_numbers(a, b) function returns the sum of a and b, which is then assigned to the variable sum and printed.
So, now you know you are not a Copy-Paste programmer😂.
Hey!! What is this now? Does this mean putting data into some structures🤔?
Yes!! Kind of will get back to you on this unlike your HR 😂.
Python provides several built-in data structures that allow you to store and organize data efficiently. Three fundamental data structures in Python are lists, tuples, and dictionaries. Let's explore each of them in detail:
[].# Example of a list
fruits = ["apple", "banana", "cherry"]
Characteristics:
Lists are ordered, meaning the items have a defined order that will not change.
Lists are mutable, so you can modify their elements after creation.
Operations:
Accessing Elements: You can access individual elements of a list using indexing. Indexing starts at 0.
first_fruit = fruits[0] # Access the first element
Slicing: You can extract a sublist (slice) from a list using slicing notation [start:end:step].
sublist = fruits[1:3] # Extract elements from index 1 to index 2
Adding Elements: You can add elements to a list using methods like append(), insert(), or concatenation.
fruits.append("orange") # Add "orange" to the end of the list
Removing Elements: You can remove elements from a list using methods like remove(), pop(), or slicing.
fruits.remove("banana") # Remove "banana" from the list
Common Use Cases:
Lists are used to store collections of items where the order matters, such as to-do lists, shopping lists, or sequences of data.
Lists are versatile and can hold a mix of data types, making them suitable for various applications.
().# Example of a tuple
coordinates = (10, 20)
Characteristics:
Tuples are ordered, meaning the items have a defined order that will not change.
Tuples are immutable, so you cannot modify their elements after creation.
Operations:
Accessing Elements: You can access individual elements of a tuple using indexing, similar to lists.
Slicing: You can extract a subtuple (slice) from a tuple using slicing notation, similar to lists.
Common Use Cases:
Tuples are used to represent fixed collections of items, such as coordinates, RGB color codes, or database records.
Tuples are often used in scenarios where immutability is desired, such as dictionary keys or function arguments.
{}.# Example of a dictionary
person = {"name": "Alice", "age": 30, "city": "New York"}
Characteristics:
Dictionaries are unordered, meaning the order of key-value pairs is not guaranteed.
Dictionaries are mutable, so you can add, modify, or remove key-value pairs after creation.
Operations:
Accessing Elements: You can access the value associated with a key by using the key within square brackets.
age = person["age"] # Access the value associated with the key "age"
Adding Elements: You can add new key-value pairs to a dictionary by assigning a value to a new key.
person["gender"] = "Female" # Add a new key-value pair
Removing Elements: You can remove key-value pairs from a dictionary using the del keyword or the pop() method.
del person["city"] # Remove the key-value pair with the key "city"
Common Use Cases:
Dictionaries are used to represent structured data with named fields, such as user profiles, configuration settings, or JSON-like data.
Dictionaries provide fast lookups based on keys, making them ideal for scenarios where you need to quickly retrieve information based on a unique identifier.
So I hope now you know why its called DATA STRUCTURES.
Now that you have known a lot from this blog (I hope you did🙂), leave back a small heart(❤️) and some beautiful word(s) in the comments.
Keep coding, keep learning, and enjoy the endless possibilities that Python has to offer!
Happy coding! 🐍✨