The Python Journey – Chapter I : Get The Basics Right

the python journey ch1

The objective of this article is to familiarize all the people who want to get a hang of Python programming language about the nitty-gritties of the language. The Python Journey starts here and we should get all the nuances right. I started learning Python back in the year 2007 when Python was already more than a decade old and mature. Back then people or I’ld call them hardcore programmers used Java as the defacto choice for coding. And why not, it supported maximum things a corporate would want to write down a huge project. It was a mammoth! I hated Java, although I was familiar with it. It was purely verbose and bloated for the programmer in me. In came Python and I fell in love with the syntax. Perhaps it was slower by a magnitude than Java but I did not care. It was the sheer joy of writing code in python that made me love it.  We will be having the most comprehensive series of articles on the python language in the next few days/weeks to understand the language completely. Post that, and I mean eventually we would post articles that help us understand Flask and Django. Also, at the end of the series we plan to release a pdf book bunching up all the articles. This will give you a value addition and kick start, share your journey of learning Python successfully.

Introduction

Python is a versatile, high-level programming language known for its simplicity and readability, making it one of the most popular languages in the world. Historically it was released in 1991 by Guido van Rossum, Python has since evolved into a powerful tool used in various domains, including web development, data analysis, artificial intelligence, machine learning, automation, and more. Its clean, easy-to-read syntax allows programmers to write less code compared to other programming languages like Java or C++, while still achieving the same functionality.

Python’s emphasis on code readability, using indentation instead of braces to define code blocks, makes it an excellent choice for both beginners and experienced developers. It also boasts a massive standard library and community-contributed modules, enabling programmers to quickly find solutions to many common tasks without writing custom code.

One of Python’s core strengths lies in its flexibility. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python is an interpreted language, meaning that it executes code line by line, which facilitates rapid development and testing.

In this article, we will delve into the basic syntax of Python, explore variables and data types, and examine core programming concepts such as conditionals, loops, functions, and data structures. By the end, you’ll have a strong foundation to continue exploring more advanced Python features.


The Basic Syntax

Let’s understand the python basic syntax. This will include all the details of the language. Python is widely known for its simple and readable syntax. This simplicity makes it a great choice for beginners and experienced developers alike. Understanding the basic syntax is the first step to mastering Python programming. Let’s delve into key elements that define Python’s structure.

Python Indentation

Unlike many other programming languages like C, Java, or JavaScript, which use curly braces {} to define blocks of code, Python uses indentation. Indentation is not just for readability; it’s how Python organizes the flow of control within the code. Each level of indentation represents a new code block.

For example:

if True:

    print("This is inside the if block")

    if 10 > 5:

        print("This is inside the nested if block")

print("This is outside all if blocks")

In this example:

  • The first print() statement is indented four spaces, meaning it is part of the if block.
  • The second print() is indented eight spaces, which shows that it’s part of the nested if block.
  • The final print() has no indentation and is outside of any block.

Python strictly requires consistent indentation, and the most common convention is using 4 spaces per level of indentation. Mixing tabs and spaces will result in an error.

if True:

 print("This will raise an IndentationError because of inconsistent indentation")

Python Comments

Comments in Python are used to describe what the code does and are ignored by the Python interpreter. There are two types of comments:

  • Single-line comments: Start with the # symbol. Everything on the same line after the # is considered a comment.

Example:

# This is a single-line comment

print(“Hello, World!”)  # This is an inline comment

  • Multi-line comments: Although Python doesn’t have an explicit multi-line comment syntax like /* */ in some other languages, you can create multi-line comments using triple quotes (“”” “”” or ”’ ”’). This is actually a string that isn’t assigned to any variable, so it gets ignored during execution.

Example:

"""

This is a multi-line comment.

It spans multiple lines.

"""

print("This code will execute")

Statements in Python

A statement in Python is essentially a line of code that performs an action. For example, assigning a value to a variable or calling a function. Python statements are typically written one per line.

python

Example:

x = 10  # Assignment statement

print(x)  # Function call statement

If you need to write multiple statements on the same line, they can be separated by a semicolon (;), though this is generally discouraged in Python as it reduces readability.

Example:

x = 5; y = 10; print(x + y)

However, it’s best to write each statement on its own line to maintain clean and readable code.

Line Continuation in Python

Sometimes, a statement in Python can be too long to fit on one line. To continue a statement across multiple lines, you can use a backslash (\) as a line continuation character. Python also allows implicit line continuation inside parentheses (), brackets [], and braces {}, without needing a backslash.

Examples:

  • Explicit Line Continuation:
total_sum = 1 + 2 + 3 + 4 + 5 + \

            6 + 7 + 8 + 9 + 10

print(total_sum)
  • Implicit Line Continuation (inside parentheses):

total_sum = (1 + 2 + 3 +

             4 + 5 + 6 +

             7 + 8 + 9 + 10)

print(total_sum)

In both cases, Python allows breaking the code into multiple lines for better readability.

Quotations in Python

Python supports three types of quotes for string literals: single quotes (‘), double quotes (“), and triple quotes (”’ or “””). You can use either single or double quotes for single-line strings, and triple quotes for multi-line strings.

Examples:

  • Single-line string:
single_quote_string = 'Hello'

double_quote_string = "World"

print(single_quote_string, double_quote_string)
  • Multi-line string:
multi_line_string = """This is a multi-line string.

It spans several lines."""

print(multi_line_string)

Case Sensitivity in Python

Python is a case-sensitive language, meaning that variable, Variable, and VARIABLE would be considered different identifiers.

Example:

variable = 10

Variable = 20

print(variable)  # Output: 10

print(Variable)  # Output: 20

Reserved Keywords

Python has a set of reserved keywords that cannot be used as variable names, function names, or any other identifiers. These keywords have predefined meanings in the language, and they control the flow of execution, data types, etc.

Python Crash Course, 3rd Edition Paperback – 10 January 2023

To view all reserved keywords in Python, you can use the following code:

import keyword

print(keyword.kwlist)

Examples of reserved keywords include:

  • if
  • else
  • while
  • for
  • try
  • def
  • class
  • return

Attempting to use any of these keywords as variable names will result in a syntax error.

Print Function

The print() function is one of the most used functions in Python. It allows you to output data to the console.

Example:

print(“Hello, World!”)

Python 3.x requires parentheses () with print(), which is different from Python 2.x, where parentheses were optional. Note in this article and its series we are going to go ahead with Python 3.12.x

You can print multiple values by separating them with commas:

name = "Alice"

age = 25

print("Name:", name, "Age:", age)
The Python Journey

Input Function

Python uses the input() function to take user input. The input is always returned as a string, so it must be type-cast if you need a different data type (e.g., an integer).

Example:

user_input = input(“Enter something: “)

print(“You entered:”, user_input)

Variables and Assignment

Python is smart, it was meant to be. The variables need not be explicitly defined. Python, variables are created when you assign a value to them. There’s no need to declare the type of the variable as Python is dynamically typed. Lets understand the variable assignment further.

Example:

x = 10  # Integer assignment

y = “Hello”  # String assignment

Variables can be reassigned to a different type at any time:

x = 10

x = “Now I’m a string”

print(x)

Python also supports multiple assignment, allowing you to assign values to multiple variables in a single statement:

a, b, c = 1, 2, “Three”

print(a, b, c)

The basic syntax of Python emphasizes readability and simplicity. Indentation defines code blocks, and its clean syntax removes much of the boilerplate code found in other languages. With a solid understanding of Python’s basic syntax, you are well-prepared to write clean and efficient Python programs.

Overall, we have these few key takeaways from this chapter.

  • Indentation: Python uses indentation to define code blocks, unlike other languages that use curly braces {}.
  • Comments: Single-line (#) and multi-line comments (“”” “”””) help document code.
  • Statements: Python has simple, single-line statements, and multiple statements can be combined using a semicolon.

So, I hope you have started to understand the language syntax and details. We will dive into more details as we go ahead. We conclude this chapter here, stay tuned for the next version to understand the Python Variables and Data Types in details. Please write down your comments and questions so that we can cover those up in the upcoming articles as chapters. Stay Hungry, Stay Tuned!

Curated Reads

Dhakate Rahul

Dhakate Rahul

Leave a Reply

Your email address will not be published. Required fields are marked *