Sitemap

Python Language Basics

6 min readJul 12, 2023

--

Press enter or click to view image in full size
Photo by Rubaitul Azad on Unsplash

Let us explore the overview and essential python programming concepts and language mechanics

Language Semantics

The python language design is distinguished by its emphasis on readability, simplicity, and explicitness.

Indentation, not braces

Python uses whitespaces (tabs or spaces) to structure code instead of using braces as in many other languages like R, C++, Java etc

The colon ‘:’ denotes the start of an indented code block which all of the code must be indented by the same amount until the end of the block.

Everything is an object

  • Every number, string, data structure, function, class, module and so on exists in the python interpreter in its own “box” is referred as an object
  • Each object has an associated type (eg, integer, string, or function)

Comments

Any text preceded by # mark is ignored by python interpreter.

  • Comments can occur before or after the code block, inside the code block and some programmes prefer comments to be placed in the line preceding a particular line of code

Function and object method calls

You call functions using parentheses and passing zero or more arguments.

  • Almost every object in python has attached functions called methods, that have access to the object’s internal contents.

Variable and argument passing

When assigning a variable to an object you’re creating a reference to the object shown on the right hand side of equal sign

In python assignment will not be copied but refers to the same object, for example

When you pass objects as arguments to a function, new local variables are created referencing the original objects without any copying.

If you bind a new object to a variable to a function, that will not overwrite a variable of the same name in the “scope” outside of the function. It is therefore possible to alter the internals of mutable argument

Dynamic reference and strong types

Variables in python have no inherent type associated with them; a variable can be different type of object simply by assignment.

Python is strongly a typed language. These are the languages that do not require any pre-defined data type for any variable as it is interpreted at runtime by the machine itself. In these languages, interpreters assign the data type to a variable at runtime depending on its value. We don’t even need to specify the type of variable that a function is returning or accepting in these languages. JavaScript, Python, Ruby, Perl, etc are examples of dynamically typed languages.

In some languages the string ‘5’ might get implicitly converted (or cast) to an integer, thus yielding 10. In other language the integer 5 might be cast to a string, yielding the concatenated string ‘55’. In python, such implicit casts are not allowed. In this regard python is a strongly typed language

Attributes and methods

  • Attributes: Other python objects “inside” a python object
  • Methods: Functions associated with an object that can have object’s internal data

Attributes and methods can also be accessed by name via getattr() function

Duck Typing

Often you may not care about type of an object but rather only whether it has certain methods or behaviour. This is duck typing
You can verify that an object is iterable if it implements the iterator protocol.

Binary operators and comparisons

Most of the binary math operations and comparisons use familiar mathematical syntax used in other programming languages.

To check if two variables refer to the same object, use is keyword. Use is not to check two objects are not the same

Since the list function always creates a new python list (i.e., a copy), we can be sure c is distinct from a. Comparing with is is not the same as == operator

Mutable and immutable objects

Many objects in python, such as lists, dictionaries, NumPy arrays and mose user defined types (classes) are mutable. This means that the object or the values that they contain may be modified:

Others like strings and tuples are immutable

Scalar Types

Python has a small set of built-in types for handling numerical data, strings, boolean (True or False) values, and dates and time. These single value types are called scaler types

Numeric types

The primary types for numbers are int and float. An int can store arbitrarily large numbers

Floating-point numbers are represented with the Python float type. each one is a double precision value.

Integer division is not yielding in a whole number will always yield a floating-point number

You should use floor division // to get a whole number upon division

Strings

Many people use Python for its built-in string handling capabilities. You can use single quote, double quote to write strings

We can count the new line characters with count method

Strings in Python are immutable, however we can replace a character (item) using replace method

Many python objects can be converted into string using str function

Strings are a sequence of unicode characters and therefore can be treated like another sequence such as lists and tuples

The backlash is an escape character, meaning that it is used to specify special characters like newline ‘\n’ or unicode characters

Get Trinesh’s stories in your inbox

Join Medium for free to get updates from this writer.

Adding two strings concatenates them and produces a new string

String template and formatting is an another important topic, please refer here https://www.geeksforgeeks.org/string-formatting-in-python/

Bytes and Unicode

In modern python (i.e., Python 3.0 and up) Unicode has become the first-class string type enable more consistent handling of ASCII and non-ASCII text.

Booleans

The two boolean values in python are True and False. Comparison or conditional expressions evaluate either True or False. Boolean values are combined with the and and or operator

Type casting

The str, int, and float types are also functions that can be used to cast values to those types

Note that most nonzero values when cast to bool become True

None

None is a python null value type

Dates and times

The built-in python datetime module provides datetime, date and time types. The datetime type combines the information stored in date and time and is the most commonly used

When you are aggregating or grouping time series data, it will occasionally be useful to replace time fields of a series of datetimes — for example replacing minute and seconds with 0

Check here https://www.geeksforgeeks.org/python-datetime-module/ to learn more about Python datetime module

Control Flow

Python has several built-in keywords for conditional logic, loops and other standard control flow concepts found in programming languages

if, elif, and else

The if statement is one of the most well-known control flow statement types. It checks the condition that, if True, evaluates code in the block as follows.

If statement can optionally followed by one or more elif blocks and catchall else block if all of the conditions are False

If any of the conditions are True, no further elif or else blocks will be reached. With a compound condition using and or or, conditions are evaluated left to right and will short-circuit

for loops

for loops are for iterating over a collection (like a list or tuple) or an iterator. The standard syntax for a for loop is

You can advance a for loop to the next iteration. skipping the reminder of the block, using the continue keyword. Consider this code, which sums up integers in a list and skips None values

A for loop can be exited altogether with the break keyword. This code sums elements in the list until 5 is reached

The break keyword only terminates the innermost for loop; any outer for loops will continue to run

While loops

A while loop specifies a condition and a block of code that is to be executed until the condition evaluates to False or the loop is explicitly ended with break

Pass

pass is the “no-op” (or “do nothing”) statement in python. It can be used in blocks where no action is to be takes

Range

The range function generates a sequence of evenly spaced integers

As you can see range produces integers up to but not including endpoint. A common use of range is for iterating through sequences by index

This blog provided only a brief introduction to some basic Python language concepts. For more information kindly refer https://www.python.org/about/gettingstarted/ 🙌

--

--