Introduction

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?

1. 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 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 designed to be used for building software in a wide variety of application domains.

2. 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.

3. Automated garbage collection

When an item is no longer in use, garbage collection is used to free up memory. The unused item is disposed of, and the memory slot is repurposed for the storage of new ones. You may think of it as a computer recycling system.

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

4. Supports multiple programming paradigms and object-oriented

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

The functional programming paradigm treats program computation as the evaluation of 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 follows the "what-to-solve" approach—that is, it expresses logic without describing its control flow—hence it is also classified as the declarative programming model.

The procedural programming paradigm is a subclass of imperative programming (also known as 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 are objects that contain data and ways to manipulate it. But replicating the same logic in an object-oriented method is challenging since object-oriented design principles encourage code reuse and data hiding.

Why Python?

1. Simple & Easy to Learn

The Python language is extremely simple to learn and use. Python is one of the most accessible programming languages available due to its simple syntax and emphasis on natural language. Python codes can be written and executed much faster than other programming languages due to their simplicity.

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.

2. Mature and Supportive Python Community

Python has been around for over 30 years, which is significant time for any programming language community to grow and mature to support developers of all levels. There is lots of material, guidelines, and video tutorials 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 incredibly 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.

3. Support from Renowned Corporate Sponsors

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

Google began using Python in 2006 for numerous applications and platforms. Google has invested a lot of time and money on the training and development of the Python language. They have even created a dedicated portal only for python. The number of developer tools and documentation for Python continues expanding.

4. 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?

Python is used by the novice programmer as well as by the highly skilled professional developer. It is being used in academia, at web companies, in large corporations and financial institutions. It is used for:

  • Web and Internet development: Python is used on the server side to create web applications. Web frameworks like flask, Django and FastAPI are quite popular.
  • Software development: Python is used to create GUI applications, connecting databases, etc. SqlAlchemy is the popular library for connection with databases.
  • Scientific and Numeric applications: Python is used to handle big data and perform complex mathematics. Libraries include Numpy, Pandas, Dask, PySpark, Vaex, Data Table and PyPolars.
  • Education: Python is a great language for teaching programming, both at the introductory level and in more advanced courses.
  • Desktop GUIs: The Tk GUI library included with most binary distributions of Python 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 ecommerce systems.

Comments

Comments are used to annotate codes, and they are not interpreted by Python. Comments in Python starts with the hash character # and end at the end of the code line. A comment may occur at the start of a line, after whitespace or code, but not inside a string literal.

A single-line comments may be looked like below:

# This is a comment in Python.

To represent multi-line comment, # has to be precede before start of 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

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

Arithmetic Operations in Python

To begin with the simplest mathematical operations, such as addition, subtraction, multiplication and division, we can start using the Python Console using the following expressions.

# 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.

To manually specify the order of evaluation, Python allow the use of brackets like this one.

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

print() function

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 - value are separated by sep. Default value: ' ' i.e. values passed in print function will automatically be separated by ' '
  • end - end is printed at last. \n for new-line and \t for tab.
  • file - must be an value with write(string) method. If omitted, sys.stdout will be used which prints value on the screen.
  • flush - If True, the stream is forcibly flushed. Default value: False

Let's look at 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.

1. 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.

2. %-formatting strings

This formatting style is in the language since the very beginning.

Let's run through some examples of single and multiple strings 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.

3. .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 ' and the Python interpreter will get confused as to where the string begins and finishes. As a result, we must indicate that the string does not terminate at 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 if we are 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 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 below example:

>>> 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, there are several other escape sequences 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 beginning 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 are used to establish the indentation level, which in turn 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, as well as for 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

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐