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!!
Introduction:
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 .
Getting Started:
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:
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.
Basic Syntax:
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):
- Variables: Variables are used to store data values. In Python, you can create a variable and assign a value to it using the assignment operator (
=
). Variable names should be descriptive and follow certain rules, such as starting with a letter or underscore and consisting of letters, numbers, and underscores.
x = 10
name = "Brahma"
is_active = True
- Data Types: Python supports various data types to represent different kinds of information. Common data types include integers (int), floating-point numbers (float), strings (str), and booleans (bool), among others.
age = 25
height = 1.75
name = "Bob"
is_student = False
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).
result = 10 + 5
difference = 20 - 8
product = 3 * 4
quotient = 15 / 3
is_equal = (10 == 5)
not_equal = (10 != 5)
greater_than = (20 > 10)
less_than = (15 < 20)
is_valid = True and False
is_active = True or False
not_active = not True
Oh!! That’s a lot to know in one go but yeah you already got in the 40% club.
Control Flow:
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:
elif another_condition:
else:
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: A
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 afor
loop is as follows:
for item in 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: A
while
loop repeats a block of code as long as a specified condition is true. The syntax for awhile
loop is as follows:
while condition:
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.
Functions:
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.
- Defining Functions: In Python, you can define a function using the
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.
- Calling Functions: To execute a function, you simply need to call it by its name followed by parentheses. If the function takes parameters, you need to provide values for those parameters.
greet()
result = add_numbers(5, 3)
print(result)
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.
- Passing Arguments: Functions can take zero or more parameters, allowing you to pass data to them for processing. Parameters can have default values, making them optional.
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")
greet("Bob")
result1 = exponentiate(2)
result2 = exponentiate(3, 4)
print(result1)
print(result2)
- Returning Values: Functions can optionally return a value using the
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)
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.
Data Structures:
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:
- Lists: A list is a collection of items that are ordered and mutable (modifiable). Lists are created by enclosing comma-separated values within square brackets
[]
.
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]
-
Slicing: You can extract a sublist (slice) from a list using slicing notation
[start:end:step]
.sublist = fruits[1:3]
-
Adding Elements: You can add elements to a list using methods like
append()
,insert()
, or concatenation.fruits.append("orange")
-
Removing Elements: You can remove elements from a list using methods like
remove()
,pop()
, or slicing.fruits.remove("banana")
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.
- Tuples: A tuple is a collection of items that are ordered and immutable (unchangeable). Tuples are created by enclosing comma-separated values within parentheses
()
.
- Tuples: A tuple is a collection of items that are ordered and immutable (unchangeable). Tuples are created by enclosing comma-separated values within parentheses
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.
- Dictionaries: A dictionary is a collection of key-value pairs that are unordered and mutable. Dictionaries are created by enclosing comma-separated key-value pairs within curly braces
{}
.
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"]
-
Adding Elements: You can add new key-value pairs to a dictionary by assigning a value to a new key.
person["gender"] = "Female"
-
Removing Elements: You can remove key-value pairs from a dictionary using the
del
keyword or thepop()
method.del person["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.
Conclusion:
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!