Programming languages are a medium between humans and computers to express computations in an understandable form to both. Programming languages are the most demanded skills today. Learning programming languages significantly improves problem-solving skills.
Like natural languages, programming languages are also governed by grammar, called Syntax and Semantics. The Syntax of a programming language is the set of rules that are allowed to structure a program. The Semantics of a programming language is concerned with the meaning of programs. Every programming language has developed its own rules based on design specifications, which may differ from one to another.
There are trade-offs in designing programming languages, some language features make it easy for developers to write programs quickly but some languages make it easy to compile or optimize programs. With Python language, it is easy and quick to develop programs but is generally slower than other language programs like Java. Even though programmers love Python because of increased productivity and debugging Python programs is easy.
My point is that a program is never a goal itself; the purpose of a program is to evoke computations and the purpose of the computations is to establish a desired effect. - E.W. DIJKSTRA
Python is the most popular and beginner-friendly language and ranked No.1 in the TIOBE rankings as of Apr'23 (https://www.tiobe.com/tiobe-index/).
This article explains basic concepts and syntax with Python programming language.
Introduction
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It was created by Guido van Rossum, and released in 1991. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
Python is widely used in most of the software verticals but predominantly used in developing Web development, Data Science, Machine Learning and Artificial Intelligence applications.
Python Installation
Python interpreter comes pre-bundled with some of the operating systems, but may it comes with older versions, so it is best to use the latest version of Python which is constantly evolving.
To download the latest Python interpreter, download from the link https://www.python.org/downloads/ and install the interpreter based on the choice of your OS.
The standard installation comes with IDLE (Integrated Development and Learning Environment) for quick prototyping. Command line interpreter also can be used, one can type Python/Python3 to get the interpreter. Python files end with a .py extension and can be executed by "Python filename" or "Python3 filename" at the command line.
One can use any other code editor like Microsoft Visual code editor, Atom, Vim or Emacs etc and IDE like Microsoft Visual Studio, Pycharm etc. to write code in Python.
Hello World!
Traditionally, Hello World programs are used to introduce to the coding world as they can be executed easily and correctly even with little or no experience. The below snippet shows the Hello World! program in Python.
# Print Hello World!
print("Hello World!")
# Output
Hello World!
Any statement starting with "#" is a comment and will be ignored by the interpreter.
Syntax of print function is print(\objects, sep=' ', end='\n', file=None, flush=False*). Generally, functions take some arguments and return results, which will be discussed in the later part of the article.
Here concentrating on *objects only, the Print function takes objects as input and gives output to the standard output/screen. We can give multiple values to the print function and gives the output values space-separated.
# Print Multiple values
print(1,2,3)
# Output
1 2 3
# Print String and value
print("Hi", 1)
# Output
Hi 1
Data Types and Variables
Data are the raw material for doing computations. Data is a collection of facts in any form. Data can be numerical or non-numerical. The data type is a set of values and a set of operations defined on those values.
Value is an entity that can be stored, evaluated or manipulated. Programming languages group values into types. Different types of languages support different types of values. The variable is a symbolic name referring to a particular object or memory location.
Objects are Python’s abstraction for data. i.e. they are implemented as objects. type() function gives you the type of data and the id() function gives you the memory address of the data.
Basic data types in Python are Integers, Floating point numbers, Booleans and Strings, which are implemented as classes int, float, bool and str respectively. Integers represent natural numbers, floating point numbers represent real numbers, Booleans represent truth values (True or False) and Strings represent sequences of characters.
# Variable Declarations
number = 1
name = 'naveen'
status = True
gender = 'M'
weight = 76.5
# Printing Variables
print("Number:", number)
print("Name:", name)
print("Status:", status)
print("Gender:", gender)
print("Weight in Kgs:", weight)
# Output
Number: 1
Name: naveen
Status: True
Gender: M
Weight in Kgs: 76.5
# Printing type of Variables
print("Type of Number:",type(number))
print("Type of Name:",type(name))
print("Type of Status:",type(status))
print("Type of Gender:",type(gender))
print("Type of Weight:",type(weight))
# Output
Type of Number: <class 'int'>
Type of Name: <class 'str'>
Type of Status: <class 'bool'>
Type of Gender: <class 'str'>
Type of Weight: <class 'float'>
In the above code number, name, status, gender and weight are identifiers. Identifiers are names which identify variables, constants, functions, classes etc. Identifiers can be sequences of letters, digits and underscores but should not start with a digit. Ex: abc, Ab_, abc123 are legal and 1ab, Ab*, a+b are illegal. Identifiers are case-sensitive so ab, Ab are different.
Every language has reserved keywords for its implementation, so those words cannot be used as identifiers. Keywords in Python are below (https://docs.python.org/3/reference/lexical_analysis.html#keywords)
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
There is no concept of Constants in Python, but in general capital letters are used to denote constants. It is to understand that the variable declared is to be used as a constant.
# Declaring a constant PI
PI = 3.14159265359
As Python is dynamically typed, the type checking happens at the run-time of the program. In dynamically typed, only values have fixed types but variables have no designated type. So variables may take different values at different times. Dynamic typing enhances flexibility but execution may become slower.
Type inference i.e. automatic detection of data type happens in Python, so no need to mention any type to the variable declaration.
# Variable declaration and Printing
name = "Naveen"
print(name)
# Output
Naveen
# Changing value and printing
name = "Kumar"
print(name)
# Output
Kumar
There are other built-in data types Lists, Tuples, Dictionaries and Sets defined in Python. Lists are described below as these are fundamental sequence or container data types which are mostly used everywhere.
Lists are Sequence type. Sequence types represent finite ordered sets indexed by non-negative numbers. Lists are mutable, which means they can be modified after creation. Items of a list can be any object like integers, floats, strings etc. Lists are formed by placing a comma-separated list of expressions in square brackets. Indexing starts from 0 in Python, the maximum value of the index is the number of elements minus 1.
# Variable declaration
names = ['naveen', 'srikanth', 'hari']
ages = [37, 36, 38]
# Printing variables
print(names)
print(ages)
print("First member:", names[0])
print("Age of first member:", age[0])
# Output
['naveen', 'srikanth', 'hari']
[37, 36, 38]
First member: naveen
Age of first member: 37
Python documentation links for data types https://docs.python.org/3/library/stdtypes.html and data structures https://docs.python.org/3/tutorial/datastructures.html for further study.
Operators and Expressions
An expression is a phrase that will be evaluated to yield a value. They are a combination of operators and operands to produce some value.
Operators denote action and Operands indicate the items in an expression. Operands can be Constants, Variables or Functions. Operators are Arithmetic, Assignment, Comparison, Logical, Bitwise, Identity and membership operators.
Below are the Operators in Python with examples.
Arithmetic operators are used to perform mathematical operations on numerical values.
+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus), ** (Exponentiation), // (Floor division)
# Arithmetic Operators
# Variable declaration
x = 10
y = 5
# addition
print ('Addition: ', x + y)
# subtraction
print ('Subtraction: ', x - y)
# multiplication
print ('Multiplication: ', x * y)
# division
print ('Division: ', x / y)
# floor division
print ('Floor Division: ', x // y)
# modulus
print ('Modulus: ', x % y)
# Exponentiation (x to the power y)
print ('Exponentiaton: ', y ** y)
# Output
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Floor Division: 2
Modulus: 0
Exponentiation: 100000
Assignment operators are used to assigning values to variables.
\= (Assignment), += (Addition assignment), -= (Subtraction assignment), = (Multiplication assignment), /= (Division assignment), %= (Modulus assignment), **= (Exponentiation assignment)
# Assigning value 10 to variable a and 5 to variable b
a = 10
b = 5
# Addition assignment
a += b # Same as a = a + b
print("a value after addition assignment:", a)
# Multiplication assignment
a *= b # Same as a = a * b
print("a value after multiplcation assignment:", a)
# Output
a value after addition assignment: 15
a value after multiplcation assignment: 75 # a value changed to 15 after addition assignment
Comparison operators are used to compare two values and give a boolean value as a result.
\== (Equal to), != (Not equal to), > (Greater than), < (Less than), >= (Greater than or equal to), <= (Less than or equal to)
# Variable declaration
x = 10
y = 5
# equal to operator
print('x == y is', x == y)
# not equal to operator
print('x != y is', x != y)
# greater than operator
print('x > y is', x > y)
# less than operator
print('x < y is', x < y)
# Output
x == y is False
x != y is True
x > y is True
x < y is False
Logical operators are used to checking whether the compound expression is True or False.
and (Logical AND), or (Logical OR), not (Logical Not)
# Variable declaration
x = 6
y = 5
print((x > 2) and (y > 3))
print((x > 2) or (y > 5))
print(not (x > 2))
# Output
True
True
False
Bitwise operators are used to comparing binary numbers.
& (Bitwise AND), | (Bitwise OR), ~ (Bitwise NOT), ^ (Bitwise XOR), << (Zero fill Left Shift), >> (Signed Right shift).
bin() function can be used to view the binary representation of a decimal. With bitwise operators, decimal numbers are compared in binary form and give the results in decimal numbers.
# Variable declaration
a = 5
b = 6
# Bitwise Operators
print("Binary representation of a:", bin(a))
print("Binary representation of b:", bin(b))
print("Bitwise AND:", a & b)
print("Bitwise OR:", a | b)
print("Bitwise NOT", ~ a)
print("Bitwise XOR", a ^ b)
print("Left shift by 2 bits:", a<<2)
print("Right shift by 2 bits:", a>>2)
# Output
Binary representation of a: '0b101'
Binary representation of b: '0b110'
Bitwise AND: 4
Bitwise OR: 7
Bitwise NOT: -6
Bitwise XOR: 3
Left shift by 2 bits: 20
Right shift by 2 bits: 1
Identity operators are used to checking whether the objects belong to the same memory or not.
is and is not
# Variable declaration
a = 'Naveen'
b = 'Naveen'
x = 5
y = 6
# Identity checking
print(a is b)
print(x is not y)
print(x is y)
# Output
True
True
False
Membership operators are used to checking whether a value present in a sequence.
in and not in
# Variable declaration
x = 'Hello World'
# Membership checking
print('H' in x)
print('a' not in x)
print('e' not in x)
# Output
True
True
False
Control Flow
Control flow is the ability to control the order in which the code is executed. Statements, Functions determine how control flows from one segment of the program to another. Functions are covered in the next section.
Types of Control Statements in Python are:
Conditional Statements such as if...else, if...elif...else
Iterative Statements such as While and For
Transfer Statements such as Continue, Break and Pass
Structural Pattern Matching such as match...case
One of the guiding principles of Python language is Readability. To achieve readability, white space is used for indentation for blocks of code ( A block is a group of statements ) instead of curly brackets ( {} ) which is predominantly used in other languages for the separation of blocks of code. The usage of white space for indentation is mandatory in Python.
With conditional statements, we can choose from two or more statements based on condition evaluation.
# If syntax
if expression:
Statement 1...n
# If else syntax
if expression:
Statement 1...n
else:
Statement 1...n
# If elif else syntax
if expression:
Statement 1...n
elif expression:
Statement 1...n
else:
Statement 1...n
# If...elif...else example
a = 10
b = 5
if a == b:
print("a and b are Equal")
elif a > b:
print("a is greater than b")
else:
print("a is smaller than b")
# Output
a is greater than b
With Iterative statements ( Loops ), we can repeatedly execute a statement or block of statements.
# While Loop
while expression:
statements 1...n
# For Loop
for item in iterable:
statements 1...n
While Loop is used over an expression or condition, whereas For loop is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable objects.
# While loop example
x = 5
i = 0
while i < x:
print(i)
i = i + 1
# Output
0
1
2
3
4
# For loop example
numbers = [0,1,2,3,4]
for i in numbers:
print(i)
# Output
0
1
2
3
4
With Transfer statements, we can change the way of the execution.
The continue statement continues with the next iteration of the loop.
The break statement breaks out of the enclosing loop.
The pass statement does nothing. It can be used where the program requires no action but is required as per syntax.
# Variable declaration
num = [1,2,3,4]
# Example with Continue
for i in num:
if i == 2:
continue
else:
print(i)
# Output
1
3
4
# Example with break
for i in num:
if i == 3:
break
else:
print(i)
# Output
1
2
# Example with pass
for i in num:
pass
print(num)
# Output
[1,2,3,4]
With pattern-matching statements like match-case, we can check for different matching conditions.
# match case syntax
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
# Example with match case
# Variable declaration
number = 1
match number:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case _:
print("Nothing")
# Output
One
Functions
Functions help in controlling the flow of the program and functions contain expressions to be evaluated and when called will yield the result. Functions set up an input-output relationship. and the same input always produces the same output. Functions are reusable pieces of code and eliminate duplication.
There are two types of functions in Python
Standard Library Functions - These are built into Python language, always available.
User-Defined Functions - Creating own functions for a specific task.
We need to define the function first and then trigger/call the function to get the value after computation.
In Python, User-defined functions begin with the def keyword and may contain a return keyword to return a value. In general, functions take inputs called arguments or parameters.
# Syntax of user defined function
def function_name(arg1, arg2....):
statement 1
statement 2
...........
...........
statement n
return expression # For returning a value, if no value it will return None
In Python, functions behave like any other objects, so functions can be arguments to other functions or can store functions as dictionary values, or return a function from another function.
# Defining a function for Square of a number
def square(x):
return x * x
# Defining a function for Cube of a number
def cube(x):
return x * x * x
# Variable declaration and Calling a function
a = 2
print("Square of", a, "is", square(a))
print("Cube of", a, "after Squaring is", cube(square(a)))
# Output
Square of 2 is 4
Cube of 2 after Squaring is 64
We can give default values to arguments, which will be a basis for computation when no inputs are given.
# Defining a function for Square of a number
def square(x = 2):
return x * x
print("Square function result is", square())
print("Square function result is", square(3))
# Output
Square function result is 4
Square function result is 9
PEP 8 – Style Guide for Python Code (https://peps.python.org/pep-0008/), this document gives coding conventions for the Python code. It suggests that function names should be in lowercase. PEP stands for Python Enhancement Proposals, for better programming guidelines. These documents can be referred to understand the best practices for good programming conventions.
Input and Output
Output:
A basic explanation of output with the print() function is explained at Hello World! section, would like to extend more here.
Syntax of print function is print(\objects, sep=' ', end='\n', file=None, flush=False*)
*objects - values to be printed
sep (optional) - to separate multiple objects inside a print function.
end (optional) - to add specific values like new line, tab space etc ( "\n", "\t")
file (optional) - where the values are printed, the default is Stdout (screen)
flush (optional) - if the output is flushed or buffered, the default is False
# Example with print
print("Morning!")
print("Have a good day.")
# Output
Morning!
Have a good day.
# Example with end parameter
print("Morning!", end=' ')
print("Have a good day.")
# Output
Morning! Have a good day.
# Example with sep parameter
print("Morning!", "Have a good day", sep = ' ')
# Output
Morning! Have a good day.
Input:
Taking inputs is essential for user programs. This can be achieved with the input() function.
The syntax of the input function is input(prompt), If the prompt argument is present, it will be written to standard output without a trailing newline.
# Example for input
name = input("Hi, Enter your name: ")
print("Hello,", name)
# Output
Hi, Enter your name: Naveen # Prompts for data
Hello, Naveen
input function always converts the given data to a string, so be mindful to convert data other than strings to respective types with type casting. In type casting, data loss may occur because we enforce the object to a specific data type.
Zen of Python
The Zen of Python is a collection of 19 "guiding principles" for writing computer programs that influence the design of the Python programming language.
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Thank you for reading, if you like this article, feel free to like and share.