Category: Basic

  • Type Casting

    Python Type Casting

    From a programming point of view, a type casting refers to converting an object of one type into another. Here, we shall learn about type casting in Python Programming.

    Python Type Casting is a process in which we convert a literal of one data type to another data type. Python supports two types of casting − implicit and explicit.

    In Python there are different data types, such as numbers, sequences, mappings etc. There may be a situation where, you have the available data of one type but you want to use it in another form. For example, the user has input a string but you want to use it as a number. Python’s type casting mechanism let you do that.

    Python Implicit Casting

    When any language compiler/interpreter automatically converts object of one type into other, it is called automatic or implicit casting. Python is a strongly typed language. It doesn’t allow automatic type conversion between unrelated data types. For example, a string cannot be converted to any number type. However, an integer can be cast into a float. Other languages such as JavaScript is a weakly typed language, where an integer is coerced into a string for concatenation.

    Note that memory requirement of each data type is different. For example, an integer object in Python occupies 4 bytes of memory, while a float object needs 8 bytes because of its fractional part. Hence, Python interpreter doesn’t automatically convert a float to int, because it will result in loss of data. On the other hand, int can be easily converted into float by setting its fractional part to 0.

    Implicit int to float casting takes place when any arithmetic operation on int and float operands is done.

    Consider we have an ,int and one float variable

    <<< a=10# int object<<< b=10.5# float object

    To perform their addition, 10 − the integer object is upgraded to 10.0. It is a float, but equivalent to its earlier numeric value. Now we can perform addition of two floats.

    <<< c=a+b
    <<<print(c)20.5

    In implicit type casting, a Python object with lesser byte size is upgraded to match the bigger byte size of other object in the operation. For example, a Boolean object is first upgraded to int and then to float, before the addition with a floating point object. In the following example, we try to add a Boolean object in a float, pleae note that True is equal to 1, and False is equal to 0.

    a=True;
    b=10.5;
    c=a+b;print(c);

    This will produce the following result:

    11.5
    

    Python Explicit Casting

    Although automatic or implicit casting is limited to int to float conversion, you can use Python’s built-in functions int(), float() and str() to perform the explicit conversions such as string to integer.

    Python int() Function

    Python’s built-in int() function converts an integer literal to an integer object, a float to integer, and a string to integer if the string itself has a valid integer literal representation.

    Using int() with an int object as argument is equivalent to declaring an int object directly.

    <<< a =int(10)<<< a
    10

    is same as −

    <<< a =10<<< a
    10<<<type(a)<class 'int>

    If the argument to int() function is a float object or floating point expression, it returns an int object. For example −

    <<< a =int(10.5)#converts a float object to int<<< a
    10<<< a =int(2*3.14)#expression results float, is converted to int<<< a
    6<<<type(a)<class'int'>

    The int() function also returns integer 1 if a Boolean object is given as argument.

    <<< a=int(True)<<< a
    1<<<type(a)<class'int'>

    String to Integer

    The int() function returns an integer from a string object, only if it contains a valid integer representation.

    <<< a =int("100")<<< a
    100<<<type(a)<class'int'><<< a =("10"+"01")<<< a =int("10"+"01")<<< a
    1001<<<type(a)<class'int'>

    However, if the string contains a non-integer representation, Python raises ValueError.

    <<< a =int("10.5")
    Traceback (most recent call last):
       File "<stdin>", line 1,in<module>
    ValueError: invalid literal forint()with base 10:'10.5'<<< a =int("Hello World")
    Traceback (most recent call last):
       File "<stdin>", line 1,in<module>
    ValueError: invalid literal forint()with base 10:'Hello World'

    The int() function also returns integer from binary, octal and hexa-decimal string. For this, the function needs a base parameter which must be 2, 8 or 16 respectively. The string should have a valid binary/octal/Hexa-decimal representation.

    Binary String to Integer

    The string should be made up of 1 and 0 only, and the base should be 2.

    <<< a =int("110011",2)<<< a
    51

    The Decimal equivalent of binary number 110011 is 51.

    Octal String to Integer

    The string should only contain 0 to 7 digits, and the base should be 8.

    <<< a =int("20",8)<<< a
    16

    The Decimal equivalent of octal 20 is 16.

    Hexa-Decimal String to Integer

    The string should contain only the Hexadecimal symbols i.e., 0-9 and A, B, C, D, E or F. Base should be 16.

    <<< a =int("2A9",16)<<< a
    681

    Decimal equivalent of Hexadecimal 2A9 is 681. You can easily verify these conversions with calculator app in Windows, Ubuntu or Smartphones.

    Following is an example to convert number, float and string into integer data type:

    a =int(1)# a will be 1
    b =int(2.2)# b will be 2
    c =int("3")# c will be 3print(a)print(b)print(c)

    This produce the following result −

    1
    2
    3

    Python float() Function

    The float() is a built-in function in Python. It returns a float object if the argument is a float literal, integer or a string with valid floating point representation.

    Using float() with an float object as argument is equivalent to declaring a float object directly

    <<< a =float(9.99)<<< a
    9.99<<<type(a)<class'float'>

    is same as −

    <<< a =9.99<<< a
    9.99<<<type(a)<class'float'>

    If the argument to float() function is an integer, the returned value is a floating point with fractional part set to 0.

    <<< a =float(100)<<< a
    100.0<<<type(a)<class'float'>

    The float() function returns float object from a string, if the string contains a valid floating point number, otherwise ValueError is raised.

    <<< a =float("9.99")<<< a
    9.99<<<type(a)<class'float'><<< a =float("1,234.50")
    Traceback (most recent call last):
       File "<stdin>", line 1,in<module>
    ValueError: could not convert string to float:'1,234.50'

    The reason of ValueError here is the presence of comma in the string.

    For the purpose of string to float conversion, the sceientific notation of floating point is also considered valid.

    <<< a =float("1.00E4")<<< a
    10000.0<<<type(a)<class'float'><<< a =float("1.00E-4")<<< a
    0.0001<<<type(a)<class'float'>

    Following is an example to convert number, float and string into float data type:

    a =float(1)# a will be 1.0
    b =float(2.2)# b will be 2.2
    c =float("3.3")# c will be 3.3print(a)print(b)print(c)

    This produce the following result −

    1.0
    2.2
    3.3
    

    Python str() Function

    We saw how a Python obtains integer or float number from corresponding string representation. The str() function works the opposite. It surrounds an integer or a float object with quotes (‘) to return a str object. The str() function returns the string representation of any Python object. In this section, we shall see different examples of str() function in Python.

    The str() function has three parameters. First required parameter (or argument) is the object whose string representation we want. Other two operators, encoding and errors, are optional.

    We shall execute str() function in Python console to easily verify that the returned object is a string, with the enclosing quotation marks (‘).

    Integer to string

    You can convert any integer number into a string as follows:

    <<< a =str(10)<<< a
    '10'<<<type(a)<class'str'>

    Float to String

    str() function converts floating point objects with both the notations of floating point, standard notation with a decimal point separating integer and fractional part, and the scientific notation to string object.

    <<< a=str(11.10)<<< a
    '11.1'<<<type(a)<class'str'><<< a =str(2/5)<<< a
    '0.4'<<<type(a)<class'str'>

    In the second case, a division expression is given as argument to str() function. Note that the expression is evaluated first and then result is converted to string.

    Floating points in scientific notations using E or e and with positive or negative power are converted to string with str() function.

    <<< a=str(10E4)<<< a
    '100000.0'<<<type(a)<class'str'><<< a=str(1.23e-4)<<< a
    '0.000123'<<<type(a)<class'str'>

    When Boolean constant is entered as argument, it is surrounded by (‘) so that True becomes ‘True’. List and Tuple objects can also be given argument to str() function. The resultant string is the list/tuple surrounded by (‘).

    <<< a=str('True')<<< a
    'True'<<< a=str([1,2,3])<<< a
    '[1, 2, 3]'<<< a=str((1,2,3))<<< a
    '(1, 2, 3)'<<< a=str({1:100,2:200,3:300})<<< a
    '{1: 100, 2: 200, 3: 300}'

    Following is an example to convert number, float and string into string data type:

    a =str(1)# a will be "1"
    b =str(2.2)# b will be "2.2"
    c =str("3.3")# c will be "3.3"print(a)print(b)print(c)

    This produce the following result −

    1
    2.2
    3.3
    

    Conversion of Sequence Types

    List, Tuple and String are Python’s sequence types. They are ordered or indexed collection of items.

    A string and tuple can be converted into a list object by using the list() function. Similarly, the tuple() function converts a string or list to a tuple.

    We shall take an object each of these three sequence types and study their inter-conversion.

    <<< a=[1,2,3,4,5]# List Object<<< b=(1,2,3,4,5)# Tupple Object<<< c="Hello"# String Object### list() separates each character in the string and builds the list<<< obj=list(c)<<< obj
    ['H','e','l','l','o']### The parentheses of tuple are replaced by square brackets<<< obj=list(b)<<< obj
    [1,2,3,4,5]### tuple() separates each character from string and builds a tuple of characters<<< obj=tuple(c)<<< obj
    ('H','e','l','l','o')### square brackets of list are replaced by parentheses.<<< obj=tuple(a)<<< obj
    (1,2,3,4,5)### str() function puts the list and tuple inside the quote symbols.<<< obj=str(a)<<< obj
    '[1, 2, 3, 4, 5]'<<< obj=str(b)<<< obj
    '(1, 2, 3, 4, 5)'

    Thus Python’s explicit type casting feature allows conversion of one data type to other with the help of its built-in functions.

    Data Type Conversion Functions

    There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

    Sr.No.Function & Description
    1Python int() functionConverts x to an integer. base specifies the base if x is a string.
    2Python long() functionConverts x to a long integer. base specifies the base if x is a string.
    3Python float() functionConverts x to a floating-point number.
    4Python complex() functionCreates a complex number.
    5Python str() functionConverts object x to a string representation.
    6Python repr() functionConverts object x to an expression string.
    7Python eval() functionEvaluates a string and returns an object.
    8Python tuple() functionConverts s to a tuple.
    9Python list() functionConverts s to a list.
    10Python set() functionConverts s to a set.
    11Python dict() functionCreates a dictionary. d must be a sequence of (key,value) tuples.
    12Python frozenset() functionConverts s to a frozen set.
    13Python chr() functionConverts an integer to a character.
    14Python unichr() functionConverts an integer to a Unicode character.
    15Python ord() functionConverts a single character to its integer value.
    16Python hex() functionConverts an integer to a hexadecimal string.
    17Python oct() functionConverts an integer to an octal string.
  • Data Types

    Python Data Types

    Python data types are actually classes, and the defined variables are their instances or objects. Since Python is dynamically typed, the data type of a variable is determined at runtime based on the assigned value.

    In general, the data types are used to define the type of a variable. It represents the type of data we are going to store in a variable and determines what operations can be done on it.

    Each programming language has its own classification of data items.With these datatypes, we can store different types of data values.

    Types of Data Types in Python

    Python supports the following built-in data types −

    data_types

    1. Python Numeric Data Types

    Python numeric data types store numeric values. Number objects are created when you assign a value to them. For example −

    var1 =1# int data type
    var2 =True# bool data type
    var3 =10.023# float data type
    var4 =10+3j# complex data type

    Python supports four different numerical types and each of them have built-in classes in Python library, called int, bool, float and complex respectively −

    • int (signed integers)
    • float (floating point real values)
    • complex (complex numbers)

    A complex number is made up of two parts – real and imaginary. They are separated by ‘+’ or ‘-‘ signs. The imaginary part is suffixed by ‘j’ which is the imaginary number. The square root of -1 (&bsol;sqrt{-1}), is defined as imaginary number. Complex number in Python is represented as x+yj, where x is the real part, and y is the imaginary part. So, 5+6j is a complex number.

    >>>type(5+6j)<class'complex'>

    Here are some examples of numbers −

    intfloatcomplex
    100.03.14j
    0O77715.2045.j
    -786-21.99.322e-36j
    08032.3+e18.876j
    0x17-90.-.6545+0J
    -0x260-32.54e1003e+26J
    0x6970.2-E124.53e-7j

    Example of Numeric Data Types

    Following is an example to show the usage of Integer, Float and Complex numbers:

    # integer variable.
    a=100print("The type of variable having value", a," is ",type(a))# float variable.
    c=20.345print("The type of variable having value", c," is ",type(c))# complex variable.
    d=10+3jprint("The type of variable having value", d," is ",type(d))

    2. Python String Data Type

    Python string is a sequence of one or more Unicode characters, enclosed in single, double or triple quotation marks (also called inverted commas). Python strings are immutable which means when you perform an operation on strings, you always produce a new string object of the same type, rather than mutating an existing string.

    As long as the same sequence of characters is enclosed, single or double or triple quotes don’t matter. Hence, following string representations are equivalent.

    >>>'TutorialsPoint''TutorialsPoint'>>>"TutorialsPoint"'TutorialsPoint'>>>'''TutorialsPoint''''TutorialsPoint'

    A string in Python is an object of str class. It can be verified with type() function.

    >>>type("Welcome To TutorialsPoint")<class'str'>

    A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on it. However, operations such as slicing and concatenation can be done. Python’s str class defines a number of useful methods for string processing. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

    The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in Python.

    Example of String Data Type

    str='Hello World!'print(str)# Prints complete stringprint(str[0])# Prints first character of the stringprint(str[2:5])# Prints characters starting from 3rd to 5thprint(str[2:])# Prints string starting from 3rd characterprint(str*2)# Prints string two timesprint(str+"TEST")# Prints concatenated string

    This will produce the following result −

    Hello World!
    H
    llo
    llo World!
    Hello World!Hello World!
    Hello World!TEST
    

    3. Python Sequence Data Types

    Sequence is a collection data type. It is an ordered collection of items. Items in the sequence have a positional index starting with 0. It is conceptually similar to an array in C or C++. There are following three sequence data types defined in Python.

    • List Data Type
    • Tuple Data Type
    • Range Data Type

    Python sequences are bounded and iterable – Whenever we say an iterable in Python, it means a sequence data type (for example, a list).

    (a) Python List Data Type

    Python Lists are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where as C array can store elements related to a particular data type.

    >>>[2023,"Python",3.11,5+6j,1.23E-4]

    A list in Python is an object of list class. We can check it with type() function.

    >>>type([2023,"Python",3.11,5+6j,1.23E-4])<class'list'>

    As mentioned, an item in the list may be of any data type. It means that a list object can also be an item in another list. In that case, it becomes a nested list.

    >>>[['One','Two','Three'],[1,2,3],[1.0,2.0,3.0]]

    A list can have items which are simple numbers, strings, tuple, dictionary, set or object of user defined class also.

    The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

    Example of List Data Type

    list=['abcd',786,2.23,'john',70.2]
    tinylist =[123,'john']print(list)# Prints complete listprint(list[0])# Prints first element of the listprint(list[1:3])# Prints elements starting from 2nd till 3rd print(list[2:])# Prints elements starting from 3rd elementprint(tinylist *2)# Prints list two timesprint(list+ tinylist)# Prints concatenated lists

    This produce the following result −

    ['abcd', 786, 2.23, 'john', 70.2]
    abcd
    [786, 2.23]
    [2.23, 'john', 70.2]
    [123, 'john', 123, 'john']
    ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
    

    (b) Python Tuple Data Type

    Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses (…).

    A tuple is also a sequence, hence each item in the tuple has an index referring to its position in the collection. The index starts from 0.

    >>>(2023,"Python",3.11,5+6j,1.23E-4)

    In Python, a tuple is an object of tuple class. We can check it with the type() function.

    >>>type((2023,"Python",3.11,5+6j,1.23E-4))<class'tuple'>

    As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other Python class.

    >>>(['One','Two','Three'],1,2.0,3,(1.0,2.0,3.0))

    To form a tuple, use of parentheses is optional. Data items separated by comma without any enclosing symbols are treated as a tuple by default.

    
    
  • Variables

    Python Variables

    Python variables are the reserved memory locations used to store values with in a Python Program. This means that when you create a variable you reserve some space in the memory.

    Based on the data type of a variable, memory space is allocated to it. Therefore, by assigning different data types to Python variables, you can store integers, decimals or characters in these variables.

    Memory Addresses

    Data items belonging to different data types are stored in computer’s memory. Computer’s memory locations are having a number or address, internally represented in binary form. Data is also stored in binary form as the computer works on the principle of binary representation. In the following diagram, a string May and a number 18 is shown as stored in memory locations.

    memory

    If you know the assembly language, you will covert these data items and the memory address, and give a machine language instruction. However, it is not easy for everybody. Language translator such as Python interpreter performs this type of conversion. It stores the object in a randomly chosen memory location. Python’s built-in id() function returns the address where the object is stored.

    >>>"May"
    May
    >>>id("May")2167264641264>>>1818>>>id(18)140714055169352

    Once the data is stored in the memory, it should be accessed repeatedly for performing a certain process. Obviously, fetching the data from its ID is cumbersome. High level languages like Python make it possible to give a suitable alias or a label to refer to the memory location.

    In the above example, let us label the location of May as month, and location in which 18 is stored as age. Python uses the assignment operator (=) to bind an object with the label.

    >>> month="May">>> age=18

    The data object (May) and its name (month) have the same id(). The id() of 18 and age are also same.

    >>>id(month)2167264641264>>>id(age)140714055169352

    The label is an identifier. It is usually called as a variable. A Python variable is a symbolic name that is a reference or pointer to an object.

    Creating Python Variables

    Python variables do not need explicit declaration to reserve memory space or you can say to create a variable. A Python variable is created automatically when you assign a value to it. The equal sign (=) is used to assign values to variables.

    The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example −

    Example to Create Python Variables

    This example creates different types (an integer, a float, and a string) of variables.

    counter =100# Creates an integer variable
    miles   =1000.0# Creates a floating point variable
    name    ="Zara Ali"# Creates a string variable

    Printing Python Variables

    Once we create a Python variable and assign a value to it, we can print it using print() function. Following is the extension of previous example and shows how to print different variables in Python:

    Example to Print Python Variables

    This example prints variables.

    counter =100# Creates an integer variable
    miles   =1000.0# Creates a floating point variable
    name    ="Zara Ali"# Creates a string variableprint(counter)print(miles)print(name)

    Here, 100, 1000.0 and “Zara Ali” are the values assigned to countermiles, and name variables, respectively. When running the above Python program, this produces the following result −

    100
    1000.0
    Zara Ali
    

    Deleting Python Variables

    You can delete the reference to a number object by using the del statement. The syntax of the del statement is −

    del var1[,var2[,var3[....,varN]]]]

    You can delete a single object or multiple objects by using the del statement. For example −

    del var
    del var_a, var_b
    

    Example

    Following examples shows how we can delete a variable and if we try to use a deleted variable then Python interpreter will throw an error:

    counter =100print(counter)del counter
    print(counter)

    This will produce the following result:

    100
    Traceback (most recent call last):
      File "main.py", line 7, in <module>
    
    print (counter)
    NameError: name 'counter' is not defined
  • Syntax

    The Python syntax defines a set of rules that are used to create a Python Program. The Python Programming Language Syntax has many similarities to Perl, C, and Java Programming Languages. However, there are some definite differences between the languages.

    First Python Program

    Let us execute a Python program to print “Hello, World!” in two different modes of Python Programming. (a) Interactive Mode Programming (b) Script Mode Programming.

    Python – Interactive Mode Programming

    We can invoke a Python interpreter from command line by typing python at the command prompt as following −

    $ python3
    Python 3.10.6(main, Mar 102023,10:55:28)[GCC 11.3.0] on linux
    Type "help","copyright","credits"or"license"for more information.>>>

    Here >>> denotes a Python Command Prompt where you can type your commands. Let’s type the following text at the Python prompt and press the Enter −

    >>>print("Hello, World!")

    If you are running older version of Python, like Python 2.4.x, then you would need to use print statement without parenthesis as in print “Hello, World!”. However in Python version 3.x, this produces the following result −

    Hello, World!
    

    Python – Script Mode Programming

    We can invoke the Python interpreter with a script parameter which begins the execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.

    Let us write a simple Python program in a script which is simple text file. Python files have extension .py. Type the following source code in a test.py file −

    print (“Hello, World!”)

    We assume that you have Python interpreter path set in PATH variable. Now, let’s try to run this program as follows −

    $ python3 test.py
    

    This produces the following result −

    Hello, World!
    

    Let us try another way to execute a Python script. Here is the modified test.py file −

    Open Compiler

    #!/usr/bin/python3print("Hello, World!")

    We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −

    $ chmod +x test.py     # This is to make file executable
    $./test.py
    

    This produces the following result −

    Hello, World!
    

    Python Identifiers

    A Python identifier is a name used to identify a variablefunctionclassmodule or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

    Python does not allow punctuation characters such as &commat;, $, and % within identifiers.

    Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

    Here are naming conventions for Python identifiers −

    • Python Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
    • Starting an identifier with a single leading underscore indicates that the identifier is private identifier.
    • Starting an identifier with two leading underscores indicates a strongly private identifier.
    • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

    Python Reserved Words

    The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

    andasassert
    breakclasscontinue
    defdelelif
    elseexceptFalse
    finallyforfrom
    globalifimport
    inislambda
    Nonenonlocalnot
    orpassraise
    returnTruetry
    whilewithyield

    Python Lines and Indentation

    Python programming provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

    The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −

    ifTrue:print("True")else:print("False")

    However, the following block generates an error −

    ifTrue:print("Answer")print("True")else:print("Answer")print("False")

    Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −

    Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.

    import sys
    
    try:# open file streamfile=open(file_name,"w")except IOError:print"There was an error writing to", file_name
       sys.exit()print"Enter '", file_finish,print"' When finished"while file_text != file_finish:
       file_text =raw_input("Enter text: ")if file_text == file_finish:# close the filefile.close
    
      breakfile.write(file_text)file.write("\n")file.close()
    file_name =raw_input("Enter filename: ")iflen(file_name)==0:print"Next time please enter something" sys.exit()try:file=open(file_name,"r")except IOError:print"There was an error reading file" sys.exit() file_text =file.read()file.close()print file_text

    Python Multi-Line Statements

    Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example −

    total = item_one + \
    
        item_two + \
        item_three

    Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example following statement works well in Python −

    days =['Monday','Tuesday','Wednesday','Thursday','Friday']

    Quotations in Python

    Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string.

    The triple quotes are used to span the string across multiple lines. For example, all the following are legal −

    word ='word'print(word)
    
    sentence ="This is a sentence."print(sentence)
    
    paragraph ="""This is a paragraph. It is
     made up of multiple lines and sentences."""print(paragraph)

    Comments in Python

    A comment is a programmer-readable explanation or annotation in the Python source code. They are added with the purpose of making the source code easier for humans to understand, and are ignored by Python interpreter

    Just like most modern languages, Python supports single-line (or end-of-line) and multi-line (block) comments. Python comments are very much similar to the comments available in PHP, BASH and Perl Programming languages.

    A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

    # First commentprint("Hello, World!")# Second comment

    This produces the following result −

    Hello, World!
    

    You can type a comment on the same line after a statement or expression −

    name ="Madisetti"# This is again comment

    You can comment multiple lines as follows −

    # This is a comment.# This is a comment, too.# This is a comment, too.# I said that already.

    Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments:

    '''
    This is a multiline
    comment.
    '''

    Using Blank Lines in Python Programs

    A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

    In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.

    Waiting for the User

    The following line of the program displays the prompt, the statement saying Press the enter key to exit, and waits for the user to take action −

    #!/usr/bin/pythonraw_input("\n\nPress the enter key to exit.")

    Here, “\n\n” is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.

    Multiple Statements on a Single Line

    The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −

    import sys; x ='foo'; sys.stdout.write(x +'\n')

    Multiple Statement Groups as Suites

    A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.

    Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example −

    if expression :
       suite
    elif expression :
       suite
    else:
       suite
    

    Command Line Arguments in Python

    Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h −

    $ python3 -h
    usage: python3 [option]...[-c cmd |-m mod |file|-][arg]...
    Options and arguments (and corresponding environment variables):-c cmd : program passed inas string (terminates option list)-d     : debug output from parser (also PYTHONDEBUG=x)-E     : ignore environment variables (such as PYTHONPATH)-h     :print this help message and exit
    
    [ etc.]

    You can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced topic and should be studied a bit later once you have gone through rest of the Python concepts.

  • Virtual Environment

    Python virtual environments create a virtual installation of Python inside a project directory. Users can then install and manage Python packages for each project. This allows users to be able to install packages and modify their Python environment without fear of breaking packages installed in other environments.

    What is Virtual Environment in Python?

    A Python virtual environment is:

    • Considered as disposable.
    • Used to contain a specific Python interpreter and software libraries and binaries which are needed to support a project.
    • Contained in a directory, conventionally either named venv or .venv in the project directory.
    • Not considered as movable or copyable.

    When you install Python software on your computer, it is available for use from anywhere in the filesystem. This is a system-wide installation.

    While developing an application in Python, one or more libraries may be required to be installed using the pip utility (e.g., pip3 install somelib). Moreover, an application (let us say App1) may require a particular version of the library − say somelib 1.0. At the same time another Python application (for example App2) may require newer version of same library say somelib 2.0. Hence by installing a new version, the functionality of App1 may be compromised because of conflict between two different versions of same library.

    This conflict can be avoided by providing two isolated environments of Python in the same machine. These are called virtual environment. A virtual environment is a separate directory structure containing isolated installation having a local copy of Python interpreter, standard library and other modules.

    The following figure shows the purpose of advantage of using virtual environment. Using the global Python installation, more than one virtual environments are created, each having different version of the same library, so that conflict is avoided.

    python virtual environment

    Creation of Virtual Environments in Python using venv

    This functionality is supported by venv module in standard Python distribution. Use following commands to create a new virtual environment.

    C:\Users\Acer>md\pythonapp
    C:\Users\Acer>cd\pythonapp
    C:\pythonapp>python -m venv myvenv
    

    Here, myvenv is the folder in which a new Python virtual environment will be created showing following directory structure −

    Directory of C:\pythonapp\myvenv
    22-02-202309:53<DIR>.22-02-202309:53<DIR>..22-02-202309:53<DIR> Include
    22-02-202309:53<DIR> Lib
    22-02-202309:5377 pyvenv.cfg
    22-02-202309:53<DIR> Scripts
    

    The utilities for activating and deactivating the virtual environment as well as the local copy of Python interpreter will be placed in the scripts folder.

    Directory of C:\pythonapp\myvenv\scripts
    22-02-202309:53<DIR>.22-02-202309:53<DIR>..22-02-202309:532,063 activate
    22-02-202309:53992 activate.bat
    22-02-202309:5319,611 Activate.ps1
    22-02-202309:53393 deactivate.bat
    22-02-202309:53106,349 pip.exe
    22-02-202309:53106,349 pip3.10.exe
    22-02-202309:53106,349 pip3.exe
    22-02-202309:53242,408 python.exe
    22-02-202309:53232,688 pythonw.exe
    

    Activating Virtual Environment

    To enable this new virtual environment, execute activate.bat in Scripts folder.

    C:\pythonapp>myvenv\scripts\activate
    (myvenv) C:\pythonapp>

    Note the name of the virtual environment in the parentheses. The Scripts folder contains a local copy of Python interpreter. You can start a Python session in this virtual environment.

    Checking If Python is Running Inside a Virtual Environment?

    To confirm whether this Python session is in virtual environment check the sys.path.

    (myvenv) C:\pythonapp>python
    Python 3.10.1(tags/v3.10.1:2cd268a, Dec 62021,19:10:37)[MSC v.192964 bit (AMD64)] on win32
    Type "help","copyright","credits"or"license"for more information.>>>import sys
    >>> sys.path
    ['','C:\\Python310\\python310.zip','C:\\Python310\\DLLs','C:\\Python310\\lib','C:\\Python310','C:\\pythonapp\\myvenv','C:\\pythonapp\\myvenv\\lib\\site-packages']>>>

    The scripts folder of this virtual environment also contains pip utilities. If you install a package from PyPI, that package will be active only in current virtual environment.

    Deactivating Virtual Environment

    To deactivate this environment, run deactivate.bat.

  • Environment Setup

    First step in the journey of learning Python is to install it on your machine. Today most computer machines, especially having Linux OS, have Python pre-installed. However, it may not be the latest version.

    Python is available on a wide variety of platforms including Linux and Mac OS X. Let’s understand how to set up our Python environment.

    • Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)
    • Win 9x/NT/2000
    • Macintosh (Intel, PPC, 68K)
    • OS/2
    • DOS (multiple versions)
    • PalmOS
    • Nokia mobile phones
    • Windows CE
    • Acorn/RISC OS
    • BeOS
    • Amiga
    • VMS/OpenVMS
    • QNX
    • VxWorks
    • Psion

    Python has also been ported to the Java and .NET virtual machines

    Local Environment Setup

    Open a terminal window and type “python” to find out if it is already installed and which version is installed. If Python is already installed then you will get a message something like as follows:

    $ python
    Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.

    >>>
    Downloading Python
    The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/

    You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats.

    Installing Python
    Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.

    If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.

    Here is a quick overview of installing Python on various platforms −

    Install Python on Ubuntu Linux
    To check whether Python is already installed, open the Linux terminal and enter the following command −

    $ python3.11 --version
    In Ubuntu Linux, the easiest way to install Python is to use apt Advanced Packaging Tool. It is always recommended to update the list of packages in all the configured repositories.

    $ sudo apt update
    Even after the update, the latest version of Python may not be available for install, depending upon the version of Ubuntu you are using. To overcome this, add the deadsnakes repository.

    $ sudo apt-get install software-properties-common
    $ sudo add-apt-repository ppa:deadsnakes/ppa
    Update the package list again.

    $ sudo apt update
    To install the latest Python 3.11 version, enter the following command in the terminal −

    $ sudo apt-get install python3.11
    Check whether it has been properly installed.

    $ python3
    Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.

    >>> print ("Hello World")
    Hello World

    >>>
    Install Python on other Linux
    Here are the simple steps to install Python on Unix/Linux machine.

    Open a Web browser and go to https://www.python.org/downloads/.

    Follow the link to download zipped source code available for Unix/Linux.

    Download and extract files.

    Editing the Modules/Setup file if you want to customize some options.

    Now issue the following commands:

    $ run ./configure script
    $ make
    $ make install
    This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.

    Using Yum Command
    Red Hat Enterprise Linux (RHEL 8) does not install Python 3 by default. We usually use yum command on CentOS and other related variants. The procedure for installing Python-3 on RHEL 8 is as follows:

    $ sudo yum install python3
    Install Python on Windows
    It should be noted that Python's version 3.10 onwards cannot be installed on Windows 7 or earlier operating systems.

    The recommended way to install Python is to use the official installer. A link to the latest stable version is given on the home page itself. It is also found at https://www.python.org/downloads/windows/.

    You can find embeddable packages and installers for 32 as well as 64-bit architecture.

  • Interpreter and Its Modes

    Python Interpreter

    Python is an interpreter-based language. In a Linux system, Python’s executable is installed in /usr/bin/ directory. For Windows, the executable (python.exe) is found in the installation folder (for example C:\python311).

    This tutorial will teach you How Python Interpreter Works in interactive and scripted mode. Python code is executed by one statement at a time method. Python interpreter has two components. The translator checks the statement for syntax. If found correct, it generates an intermediate byte code. There is a Python virtual machine which then converts the byte code in native binary and executes it. The following diagram illustrates the mechanism:

    Python Interpreter

    Python interpreter has an interactive mode and a scripted mode.

    Python Interpreter – Interactive Mode

    When launched from a command line terminal without any additional options, a Python prompt >>> appears and the Python interpreter works on the principle of REPL (Read, Evaluate, Print, Loop). Each command entered in front of the Python prompt is read, translated and executed. A typical interactive session is as follows.

    >>> price =100>>> qty =5>>> total = price*qty
    >>> total
    500>>>print("Total = ", total)
    Total =500

    To close the interactive session, enter the end-of-line character (ctrl+D for Linux and ctrl+Z for Windows). You may also type quit() in front of the Python prompt and press Enter to return to the OS prompt.

    >>> quit()
    
    $
    

    The interactive shell available with standard Python distribution is not equipped with features like line editing, history search, auto-completion etc. You can use other advanced interactive interpreter software such as IPython and bpython to have additional functionalities.

    Python Interpreter – Scripting Mode

    Instead of entering and obtaining the result of one instruction at a time as in the interactive environment, it is possible to save a set of instructions in a text file, make sure that it has .py extension, and use the name as the command line parameter for Python command.

    Save the following lines as prog.py, with the use of any text editor such as vim on Linux or Notepad on Windows.

    print (“My first program”) price = 100 qty = 5 total = price*qty print (“Total = “, total)

    When we execute above program on a Windows machine, it will produce following result:

    C:\Users\Acer>python prog.py
    My first program
    Total = 500
    

    Note that even though Python executes the entire script in one go, but internally it is still executed in line by line fashion.

    In case of any compiler-based language such as Java, the source code is not converted in byte code unless the entire code is error-free. In Python, on the other hand, statements are executed until first occurrence of error is encountered.

    Let us introduce an error purposefully in the above code.

    print("My first program")
    price =100
    qty =5
    total = prive*qty #Error in this statementprint("Total = ", total)

    Note the misspelt variable prive instead of price. Try to execute the script again as before −

    C:\Users\Acer>python prog.py
    My first program
    Traceback (most recent call last):
      File "C:\Python311\prog.py", line 4, in <module>
       total = prive*qty
       ^^^^^
    NameError: name 'prive' is not defined. Did you mean: 'price'?
    

    Note that the statements before the erroneous statement are executed and then the error message appears. Thus it is now clear that Python script is executed in interpreted manner.

    Python Interpreter – Using Shebang #!

    In addition to executing the Python script as above, the script itself can be a selfexecutable in Linux, like a shell script. You have to add a shebang line on top of the script. The shebang indicates which executable is used to interpret Python statements in the script. Very first line of the script starts with #! And followed by the path to Python executable.

    Modify the prog.py script as follows −

    #! /usr/bin/python3.11print("My first program")
    price =100
    qty =5
    total = price*qty
    print("Total = ", total)

    To mark the script as self-executable, use the chmod command

    $ chmod +x prog.py
    

    You can now execute the script directly, without using it as a command-line argument.

    $ ./hello.py
    

    Interactive Python – IPython

    IPython (stands for Interactive Python) is an enhanced and powerful interactive environment for Python with many functionalities compared to the standard Python shell. IPython was originally developed by Fernando Perez in 2001.

    IPython has the following important features −

    • IPython‘s object introspection ability to check properties of an object during runtime.
    • Its syntax highlighting proves to be useful in identifying the language elements such as keywords, variables etc.
    • The history of interactions is internally stored and can be reproduced.
    • Tab completion of keywords, variables and function names is one of the most important features.
    • IPython’s Magic command system is useful for controlling Python environment and performing OS tasks.
    • It is the main kernel for Jupyter notebook and other front-end tools of Project Jupyter.

    Install IPython with PIP installer utility.

    pip3 install ipython
    

    Launch IPython from command-line

    C:\Users\Acer>ipython
    Python 3.11.2(tags/v3.11.2:878ead1, Feb 72023,16:38:35)[MSC v.193464 bit (AMD64)] on win32
    Type 'copyright','credits'or'license'for more information
    IPython 8.4.0-- An enhanced Interactive Python. Type '?'forhelp.
    In [1]:

    Instead of the regular >>> prompt as in standard interpreter, you will notice two major IPython prompts as explained below −

    • In[1] appears before any input expression.
    • Out[1]appears before the Output appears.
  • Application Areas

    Python is a general-purpose programming language. It is suitable for the development of a wide range of software applications. Over the last few years Python has been the preferred language of choice for developers in the following application areas −

    Let’s look into these application areas in more detail:

    Data Science

    Python’s recent meteoric rise in the popularity charts is largely due to its Data science libraries. Python has become an essential skill for data scientists. Today, real time web applications, mobile applications and other devices generate huge amount of data. Python’s data science libraries help companies generate business insights from this data.

    Libraries like NumPyPandas, and Matplotlib are extensively used to apply mathematical algorithms to the data and generate visualizations. Commercial and community Python distributions like Anaconda and ActiveState bundle all the essential libraries required for data science.

    Machine Learning

    Python libraries such as Scikit-learn and TensorFlow help in building models for prediction of trends like customer satisfaction, projected values of stocks etc. based upon the past data. Machine learning applications include (but not restricted to) medical diagnosis, statistical arbitrage, basket analysis, sales prediction etc.

    Web Development

    Python’s web frameworks facilitate rapid web application development. DjangoPyramidFlask are very popular among the web developer community. etc. make it very easy to develop and deploy simple as well as complex web applications.

    Latest versions of Python provide asynchronous programming support. Modern web frameworks leverage this feature to develop fast and high performance web apps and APIs.

    Computer Vision and Image processing

    OpenCV is a widely popular library for capturing and processing images. Image processing algorithms extract information from images, reconstruct image and video data. Computer Vision uses image processing for face detection and pattern recognition. OpenCV is a C++ library. Its Python port is extensively used because of its rapid development feature.

    Some of the application areas of computer vision are robotics, industrial surveillance, automation, and biometrics etc.

    Embedded Systems and IoT

    Micropython (https://micropython.org/), a lightweight version especially for microcontrollers like Arduino. Many automation products, robotics, IoT, and kiosk applications are built around Arduino and programmed with Micropython. Raspberry Pi is also very popular alow cost single board computer used for these type of applications.

    Job Scheduling and Automation

    Python found one of its first applications in automating CRON (Command Run ON) jobs. Certain tasks like periodic data backups, can be written in Python scripts scheduled to be invoked automatically by operating system scheduler.

    Many software products like Maya embed Python API for writing automation scripts (something similar to Excel micros).

    Desktop GUI Applications

    Python is a great option for building ergonomic, attractive, and user-friendly desktop GUI applications. Several graphics libraries, though built in C/C++, have been ported to Python. The popular Qt graphics toolkit is available as a PyQt package in Python. Similarly, WxWidgets has been ported to Python as WxPython. Python’s built-in GUI package, TKinter is a Python interface to the Tk Graphics toolkit.

    Here is a select list of Python GUI libraries:

    • Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python’s standard library.
    • wxPython − This is the Python interface for the wxWidgets GUI toolkit. BitTorrent Client application has been built with wxPython functionality.
    • PyQt – Qt is one of the most popular GUI toolkits. It has been ported to Python as a PyQt5 package. Notable desktop GUI apps that use PyQt include QGIS, Spyder IDE, Calibre Ebook Manager, etc.
    • PyGTK − PyGTK is a set of wrappers written in Python and C for GTK + GUI library. The complete PyGTK tutorial is available here.
    • PySimpleGUI − PySimpleGui is an open-source, cross-platform GUI library for Python. It aims to provide a uniform API for creating desktop GUIs based on Python’s Tkinter, PySide, and WxPython toolkits.
    • Jython − Jython is a Python port for Java, which gives Python scripts seamless access to the Java GUI libraries on the local machine.

    Console-based Applications

    Python is often employed to build CLI (command-line interface) applications. Such scripts can be used to run scheduled CRON jobs such as taking database backups etc. There are many Python libraries that parse the command line arguments. The argparse library comes bundled with Pythons standard library. You can use Click (part of Flask framework) and Typer (included in FastAPI framework) to build console interfaces to the web-based applications built by the respective frameworks. Textual is a rapid development framework to build apps that run inside a terminal as well as browsers.

    CAD Applications

    CAD engineers can take advantage of Python’s versatility to automate repetitive tasks such as drawing shapes and generating reports.

    Autodesk Fusion 360 is a popular CAD software, which has a Python API that allows users to automate tasks and create custom tools. Similarly, SolidWorks has a built-in Python shell that allows users to run Python scripts inside the software.

    CATIA is another very popular CAD software. Along with a VBScript, certain third-party Python libraries that can be used to control CATIA.

    Game Development

    Some popular gaming apps have been built with Python. Examples include BattleField2, The Sims 4, World of Tanks, Pirates of the Caribbean, and more. These apps are built with one of the following Python libraries.

    Pygame is one of the most popular Python libraries used to build engaging computer games. Pygame is an open-source Python library for making multimedia applications like games built on top of the excellent SDL library. It is a cross-platform library, which means you can build a game that can run on any operating system platform.

    Another library Kivy is also widely used to build desktop as well as mobile-based games. Kivy has a multi-touch interface. It is an open-source and cross-platform Python library for rapid development of game applications. Kivy runs on Linux, Windows, OS X, Android, iOS, and Raspberry Pi.

    PyKyra library is based on both SDL (Software and Documentation Localisation) and the Kyra engine. It is one of the fastest game development frameworks. PyKyra supports MPEG , MP3, Ogg Vorbis, Wav, etc., multimedia formats.

  • Hello World Program


    This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of Python built-in print() function to print the string.

    Hello World Program in Python

    Printing “Hello World” is the first program in Python. This program will not take any user input, it will just print text on the output screen. It is used to test if the software needed to compile and run the program has been installed correctly.

    Steps

    The following are the steps to write a Python program to print Hello World –

    • Step 1: Install Python. Make sure that Python is installed on your system or not. If Python is not installed, then install it from here: https://www.python.org/downloads/
    • Step 2: Choose Text Editor or IDE to write the code.
    • Step 3: Open Text Editor or IDE, create a new file, and write the code to print Hello World.
    • Step 4: Save the file with a file name and extension “.py”.
    • Step 5: Compile/Run the program.

    Python Program to Print Hello World

    # Python code to print "Hello World"print("Hello World")

    In the above code, we wrote two lines. The first line is the Python comment that will be ignored by the Python interpreter, and the second line is the print() statement that will print the given message (“Hello World”) on the output screen.

    Output

    Hello World
    

    Different Ways to Write and Execute Hello World Program

    Using Python Interpreter Command Prompt Mode

    It is very easy to display the Hello World message using the Python interpreter. Launch the Python interpreter from a command terminal of your Windows Operating System and issue the print statement from the Python prompt as follows −

    Example

    PS C:\> python
    Python 3.11.2(tags/v3.11.2:878ead1, Feb 72023,16:38:35)[MSC v.193464 bit (AMD64)] on win32
    Type "help","copyright","credits"or"license"for more information.>>>print("Hello World")
    Hello World
    

    Similarly, Hello World message is printed on Linux System.

    Example

    $ python3
    Python 3.10.6(main, Mar 102023,10:55:28)[GCC 11.3.0] on linux
    Type "help","copyright","credits"or"license"for more information.>>>print("Hello World")
    Hello World
    

    Using Python Interpreter Script Mode

    Python interpreter also works in scripted mode. Open any text editor, enter the following text and save as Hello.py

    print("Hello World")

    For Windows OS, open the command prompt terminal (CMD) and run the program as shown below −

    C:\>python hello.py
    

    This will display the following output

    Hello World
    

    To run the program from Linux terminal

    $ python3 hello.py
    

    This will display the following output

    Hello World
    

    Using Shebang #! in Linux Scripts

    In Linux, you can convert a Python program into a self executable script. The first statement in the code should be a shebang #!. It must contain the path to Python executable. In Linux, Python is installed in /usr/bin directory, and the name of the executable is python3. Hence, we add this statement to hello.py file

    #!/usr/bin/python3print("Hello World")

    You also need to give the file executable permission by using the chmod +x command

    $ chmod +x hello.py
    

    Then, you can run the program with following command line −

    $ ./hello.py
    

    This will display the following output

    Hello World
    

    FAQs

    1. Why the first program is called Hello World?

    It is just a simple program to test the basic syntax and compiler/interpreter configuration of Python programming language.

    2. Installation of Python is required to run Hello World program?

    Yes. Python installation is required to run Hello World program.

    3. How do I run a Python program without installing it?

    TutorialsPoint developed an online environment where you can run your codes. You can use the Python online compiler to run your Python programs.

    4. First Program Vs Hello World Program in Python?

    There is no difference. The first program of Python is generally known as the Hello World program.

    5. Which is/are the method to print Hello World or any message?

    You can use the following methods –

    • print() method
    • sys.stdout.write() method by importing the sys module
    • Using python-f string
  • Python vs C++

    Python is a general-purpose, high-level programming language. Python is used for web development, Machine Learning, and other cutting-edge software development. Python is suitable for both new and seasoned C++ and Java programmers. Guido Van Rossam has created Python in 1989 at Netherlands’ National Research Institute. Python was released in 1991.

    C++ is a middle-level, case-sensitive, object-oriented programming language. Bjarne Stroustrup created C++ at Bell Labs. C++ is a platform-independent programming language that works on Windows, Mac OS, and Linux. C++ is near to hardware, allowing low-level programming. This provides a developer control over memory, improved performance, and dependable software.

    Read through this article to get an overview of C++ and Python and how these two programming languages are different from each other.

    What is Python?

    Python is currently one of the most widely used programming languages. It is an interpreted programming language that operates at a high level. When compared to other languages, the learning curve for Python is much lower, and it is also quite straightforward to use.

    Python is the programming language of choice for professionals working in fields such as Artificial IntelligenceMachine Learning (ML)Data Science, the Internet of Things (IoT), etc., because it excels at both scripting applications and as standalone programmes.

    In addition to this, Python is the language of choice because it is easy to learn. Because of its excellent syntax and readability, the amount of money spent on maintenance is decreased. The modularity of the programme and the reusability of the code both contribute to its support for a variety of packages and modules.

    Using Python, we can perform

    • Web development
    • Data analysis and machine learning
    • Automation and scripting
    • Software testing and many moreFeatures
      Here is a list of some of the important features of Python
      Easy to learn Python has a simple structure, few keywords, and a clear syntax. This makes it easy for the student to learn quickly. Code written in Python is easier to read and understand.
      Easy to maintain The source code for Python is pretty easy to keep up with.
      A large standard library Most of Python’s library is easy to move around and works on UNIX, Windows, Mac.
      Portable Python can run on a wide range of hardware platforms, and all of them have the same interface.
      Python Example
      Take a look at the following simple Python program
      a = int(input(“Enter value for a”)) b = int(input(“Enter value for b”)) print(“The number you have entered for a is “, a) print(“The number you have entered for b is “, b)
      In our example, we have taken two variables “a” and “b” and assigning some value to those variables. Note that in Python, we don’t need to declare datatype for variables explicitly, as the PVM will assign datatype as per the user’s input.
      The input() function is used to take input from the user through keyboard.
      In Python, the return type of input() is string only, so we have to convert it explicitly to the type of data which we require. In our example, we have converted to int type explicitly through int( ) function.
      print() is used to display the output.
      Output
      On execution, this Python code will produce the following output
      Enter value for a 10 Enter value for b 20 The number you have entered for a is 10 The number you have entered for b is
    • 20
    • What is C++?
      C++ is a statically typed, compiled, multi-paradigm, general-purpose programming language with a steep learning curve. Video games, desktop apps, and embedded systems use it extensively. C++ is so compatible with C that it can build practically all C source code without any changes. Object-oriented programming makes C++ a better-structured and safer language than C.
      Features
      Let’s see some features of C++ and the reason of its popularity.
      Middle-level language It’s a middle-level language since it can be used for both systems development and large-scale consumer applications like Media Players, Photoshop, Game Engines, etc.
      Execution Speed C++ code runs quickly. Because it’s compiled and uses procedures extensively. Garbage collection, dynamic typing, and other modern features impede program execution.
      Object-oriented language Object-oriented programming is flexible and manageable. Large apps are possible. Growing code makes procedural code harder to handle. C++’s key advantage over C.
      Extensive Library Support C++ has a vast library. Third-party libraries are supported for fast development.
      C++ Example
      Let’s understand the syntax of C++ through an example written below.
      #include using namespace std; int main() { int a, b; cout << “Enter The value for variable a \n”; cin >> a; cout << “Enter The value for variable b”; cin >> b; cout << “The value of a is “<< a << “and” << b; return 0; }
      In our example, we are taking input for two variables “a” and “b” from the user through the keyboard and displaying the data on the console.
    • Output
      On execution, it will produce the following output
      Enter The value for variable a 10 Enter The value for variable b 20 The value of a is 10 and 20
      Comparison Between Python and C++ across Various Aspects
      Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this tutorial, we shall take a closure look at their characteristic features which differentiate one from another.
      Compiled vs Interpreted
      Like C, C++ is also a compiler-based language. A compiler translates the entire code in a machine language code specific to the operating system in use and processor architecture.
      Python is interpreter-based language. The interpreter executes the source code line by line.
      Cross platform
      When a C++ source code such as hello.cpp is compiled on Linux, it can be only run on any other computer with Linux operating system. If required to run on other OS, it needs to be compiled.
      Python interpreter doesn’t produce compiled code. Source code is converted to byte code every time it is run on any operating system without any changes or additional steps.
      Portability
      Python code is easily portable from one OS to other. C++ code is not portable as it must be recompiled if the OS changes.
      Speed of Development
      C++ program is compiled to the machine code. Hence, its execution is faster than interpreter based language.
      Python interpreter doesn’t generate the machine code. Conversion of intermediate byte code to machine language is done on each execution of program.
      If a program is to be used frequently, C++ is more efficient than Python.
      Easy to Learn
      Compared to C++, Python has a simpler syntax. Its code is more readable. Writing C++ code seems daunting in the beginning because of complicated syntax rule such as use of curly braces and semicolon for sentence termination.
      Python doesn’t use curly brackets for marking a block of statements. Instead, it uses indents. Statements of similar indent level mark a block. This makes a Python program more readable.
      Static vs Dynamic Typing
      C++ is a statically typed language. The type of variables for storing data need to be declared in the beginning. Undeclared variables can’t be used. Once a variable is declared to be of a certain type, value of only that type can be stored in it.
      Python is a dynamically typed language. It doesn’t require a variable to be declared before assigning it a value. Since, a variable may store any type of data, it is called dynamically typed.
      OOP Concepts
      Both C++ and Python implement object oriented programming concepts. C++ is closer to the theory of OOP than Python. C++ supports the concept of data encapsulation as the visibility of the variables can be defined as public, private and protected.
      Python doesn’t have the provision of defining the visibility. Unlike C++, Python doesn’t support method overloading. Because it is dynamically typed, all the methods are polymorphic in nature by default.
      C++ is in fact an extension of C. One can say that additional keywords are added in C so that it supports OOP. Hence, we can write a C type procedure oriented program in C++.
      Python is completely object oriented language. Python’s data model is such that, even if you can adapt a procedure oriented approach, Python internally uses object-oriented methodology.
      Garbage Collection
      C++ uses the concept of pointers. Unused memory in a C++ program is not cleared automatically. In C++, the process of garbage collection is manual. Hence, a C++ program is likely to face memory related exceptional behavior.
      Python has a mechanism of automatic garbage collection. Hence, Python program is more robust and less prone to memory related issues.
      Application Areas
      Because C++ program compiles directly to machine code, it is more suitable for systems programming, writing device drivers, embedded systems and operating system utilities.
      Python program is suitable for application programming. Its main area of application today is data science, machine learning, API development etc.
      Difference Between Python and C++
      The following table summarizes the differences between Python and C++
      Criteria
      Python
      C++
      Execution
      Python is an interpreted-based programming language. Python programs are interpreted by an interpreter.
      C++ is a compiler-based programming language. C++ programs are compiled by a compiler.
      Typing
      Python is a dynamic-typed language.
      C++ is a static-typed language.
      Portability
      Python is a highly portable language, code written and executed on a system can be easily run on another system.
      C++ is not a portable language, code written and executed on a system cannot be run on another system without making changes.
      Garbage collection
      Python provides a garbage collection feature. You do not need to worry about the memory management. It is automatic in Python.
      C++ does not provide garbage collection. You have to take care of freeing memories. It is manual in C++.
      Syntax
      Python’s syntaxes are very easy to read, write, and understand.
      C++’s syntaxes are tedious.
      Performance
      Python’s execution performance is slower than C++’s.
      C++ codes are faster than Python codes.
      Application areas
      Python’s application areas are machine learning, web applications, and more.
      C++’s application areas are embedded systems, device drivers, and more.