Python: The Ultimate Beginner’s Guide to Mastering Python

cover

Table of Contents

Python is a general-purpose programming language that is becoming more and more popular for:

  • performing data analysis
  • automating tasks,
  • learning data science,
  • machine learning, etc.

What is Python?

Interpreted high-level, general-purpose programming language

An interpreter is a computer program that directly executes instructions written in a programming or scripting language without first compiling them into machine language code. Generally, an interpreter executes instructions using one of the following strategies:

  1. Parse the source code and immediately execute it;
  2. Convert the source code to an efficient intermediate representation or object code and execute it instantly;
  3. Explicitly execute stored precompiled bytecode made by a compiler and matched with the interpreter Virtual Machine.

A high-level language is any programming language that enables the development of a program in a much more user-friendly programming context and is generally independent of the computer’s hardware architecture. A high-level language has a higher level of abstraction from the computer and focuses more on the programming logic rather than the underlying hardware components such as memory addressing and register utilization.

A general-purpose programming language is a programming language that developers can use to build software for a wide range of application domains.

Dynamically-typed language

Dynamically typed languages are those languages in which the interpreter assigns variables a type at runtime depending on their current values.

Unlike dynamically typed languages, statically typed languages execute type checking at compile-time. If you use a dynamically typed language, you don’t have to specify the data types of your variables ahead of time.

Automated garbage collection

When the system no longer uses an item, garbage collection frees up memory. The system disposes of the unused items and repurposes the memory slot to store new items. You may think of it as a computer recycling system.

Python has an automated garbage collection feature. It has an algorithm that disposes of objects which are no longer required.

Supports multiple programming paradigms and object-oriented

The imperative programming paradigm uses the imperative mood of natural language to express directions. It executes commands step-by-step, just like a series of verbal commands.

The functional programming paradigm treats program computation as evaluating mathematical functions based on lambda calculus. This is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is classified as declarative programming, following the “what-to-solve” approach, expressing logic without describing its control flow.

The procedural programming paradigm unequivocally falls under the umbrella of imperative programming, commonly called subroutines or functions. The program composition is more of a procedure call, and the execution is sequential, causing a resource bottleneck.

In the object-oriented programming paradigm, basic entities contain data and ways to manipulate it. However, implementing the same logic using object-oriented methodology can be difficult, as object-oriented design principles promote code reuse and data hiding.

Why Python?

Simple & Easy to Learn

Python is extremely simple to learn and use. Python is an easily accessible programming language due to its simple syntax and emphasis on natural language. Because of its simplicity, Python allows for faster coding and execution than other programming languages.

Python’s popularity stems from its simplicity in syntax, which allows even novice developers to read and understand it.

Python syntax allows developers to write shorter programs than other programming languages.

Mature and Supportive Python Community

Python has been around for over 30 years, a significant time for any programming language community to grow and mature to support developers of all levels. Many materials, guidelines, and video tutorials are available for Python language learners and developers of all skill levels and ages.

Languages that lack developer assistance or documentation don’t grow. But Python has no such issues as it has been around for a long time. The Python developer community is one of the most active programming language communities.

This means that if someone has a problem with Python, they can get instant help from developers of all levels in the community. Getting help on time is critical to the project’s development.

Support from Renowned Corporate Sponsors

Programming Languages evolve quicker when a corporation sponsors them. Oracle and Sun support Java, while Microsoft supports Visual Basic and C#. Facebook, Amazon Web Services, and Google all support Python programming.

Google began using Python in 2006 for numerous applications and platforms. Google has invested much time and money in training and developing Python. They have even created a dedicated portal only for Python. The number of developer tools and documentation for Python continues to expand.

Hundreds of Open-Source Python Libraries and Frameworks

Python provides good libraries that you may employ to reduce time and effort during the early development cycle due to corporate backing and a large supporting community. As of January 2022, the Python Package Index (PyPI) has approximately 352,000 libraries and frameworks accessible. Many cloud media providers also provide cross-platform compatibility through library-like technologies.

There are also specialized libraries like nltk for natural language processing and scikit-learn for machine learning.

Where is Python used?

Novice programmers, as well as highly skilled professional developers, use Python. Academia, web companies, large corporations, and financial institutions use it for various purposes:

  • Web and Internet development: Python powers the server to create web applications. Web frameworks like Flask, Django, and FastAPI are quite popular.
  • Software development: Python is used to create GUI applications, connect databases, etc. SqlAlchemy is a popular library for connection with databases.
  • Scientific and Numeric applications: Python handles big data and performs complex mathematics. Libraries include Numpy, Pandas, Dask, PySpark, Vaex, Data Table and PyPolars.
  • Education: Python is a great language for teaching programming at the introductory level and in more advanced courses.
  • Desktop GUIs: The Tk GUI library, which includes most of Python’s binary distributions, is used extensively to build desktop applications. PyQt and PySide are also popular GUI libraries with Qt bindings.
  • Business Applications: Python is also used to build ERP and e-commerce systems.

Comments

In Python, comments act like explanatory notes for your code. They’re ignored when the program runs. The hash symbol # denotes the beginning of a comment, which continues until the end of the line of code. A comment may occur at the start of a line, after whitespace or code, but not inside a string literal.

A single-line comment may be looked like below:

# This is a comment in Python.

To represent multi-line comments, # has to be preceded before the start of the new line like below:

# This is a comment in Python.
# This is a multi-line comment.

We can include comments after the Python statement like this one.

>>> 8 + 2       # Add two literals
10 

Liberally sprinkling comments across our code is usually a good programming practice. Remember, the code shows you how to do something, and the comment tells you why.

Arithmetic Operations in Python

We can use the Python Console using the following expressions to begin with the simplest mathematical operations, such as addition, subtraction, multiplication, and division.

# Addition
>>> 4 + 2
6

# Subtraction
>>> 7 - 4
3

# Multiplication
>>> 4 * 2
8

# Division
>>> 5 / 3
1.6666666666666667

# Modulo  
>>> 5 % 2           # returns remainder
1

# Integer Division 
>>> 5.0 // 2        # Divide the number and round down to an integer
2

# Exponents
>>> 2 ** 2
4

Expressions may also be used as operands in longer composite expressions.

# Composite expression
>>> 4 + 2 - 3 + 4
7

>>> 5 + 3 * 3 - 4
10

In Python, mathematical operators follow the natural precedence observed in mathematics. The order of evaluation is always from left to right, and operands */// and % evaluated before + and -. The order in which operators are applied is called operator precedence.

Python allows brackets like this one to specify the order of evaluation manually.

>>> (5 + 3) * (3 - 4) 
-8

The print() function is a powerful tool that may be used to print anything in Python.

print() syntax

print(*value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

print() Parameters:

  • values – values to the printed. * Indicates that there may be more than one value.
  • sep – values are separated by sep. Default value: ' ' i.e., values passed in the print function will automatically be separated by ' '
  • end – end is printed at last. \n for new-line and \t for tab.
  • file – must be a value with the write(string) method. If omitted, sys.stdout will print the value on the screen.
  • flush – If True, the stream is forcibly flushed. Default value: False

Let’s look at a few samples to see how print() works.

Simple print function

>>> print('Hello World!')
Hello World!

Concatenating string and integer

>>> print('June', 2021)
June 2021

Concatenating two strings

>>> print('Harry', 'Potter')
Harry Potter

Concatenating a variable and string

>>> print(Name + 'is the eldest son in family.')
Sam is the eldest son in family.

Print two statements

>>> print('This is statement one.')
>>> print('This is statement two.)
This is statement one.
This is statement two.

Spacing/gap between two print statements

>>> print('This is statement one.')
>>> print()
>>> print('This is statement two.)
This is statement one.

This is statement two.

FORMATTING STRINGS

Python allows three ways for formatting Python strings.

f-strings (formatted strings)

f-strings are string literals that have an f at the beginning, and curly braces containing expressions that will be replaced with their values.

Here are some of the ways f-strings can make your life easier.

>>> name= 'Python'
>>> age = 30
>>> print(f'My name is {name} and I am {age} old.')
My name is Python and I am 30 old.

Floats can also be formatted to two decimal places, like :.2f with f-strings as below:

height = 5.891
name = 'Steve'
>>> print(f'{name} is a police officer. His height is {height:.2f} meters.')
Steve is a police officer. His height is 5.89 meters.

Don’t worry about the concepts of strings, floats, etc. We will be discussing that in my next post.

%-formatting strings

This formatting style has been in the language since the very beginning.

Let’s run through some examples of single and multiple-string formatting.

# String formatting with variable
>>> word = 'World'
print('Hello, %s' % word)       
Hello, World

# String formatting without any variable
>>> 'Hello, %s' % 'Jacob'      
'Hello, Jacob'

# String formatting with two or more variables
>>> height = 5.891
>>> name = 'Steve'
>>> print('%s is a police officer. His height is %.2f meters.'%(name, height))
Steve is a police officer. His height is 5.89 meters.

.format() function

The format() method is another helpful tool for printing and generating strings for output. Using this function, we can construct a string from information like variables. Take a look at the following code snippet.

>>> height = 5.891
>>> name = 'Steve'
>>> print('{x} is a police officer. His height is {y:.2f} meters.'.format(x=name, y=height))
Steve is a police officer. His height is 5.89 meters.

Escape Sequence

Escape characters are often employed to do certain jobs, and their use in code instructs the compiler to execute the appropriate action mapped to that character.

Let’s say we wish to write a string. That’s all for today. If we put this inside a double quotation "", we could write it as “That’s all for today.” However, if we write the identical phrase within a single quote '', we cannot write it since we have three '. The Python interpreter will get confused about where the string begins and finishes. As a result, we must indicate that the string does not terminate s in the string; rather, it is a component of the string. We may do this by using the escape sequence. We can specify it by using a \ (backslash character).

Let’s look at the example:

>>> 'That\'s all for today'
"That's all for today"

Here, we preceded ' with a \ character to indicate that it is a part of the string. Similarly, we need to use an escape sequence for double quotes to write a string within double quotes. Also, we can include the backslash character in a string using \\. We can break a single line into multiple lines using the \n escape sequence.

>>> print('That is all for today.\nYes, it really is.')
That is all for today.
Yes, it really is.

Another useful escape character is \t the tab escape sequence. It is used to leave tab spaces between strings.

>>> print('That\t is \tall \tfor \ttoday.')
That	 is 	all 	for 	today.

In a string, if we are to mention a single \ at the end of the line, it indicates that the string is continued in the next line, and no new line is added.

Consider the following:

>>> print('Python is a high-level interpreted programming language.\
        It is very popular in Data Science.')
Python is a high-level interpreted programming language.It is very popular in Data Science.

Similarly, several other escape sequences are documented in the official Python documentation.

Indentation

In Python, whitespaces are very critical. Indentation refers to whitespace at the beginning of a line. It is used to indicate the start of a new code block. A block, often known as a code block, is a set of statements in a program or script. Leading spaces at the beginning of a line establish the indentation level, which determines how statements are grouped. In addition, statements that go together must have the same indentation level.

A wrong indentation raises the error. Let’s look at the example below:

>>> name = 'World'
>>>    print('Hello,', name)
 File "<ipython-input-7-b8acd95efa68>", line 2
    print('Hello,', name)
    ^
IndentationError: unexpected indent

The error tells us that the program’s syntax is incorrect. That is, the program is not properly written. New blocks of statements cannot be indented at will. As we’ll see in the upcoming blog posts, indentation is an important tool for establishing new blocks of code and defining functions and flow statements.

This is the end of my article. Thanks for reading, and if you like it, please share it with your friends and colleagues by clicking the LIKE button.

You can connect with me on Twitter and LinkedIn

Search through our posts

Search

ABOUT THE AUTHOR

Picture of Kashif Naz
Kashif Naz
Kashif, the founder of CampMetrics, holds a strong belief that learning is one of life's most rewarding experiences. He generously shares his expertise to assist accounting and finance professionals in enhancing their abilities and achieving skill development.

Related Posts

Leave a Reply

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

© 2024 All Rights Reserved.