Category: Basic

  • Nested if Statement


    Python supports nested if statements which means we can use a conditional if and if…else statement inside an existing if statement.

    There may be a situation when you want to check for additional conditions after the initial one resolves to true. In such a situation, you can use the nested if construct.

    Additionally, within a nested if construct, you can include an if…elif…else construct inside another if…elif…else construct.

    Syntax of Nested if Statement

    The syntax of the nested if construct with else condition will be like this −

    if boolean_expression1:
    statement(s)if boolean_expression2:
    statement(s)
    Flowchart of Nested if Statement
    Following is the flowchart of Python nested if statement −

    nested if statement flowchart
    Example of Nested if Statement
    The below example shows the working of nested if statements −

    num = 36
    print ("num = ", num)
    if num % 2 == 0:
    if num % 3 == 0:
    print ("Divisible by 3 and 2")
    print("....execution ends....")
    When you run the above code, it will display the following result −

    num = 36
    Divisible by 3 and 2
    ....execution ends....
    Nested if Statement with else Condition
    As mentioned earlier, we can nest if-else statement within an if statement. If the if condition is true, the first if-else statement will be executed otherwise, statements inside the else block will be executed.

    Syntax
    The syntax of the nested if construct with else condition will be like this −

    if expression1:
    statement(s)
    if expression2:
    statement(s)
    else
    statement(s)
    else:
    if expression3:
    statement(s)
    else:
    statement(s)
    Example
    Now let's take a Python code to understand how it works −

    num=8
    print ("num = ",num)
    if num%2==0:
    if num%3==0:
    print ("Divisible by 3 and 2")
    else:
    print ("divisible by 2 not divisible by 3")
    else:
    if num%3==0:
    print ("divisible by 3 not divisible by 2")
    else:
    print ("not Divisible by 2 not divisible by 3")
    When the above code is executed, it produces the following output −

    num = 8
    divisible by 2 not divisible by 3
    num = 15
    divisible by 3 not divisible by 2
    num = 12
    Divisible by 3 and 2
    num = 5
    not Divisible by 2 not divisible by 3
  • ifelse Statement


    Python if else Statement

    The if-else statement in Python is used to execute a block of code when the condition in the if statement is true, and another block of code when the condition is false.

    Syntax of if-else Statement

    The syntax of an if-else statement in Python is as follows −

    if boolean_expression:# code block to be executed# when boolean_expression is trueelse:# code block to be executed# when boolean_expression is false

    If the boolean expression evaluates to TRUE, then the statement(s) inside the if block will be executed otherwise statements of the else block will be executed.

    Flowchart of if-else Statement

    This flowchart shows how if-else statement is used −

    ifelse syntax

    If the expr is True, block of stmt1, 2, 3 is executed then the default flow continues with stmt7. However, if the expr is False, block stmt4, 5, 6 runs then the default flow continues.

    Python implementation of the above flowchart is as follows −

    if expr==True:
       stmt1
       stmt2
       stmt3
    else:
       stmt4
       stmt5
       stmt6
    Stmt7
    

    Python if-else Statement Example

    Let us understand the use of if-else statements with the following example. Here, variable age can take different values. If the expression age > 18 is true, then eligible to vote message will be displayed otherwise not eligible to vote message will be displayed. Following flowchart illustrates this logic −

    if-else

    Now, let’s see the Python implementation the above flowchart.

    age=25print("age: ", age)if age >=18:print("eligible to vote")else:print("not eligible to vote")

    On executing this code, you will get the following output −

    age: 25
    eligible to vote
    

    To test the else block, change the age to 12, and run the code again.

    age: 12
    not eligible to vote
    Python if elif else Statement
    The if elif else statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.

    Similar to the else block, the elif block is also optional. However, a program can contains only one else block whereas there can be an arbitrary number of elif blocks following an if block.

    Syntax of Python if elif else Statement
    if expression1:
    statement(s)
    elif expression2:
    statement(s)
    elif expression3:
    statement(s)
    else:
    statement(s)
    How if elif else Works?
    The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade of elif statements after the first if statement. If the first if statement evaluates to false, subsequent elif statements are evaluated one by one and comes out of the cascade if any one is satisfied.

    Last in the cascade is the else block which will come in picture when all preceding if/elif conditions fails.

    Example
    Suppose there are different slabs of discount on a purchase −

    20% on amount exceeding 10000,

    10% for amount between 5-10000,

    5% if it is between 1 to 5000.

    no discount if amount<1000

    The following flowchart illustrates these conditions −

    if-elif
    We can write a Python code for the above logic with if-else statements −

    amount = 2500
    print('Amount = ',amount)
    if amount > 10000:
    discount = amount * 20 / 100
    else:
    if amount > 5000:
    discount = amount * 10 / 100
    else:
    if amount > 1000:
    discount = amount * 5 / 100
    else:
    discount = 0

    print('Payable amount = ',amount - discount)
    Set amount to test all possible conditions: 800, 2500, 7500 and 15000. The outputs will vary accordingly −

    Amount: 800
    Payable amount = 800
    Amount: 2500
    Payable amount = 2375.0
    Amount: 7500
    Payable amount = 6750.0
    Amount: 15000
    Payable amount = 12000.0
    While the code will work perfectly fine, if you look at the increasing level of indentation at each if and else statement, it will become difficult to manage if there are still more conditions.

    Python if elif else Statement Example
    The elif statement makes the code easy to read and comprehend. Following is the Python code for the same logic with if elif else statements −

    amount = 2500
    print('Amount = ',amount)
    if amount > 10000:
    discount = amount * 20 / 100
    elif amount > 5000:
    discount = amount * 10 / 100
    elif amount > 1000:
    discount = amount * 5 / 100
    else:
    discount=0

    print('Payable amount = ',amount - discount)
    The output of the above code is as follows −

    Amount: 2500
    Payable amount = 2375.0
  •  if Statement

    Python If Statement

    The if statement in Python evaluates whether a condition is true or false. It contains a logical expression that compares data, and a decision is made based on the result of the comparison.

    Syntax of the if Statement

    if expression:
       # statement(s) to be executed
    

    If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if block is executed.

    Flow Diagram (Flowchart) of the if Statement

    The below diagram shows flowchart of the if statement −

    Python if statement

    Example of Python if Statement

    Let us consider an example of a customer entitled to 10% discount if his purchase amount is > 1000; if not, then no discount is applicable. The following flowchart shows the whole decision making process −

    If Statement Flowchart

    First, set a discount variable to 0 and an amount variable to 1200. Then, use an if statement to check whether the amount is greater than 1000. If this condition is true, calculate the discount amount. If a discount is applicable, deduct it from the original amount.

    Python code for the above flowchart can be written as follows −

    discount =0
    amount =1200# Check he amount valueif amount >1000:
       discount = amount *10/100print("amount = ", amount - discount)

    Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will get the following output −

    amount = 1080.0
    

    Change the variable amount to 800, and run the code again. This time, no discount is applicable. And, you will get the following output −

    amount = 800
  • Decision Making

    Python’s decision making functionality is in its keywords − if..elif…else. The if keyword requires a boolean expression, followed by colon (:) symbol. The colon (:) symbol starts an indented block. The statements with the same level of indentation are executed if the boolean expression in if statement is True. If the expression is not True (False), the interpreter bypasses the indented block and proceeds to execute statements at earlier indentation level.

    Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.

    Following is the general form of a typical decision making structure found in most of the programming languages −

    Decision making statements in Python

    Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.

    Types of Decision Making Statements in Python

    Python programming language provides following types of decision making statements. Click the following links to check their detail.

    Sr.No.Statement & Description
    1if statementsAn if statement consists of a boolean expression followed by one or more statements.
    2if…else statementsAn if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.
    3nested if statementsYou can use one if or else if statement inside another if or else if statement(s).

    Let us go through each decision making briefly −

    Single Statement Suites

    If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.

    Example

    Here is an example of a one-line if clause −

    var =100if( var ==100):print("Value of expression is 100")print("Good bye!")

    When the above code is executed, it produces the following result −

    Value of expression is 100
    Good bye!
    

    if…else statement

    In this decision making statement, if the if condition is true, then the statements within this block are executed, otherwise, the else block is executed.

    The program will choose which block of code to execute based on whether the condition in the if statement is true or false.

    Example

    The following example shows the use of if…else statement.

    var =100if( var ==100):print("Value of var is equal to 100")else:print("Value of var is not equal to 100")

    On running the above code, it will show the following output −

    Value of var is equal to 100
    

    Nested if statements

    A nested if is another decision making statement in which one if statement resides inside another. It allows us to check multiple conditions sequentially.

    Example

    In this example, we will see the use of nested-if statement.

    var =100if( var ==100):print("The number is equal to 100")if var %2==0:print("The number is even")else:print("The given number is odd")elif var ==0:print("The given number is zero")else:print("The given number is negative")

    On executing the above code, it will display the below output −

    The number is equal to 100
    The number is even
  • Control Flow

    Python program control flow is regulated by various types of conditional statementsloops, and function calls. By default, the instructions in a computer program are executed in a sequential manner, from top to bottom, or from start to end. However, such sequentially executing programs can perform only simplistic tasks. We would like the program to have a decision-making ability, so that it performs different steps depending on different conditions.

    Most programming languages including Python provide functionality to control the flow of execution of instructions. Normally, there are two type of control flow statements in any programming language and Python also supports them.

    Decision Making Statements

    Decision making statements are used in the Python programs to make them able to decide which of the alternative group of instructions to be executed, depending on value of a certain Boolean expression.

    The following diagram illustrates how decision-making statements work −

    decision making statements

    The if Statements

    Python provides if..elif..else control statements as a part of decision marking. It consists of three different blocks, which are if block, elif (short of else if) block and else block.

    Example

    Following is a simple example which makes use of if..elif..else. You can try to run this program using different marks and verify the result.

    marks =80 
    result =""if marks <30:
       result ="Failed"elif marks >75:
       result ="Passed with distinction"else:
       result ="Passed"print(result)

    This will produce following result:

    Passed with distinction
    

    The match Statement

    Python supports Match-Case statement, which can also be used as a part of decision making. If a pattern matches the expression, the code under that case will execute.

    Example

    Following is a simple example which makes use of match statement.

    defcheckVowel(n):
       match n:
    
      case 'a':return"Vowel alphabet"
      case 'e':return"Vowel alphabet"
      case 'i':return"Vowel alphabet"
      case 'o':return"Vowel alphabet"
      case 'u':return"Vowel alphabet"
      case _:return"Simple alphabet"print(checkVowel('a'))print(checkVowel('m'))print(checkVowel('o'))</pre>

    This will produce following result:

    Vowel alphabet
    Simple alphabet
    Vowel alphabet
    Loops or Iteration Statements
    Most of the processes require a group of instructions to be repeatedly executed. In programming terminology, it is called a loop. Instead of the next step, if the flow is redirected towards any earlier step, it constitutes a loop.

    The following diagram illustrates how the looping works −

    looping_works
    If the control goes back unconditionally, it forms an infinite loop which is not desired as the rest of the code would never get executed.

    In a conditional loop, the repeated iteration of block of statements goes on till a certain condition is met. Python supports a number of loops like for loop, while loop which we will study in next chapters.

    The for Loop
    The for loop iterates over the items of any sequence, such as a list, tuple or a string .

    Example
    Following is an example which makes use of For Loop to iterate through an array in Python:

    words = ["one", "two", "three"]
    for x in words:
    print(x)
    This will produce following result:

    one
    two
    three
    The while Loop
    The while loop repeatedly executes a target statement as long as a given boolean expression is true.

    Example
    Following is an example which makes use of While Loop to print first 5 numbers in Python:

    i = 1
    while i < 6:
    print(i)
    i += 1
    This will produce following result:

    1
    2
    3
    4
    5
    Jump Statements
    The jump statements are used to jump on a specific statement by breaking the current flow of the program. In Python, there are two jump statements break and continue.

    The break Statement
    It terminates the current loop and resumes execution at the next statement.

    Example
    The following example demonstrates the use of break statement −

    x = 0

    while x < 10:
    print("x:", x)
    if x == 5:
    print("Breaking...")
    break
    x += 1

    print("End")
    This will produce following result:

    x: 0
    x: 1
    x: 2
    x: 3
    x: 4
    x: 5
    Breaking...
    End
    It skips the execution of the program block and returns the control to the beginning of the current loop to start the next iteration.
    Example
    The following example demonstrates the use of continue statement −

    Open Compiler
    for letter in "Python":
    # continue when letter is 'h'
    if letter == "h":
    continue
    print("Current Letter :", letter)

    This will produce following result:

    Current Letter : P
    Current Letter : y
    Current Letter : t
    Current Letter : o
    Current Letter : n
  • Booleans

    Python Booleans (bool)

    In Python, bool is a sub-type of int type. A bool object has two possible values, and it is initialized with Python keywords, True and False.

    Example

    >>> a=True>>> b=False>>>type(a),type(b)(<class'bool'>,<class'bool'>)

    A bool object is accepted as argument to type conversion functions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for False, they return 0 and 0.0 respectively. We have a one argument version of complex() function.

    If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0.

    Example

    a=int(True)print("bool to int:", a)
    a=float(False)print("bool to float:", a)
    a=complex(True)print("bool to complex:", a)

    On running this code, you will get the following output −

    bool to int: 1
    bool to float: 0.0
    bool to complex: (1+0j)

    Python Boolean Expression
    Python boolean expression is an expression that evaluates to a Boolean value. It almost always involves a comparison operator. In the below example we will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an expresison.

    Syntax: bool([x])
    Returns True if X evaluates to true else false.
    Without parameters it returns false.
    Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out as true or false depending on the parameter.

    Example
    # Check true
    a = True
    print(bool(a))
    # Check false
    a = False
    print(bool(a))
    # Check 0
    a = 0.0
    print(bool(a))
    # Check 1
    a = 1.0
    print(bool(a))
    # Check Equality
    a = 5
    b = 10
    print(bool( a==b))
    # Check None
    a = None
    print(bool(a))
    # Check an empty sequence
    a = ()
    print(bool(a))
    # Check an emtpty mapping
    a = {}
    print(bool(a))
    # Check a non empty string
    a = 'Tutorialspoint'
    print(bool(a))

  • Numbers

    Python has built-in support to store and process numeric data (Python Numbers). Most of the times you work with numbers in almost every Python application. Obviously, any computer application deals with numbers. This tutorial will discuss about different types of Python Numbers and their properties.

    Python – Number Types

    There are three built-in number types available in Python:

    • integers (int)
    • floating point numbers (float)
    • complex numbers

    Python also has a bult-in Boolean data type called bool. It can be treated as a sub-type of int type, since it’s two possible values True and False represent the integers 1 and 0 respectively.

    Python − Integer Numbers

    In Python, any number without the provision to store a fractional part is an integer. (Note that if the fractional part in a number is 0, it doesn’t mean that it is an integer. For example a number 10.0 is not an integer, it is a float with 0 fractional part whose numeric value is 10.) An integer can be zero, positive or a negative whole number. For example, 1234, 0, -55 all represent to integers in Python.

    There are three ways to form an integer object. With (a) literal representation, (b) any expression evaluating to an integer, and (c) using int() function.

    Literal is a notation used to represent a constant directly in the source code. For example −

    >>> a =10

    However, look at the following assignment of the integer variable c.

    a =10
    b =20
    c = a + b
    
    print("a:", a,"type:",type(a))print("c:", c,"type:",type(c))

    It will produce the following output −

    a: 10 type: <class 'int'>
    c: 30 type: <class 'int'>
    

    Here, c is indeed an integer variable, but the expression a + b is evaluated first, and its value is indirectly assigned to c.

    The third method of forming an integer object is with the return value of int() function. It converts a floating point number or a string in an integer.

    >>> a=int(10.5)>>> b=int("100")

    You can represent an integer as a binary, octal or Hexa-decimal number. However, internally the object is stored as an integer.

    Binary Numbers in Python

    A number consisting of only the binary digits (1 and 0) and prefixed with “0b” is a binary number. If you assign a binary number to a variable, it still is an int variable.

    A represent an integer in binary form, store it directly as a literal, or use int() function, in which the base is set to 2

    a=0b101print("a:",a,"type:",type(a))
    
    b=int("0b101011",2)print("b:",b,"type:",type(b))

    It will produce the following output −

    a: 5 type: <class 'int'>
    b: 43 type: <class 'int'>
    

    There is also a bin() function in Python. It returns a binary string equivalent of an integer.

    a=43
    b=bin(a)print("Integer:",a,"Binary equivalent:",b)

    It will produce the following output −

    Integer: 43 Binary equivalent: 0b101011
    

    Octal Numbers in Python

    An octal number is made up of digits 0 to 7 only. In order to specify that the integer uses octal notation, it needs to be prefixed by “0o” (lowercase O) or “0O” (uppercase O). A literal representation of octal number is as follows −

    a=0O107print(a,type(a))

    It will produce the following output −

    71 <class 'int'>
    

    Note that the object is internally stored as integer. Decimal equivalent of octal number 107 is 71.

    Since octal number system has 8 symbols (0 to 7), its base is 7. Hence, while using int() function to covert an octal string to integer, you need to set the base argument to 8.

    a=int('20',8)print(a,type(a))

    It will produce the following output −

    16 <class 'int'>
    

    Decimal equivalent of octal 30 is 16.

    In the following code, two int objects are obtained from octal notations and their addition is performed.

    a=0O56print("a:",a,"type:",type(a))
    
    b=int("0O31",8)print("b:",b,"type:",type(b))
    
    c=a+b
    print("addition:", c)

    It will produce the following output −

    a: 46 type: <class 'int'>
    b: 25 type: <class 'int'>
    addition: 71
    

    To obtain the octal string for an integer, use oct() function.

    a=oct(71)print(a,type(a))

    Hexa-decimal Numbers in Python

    As the name suggests, there are 16 symbols in the Hexadecimal number system. They are 0-9 and A to F. The first 10 digits are same as decimal digits. The alphabets A, B, C, D, E and F are equivalents of 11, 12, 13, 14, 15, and 16 respectively. Upper or lower cases may be used for these letter symbols.

    For the literal representation of an integer in Hexadecimal notation, prefix it by “0x” or “0X”.

    a=0XA2print(a,type(a))

    It will produce the following output −

    162 <class 'int'>
    

    To convert a Hexadecimal string to integer, set the base to 16 in the int() function.

    a=int('0X1e',16)print(a,type(a))

    Try out the following code snippet. It takes a Hexadecimal string, and returns the integer.

    num_string ="A1"
    number =int(num_string,16)print("Hexadecimal:", num_string,"Integer:",number)

    It will produce the following output −

    Hexadecimal: A1 Integer: 161
    

    However, if the string contains any symbol apart from the Hexadecimal symbol chart an error will be generated.

    num_string ="A1X001"print(int(num_string,16))

    The above program generates the following error −

    Traceback (most recent call last):
      File "/home/main.py", line 2, in 
    
    print (int(num_string, 16))
    ValueError: invalid literal for int() with base 16: 'A1X001'

    Python’s standard library has hex() function, with which you can obtain a hexadecimal equivalent of an integer.

    Open Compiler

    a=hex(161)print(a,type(a))

    It will produce the following output −

    0xa1 <class 'str'>
    

    Though an integer can be represented as binary or octal or hexadecimal, internally it is still integer. So, when performing arithmetic operation, the representation doesn’t matter.

    a=10#decimal
    b=0b10#binary
    c=0O10#octal
    d=0XA#Hexadecimal
    e=a+b+c+d
    
    print("addition:", e)

    It will produce the following output −

    addition: 30
    

    Python − Floating Point Numbers

    A floating point number has an integer part and a fractional part, separated by a decimal point symbol (.). By default, the number is positive, prefix a dash (-) symbol for a negative number.

    A floating point number is an object of Python’s float class. To store a float object, you may use a literal notation, use the value of an arithmetic expression, or use the return value of float() function.

    Using literal is the most direct way. Just assign a number with fractional part to a variable. Each of the following statements declares a float object.

    >>> a=9.99>>> b=0.999>>> c=-9.99>>> d=-0.999

    In Python, there is no restriction on how many digits after the decimal point can a floating point number have. However, to shorten the representation, the E or e symbol is used. E stands for Ten raised to. For example, E4 is 10 raised to 4 (or 4th power of 10), e-3 is 10 raised to -3.

    In scientific notation, number has a coefficient and exponent part. The coefficient should be a float greater than or equal to 1 but less than 10. Hence, 1.23E+3, 9.9E-5, and 1E10 are the examples of floats with scientific notation.

    >>> a=1E10>>> a
    10000000000.0>>> b=9.90E-5>>> b
    9.9e-05>>>1.23E31230.0

    The second approach of forming a float object is indirect, using the result of an expression. Here, the quotient of two floats is assigned to a variable, which refers to a float object.

    a=10.33
    b=2.66
    c=a/b
    
    print("c:", c,"type",type(c))

    It will produce the following output −

    c: 3.8834586466165413 type <class 'float'>
    

    Python’s float() function returns a float object, parsing a number or a string if it has the appropriate contents. If no arguments are given in the parenthesis, it returns 0.0, and for an int argument, fractional part with 0 is added.

    >>> a=float()>>> a
    0.0>>> a=float(10)>>> a
    10.0

    Even if the integer is expressed in binary, octal or hexadecimal, the float() function returns a float with fractional part as 0.

    Open Compiler

    a=float(0b10)
    b=float(0O10)
    c=float(0xA)print(a,b,c, sep=",")

    It will produce the following output −

    2.0,8.0,10.0
    

    The float() function retrieves a floating point number out of a string that encloses a float, either in standard decimal point format, or having scientific notation.

    a=float("-123.54")
    b=float("1.23E04")print("a=",a,"b=",b)

    It will produce the following output −

    a= -123.54 b= 12300.0
    

    In mathematics, infinity is an abstract concept. Physically, infinitely large number can never be stored in any amount of memory. For most of the computer hardware configurations, however, a very large number with 400th power of 10 is represented by Inf. If you use “Infinity” as argument for float() function, it returns Inf.

    a=1.00E400print(a,type(a))
    a=float("Infinity")print(a,type(a))

    It will produce the following output −

    inf <class 'float'>
    inf <class 'float'>
    

    One more such entity is Nan (stands for Not a Number). It represents any value that is undefined or not representable.

    >>> a=float('Nan')>>> a
    Nan
    

    Python − Complex Numbers

    In this section, we shall know in detail about Complex data type in Python. Complex numbers find their applications in mathematical equations and laws in electromagnetism, electronics, optics, and quantum theory. Fourier transforms use complex numbers. They are Used in calculations with wavefunctions, designing filters, signal integrity in digital electronics, radio astronomy, etc.

    A complex number consists of a real part and an imaginary part, separated by either “+” or “−”. The real part can be any floating point (or itself a complex number) number. The imaginary part is also a float/complex, but multiplied by an imaginary number.

    In mathematics, an imaginary number “i” is defined as the square root of -1 (&bsol;sqrt{−1}). Therefore, a complex number is represented as “x+yi”, where x is the real part, and “y” is the coefficient of imaginary part.

    Quite often, the symbol “j” is used instead of “I” for the imaginary number, to avoid confusion with its usage as current in theory of electricity. Python also uses “j” as the imaginary number. Hence, “x+yj” is the representation of complex number in Python.

    Like int or float data type, a complex object can be formed with literal representation or using complex() function. All the following statements form a complex object.

    >>> a=5+6j>>> a
    (5+6j)>>>type(a)<class'complex'>>>> a=2.25-1.2J>>> a
    (2.25-1.2j)>>>type(a)<class'complex'>>>> a=1.01E-2+2.2e3j>>> a
    (0.0101+2200j)>>>type(a)<class'complex'>

    Note that the real part as well as the coefficient of imaginary part have to be floats, and they may be expressed in standard decimal point notation or scientific notation.

    Python’s complex() function helps in forming an object of complex type. The function receives arguments for real and imaginary part, and returns the complex number.

    There are two versions of complex() function, with two arguments and with one argument. Use of complex() with two arguments is straightforward. It uses first argument as real part and second as coefficient of imaginary part.

    a=complex(5.3,6)
    b=complex(1.01E-2,2.2E3)print("a:", a,"type:",type(a))print("b:", b,"type:",type(b))

    It will produce the following output −

    a: (5.3+6j) type: <class 'complex'>
    b: (0.0101+2200j) type: <class 'complex'>
    

    In the above example, we have used x and y as float parameters. They can even be of complex data type.

    a=complex(1+2j,2-3j)print(a,type(a))

    It will produce the following output −

    (4+4j) <class 'complex'>
    

    Surprised by the above example? Put “x” as 1+2j and “y” as 2-3j. Try to perform manual computation of “x+yj” and you’ll come to know.

    complex(1+2j,2-3j)=(1+2j)+(2-3j)*j
    =1+2j+2j+3=4+4j

    If you use only one numeric argument for complex() function, it treats it as the value of real part; and imaginary part is set to 0.

    a=complex(5.3)print("a:", a,"type:",type(a))

    It will produce the following output −

    a: (5.3+0j) type: <class 'complex'>
    

    The complex() function can also parse a string into a complex number if its only argument is a string having complex number representation.

    In the following snippet, user is asked to input a complex number. It is used as argument. Since Python reads the input as a string, the function extracts the complex object from it.

    a="5.5+2.3j"
    b=complex(a)print("Complex number:", b)

    It will produce the following output −

    Complex number: (5.5+2.3j)
    

    Python’s built-in complex class has two attributes real and imag − they return the real and coefficient of imaginary part from the object.

    a=5+6jprint("Real part:", a.real,"Coefficient of Imaginary part:", a.imag)

    It will produce the following output −

    Real part: 5.0 Coefficient of Imaginary part: 6.0
    

    The complex class also defines a conjugate() method. It returns another complex number with the sign of imaginary component reversed. For example, conjugate of x+yj is x-yj.

    >>> a=5-2.2j>>> a.conjugate()(5+2.2j)

    Number Type Conversion

    Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

    • Type int(x) to convert x to a plain integer.
    • Type long(x) to convert x to a long integer.
    • Type float(x) to convert x to a floating-point number.
    • Type complex(x) to convert x to a complex number with real part x and imaginary part zero. In the same way type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions

    Let us see various numeric and math-related functions.

    Theoretic and Representation Functions

    Python includes following theoretic and representation Functions in the math module −

    Sr.No.Function & Description
    1math.ceil(x)The ceiling of x: the smallest integer not less than x
    2math.comb(n,k)This function is used to find the returns the number of ways to choose “x” items from “y” items without repetition and without order.
    3math.copysign(x, y)This function returns a float with the magnitude (absolute value) of x but the sign of y.
    4math.cmp(x, y)This function is used to compare the values of to objects. This function is deprecated in Python3.
    5math.fabs(x)This function is used to calculate the absolute value of a given integer.
    6math.factorial(n)This function is used to find the factorial of a given integer.
    7math.floor(x)This function calculates the floor value of a given integer.
    8math.fmod(x, y)The fmod() function in math module returns same result as the “%” operator. However fmod() gives more accurate result of modulo division than modulo operator.
    9math.frexp(x)This function is used to calculate the mantissa and exponent of a given number.
    10math.fsum(iterable)This function returns the floating point sum of all numeric items in an iterable i.e. list, tuple, array.
    11math.gcd(*integers)This function is used to calculate the greatest common divisor of all the given integers.
    12math.isclose()This function is used to determine whether two given numeric values are close to each other.
    13math.isfinite(x)This function is used to determine whether the given number is a finite number.
    14math.isinf(x)This function is used to determine whether the given value is infinity (+ve or, -ve).
    15math.isnan(x)This function is used to determine whether the given number is “NaN”.
    16math.isqrt(n)This function calculates the integer square-root of the given non negative integer.
    17math.lcm(*integers)This function is used to calculate the least common factor of the given integer arguments.
    18math.ldexp(x, i)This function returns product of first number with exponent of second number. So, ldexp(x,y) returns x*2**y. This is inverse of frexp() function.
    19math.modf(x)This returns the fractional and integer parts of x in a two-item tuple.
    20math.nextafter(x, y, steps)This function returns the next floating-point value after x towards y.
    21math.perm(n, k)This function is used to calculate the permutation. It returns the number of ways to choose x items from y items without repetition and with order.
    22math.prod(iterable, *, start)This function is used to calculate the product of all numeric items in the iterable (list, tuple) given as argument.
    23math.remainder(x,y)This function returns the remainder of x with respect to y. This is the difference x − n*y, where n is the integer closest to the quotient x / y.
    24math.trunc(x)This function returns integral part of the number, removing the fractional part. trunc() is equivalent to floor() for positive x, and equivalent to ceil() for negative x.
    25math.ulp(x)This function returns the value of the least significant bit of the float x. trunc() is equivalent to floor() for positive x, and equivalent to ceil() for negative x.

    Power and Logarithmic Functions

    Sr.No.Function & Description
    1math.cbrt(x)This function is used to calculate the cube root of a number.
    2math.exp(x)This function calculate the exponential of x: ex
    3math.exp2(x)This function returns 2 raised to power x. It is equivalent to 2**x.
    4math.expm1(x)This function returns e raised to the power x, minus 1. Here e is the base of natural logarithms.
    5math.log(x)This function calculates the natural logarithm of x, for x> 0.
    6math.log1p(x)This function returns the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
    7math.log2(x)This function returns the base-2 logarithm of x. This is usually more accurate than log(x, 2).
    8math.log10(x)The base-10 logarithm of x for x> 0.
    9math.pow(x, y)The value of x**y.
    10math.sqrt(x)The square root of x for x > 0

    Trigonometric Functions

    Python includes following functions that perform trigonometric calculations in the math module −

    Sr.No.Function & Description
    1math.acos(x)This function returns the arc cosine of x, in radians.
    2math.asin(x)This function returns the arc sine of x, in radians.
    3math.atan(x)This function returns the arc tangent of x, in radians.
    4math.atan2(y, x)This function returns atan(y / x), in radians.
    5math.cos(x)This function returns the cosine of x radians.
    6math.sin(x)This function returns the sine of x radians.
    7math.tan(x)This function returns the tangent of x radians.
    8math.hypot(x, y)This function returns the Euclidean norm, sqrt(x*x + y*y).

    Angular conversion Functions

    Following are the angular conversion function provided by Python math module −

    Sr.No.Function & Description
    1math.degrees(x)This function converts the given angle from radians to degrees.
    2math.radians(x)This function converts the given angle from degrees to radians.

    Mathematical Constants

    The Python math module defines the following mathematical constants −

    Sr.No.Constants & Description
    1math.piThis represents the mathematical constant pi, which equals to “3.141592…” to available precision.
    2math.eThis represents the mathematical constant e, which is equal to “2.718281…” to available precision.
    3math.tauThis represents the mathematical constant Tau (denoted by ). It is equivalent to the ratio of circumference to radius, and is equal to 2.
    4math.infThis represents positive infinity. For negative infinity use “−math.inf”.
    5math.nanThis constant is a floating-point “not a number” (NaN) value. Its value is equivalent to the output of float(‘nan’).

    Hyperbolic Functions

    Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles. Following are the hyperbolic functions of the Python math module −

    Sr.No.Function & Description
    1math.acosh(x)This function is used to calculate the inverse hyperbolic cosine of the given value.
    2math.asinh(x)This function is used to calculate the inverse hyperbolic sine of a given number.
    3math.atanh(x)This function is used to calculate the inverse hyperbolic tangent of a number.
    4math.cosh(x)This function is used to calculate the hyperbolic cosine of the given value.
    5math.sinh(x)This function is used to calculate the hyperbolic sine of a given number.
    6math.tanh(x)This function is used to calculate the hyperbolic tangent of a number.

    Special Functions

    Following are the special functions provided by the Python math module −

    Sr.No.Function & Description
    1math.erf(x)This function returns the value of the Gauss error function for the given parameter.
    2math.erfc(x)This function is the complementary for the error function. Value of erf(x) is equivalent to 1-erf(x).
    3math.gamma(x)This is used to calculate the factorial of the complex numbers. It is defined for all the complex numbers except the non-positive integers.
    4math.lgamma(x)This function is used to calculate the natural logarithm of the absolute value of the Gamma function at x.

    Random Number Functions

    Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions in the random module.

    Sr.No.Function & Description
    1random.choice(seq)A random item from a list, tuple, or string.
    2random.randrange([start,] stop [,step])A randomly selected element from range(start, stop, step)
    3random.random()A random float r, such that 0 is less than or equal to r and r is less than 1
    4random.seed([x])This function sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.
    5random.shuffle(seq)This function is used to randomize the items of the given sequence.
    6random.uniform(a, b)This function returns a random floating point value r, such that a is less than or equal to r and r is less than b.

    Built-in Mathematical Functions

    Following mathematical functions are built into the Python interpreter, hence you don’t need to import them from any module.

    Sr.No.Function & Description
    1Python abs() functionThe abs() function returns the absolute value of x, i.e. the positive distance between x and zero.
    2Python max() functionThe max() function returns the largest of its arguments or largest number from the iterable (list or tuple).
    3Python min() functionThe function min() returns the smallest of its arguments i.e. the value closest to negative infinity, or smallest number from the iterable (list or tuple)
    4Python pow() functionThe pow() function returns x raised to y. It is equivalent to x**y.
    5Python round() Functionround() is a built-in function in Python. It returns x rounded to n digits from the decimal point.
    6Python sum() functionThe sum() function returns the sum of all numeric items in any iterable (list or tuple). It has an optional start argument which is 0 by default. If given, the numbers in the list are added to start value.
  • User Input

    Provide User Input in Python

    In this chapter, we will learn how Python accepts the user input from the console, and displays the output on the same console.

    Every computer application should have a provision to accept input from the user when it is running. This makes the application interactive. Depending on how it is developed, an application may accept the user input in the form of text entered in the console (sys.stdin), a graphical layout, or a web-based interface.

    Python User Input Functions

    Python provides us with two built-in functions to read the input from the keyboard.

    • The input () Function
    • The raw_input () Function

    Python interpreter works in interactive and scripted mode. While the interactive mode is good for quick evaluations, it is less productive. For repeated execution of same set of instructions, scripted mode should be used.

    Let us write a simple Python script to start with.

    #! /usr/bin/python3.11
    
    name ="Kiran"
    city ="Hyderabad"print("Hello My name is", name)print("I am from", city)

    Save the above code as hello.py and run it from the command-line. Here’s the output

    C:\python311> python hello.py
    Hello My name is Kiran
    I am from Hyderabad
    

    The program simply prints the values of the two variables in it. If you run the program repeatedly, the same output will be displayed every time. To use the program for another name and city, you can edit the code, change name to say “Ravi” and city to “Chennai”. Every time you need to assign different value, you will have to edit the program, save and run, which is not the ideal way.

    The input() Function

    Obviously, you need some mechanism to assign different value to the variable in the runtime − while the program is running. Python’s input() function does the same job.

    Following is the syntax of Python’s standard library input() function.

    >>> var =input()

    When the interpreter encounters input() function, it waits for the user to enter data from the standard input stream (keyboard) till the Enter key is pressed. The sequence of characters may be stored in a string variable for further use.

    On reading the Enter key, the program proceeds to the next statement. Let use change our program to store the user input in name and city variables.

    #! /usr/bin/python3.11
    
    name =input()
    city =input()print("Hello My name is", name)print("I am from ", city)

    When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed.

    Ravi
    Chennai
    Hello My name is Ravi
    I am from Chennai
    

    Now, the variables are not assigned any specific value in the program. Every time you run, different values can be input. So, your program has become truly interactive.

    Inside the input() function, you may give a prompt text, which will appear before the cursor when you run the code.

    #! /usr/bin/python3.11
    
    name =input("Enter your name : ")
    city =input("Enter your city : ")print("Hello My name is", name)print("I am from ", city)

    When you run the program displays the prompt message, basically helping the user what to enter.

    Enter your name: Praveen Rao
    Enter your city: Bengaluru
    Hello My name is Praveen Rao
    I am from Bengaluru
    

    The raw_input() Function

    The raw_input() function works similar to input() function. Here only point is that this function was available in Python 2.7, and it has been renamed to input() in Python 3.6

    Following is the syntax of the raw_input() function:

    >>> var =raw_input([prompt text])

    Let’s re-write the above program using raw_input() function:

    #! /usr/bin/python3.11
    
    name =raw_input("Eneter your name - ")
    city =raw_input("Enter city name - ")print("Hello My name is", name)print("I am from ", city)

    When you run, you will find the cursor waiting for user’s input. Enter values for name and city. Using the entered data, the output will be displayed.

    Eneter your name - Ravi
    Enter city name - Chennai
    Hello My name is Ravi
    I am from Chennai
    

    Taking Numeric Input in Python

    Let us write a Python code that accepts width and height of a rectangle from the user and computes the area.

    #! /usr/bin/python3.11
    
    width =input("Enter width : ")
    height =input("Enter height : ")
    
    area = width*height
    print("Area of rectangle = ", area)

    Run the program, and enter width and height.

    Enter width: 20
    Enter height: 30
    Traceback (most recent call last):
      File "C:\Python311\var1.py", line 5, in <module>
       area = width*height
    TypeError: can't multiply sequence by non-int of type 'str'
    

    Why do you get a TypeError here? The reason is, Python always read the user input as a string. Hence, width=”20″ and height=”30″ are the strings and obviously you cannot perform multiplication of two strings.

    To overcome this problem, we shall use int(), another built-in function from Python’s standard library. It converts a string object to an integer.

    To accept an integer input from the user, read the input in a string, and type cast it to integer with int() function −

    w =input("Enter width : ")
    width =int(w)
    
    h =input("Enter height : ")
    height =int(h)

    You can combine the input and type cast statements in one −

    #! /usr/bin/python3.11
    
    width =int(input("Enter width : "))
    height =int(input("Enter height : "))
    
    area = width*height
    print("Area of rectangle = ", area)

    Now you can input any integer value to the two variables in the program −

    Enter width: 20
    Enter height: 30
    Area of rectangle = 600
    Python's float() function converts a string into a float object. The following program accepts the user input and parses it to a float variable − rate, and computes the interest on an amount which is also input by the user.

    #! /usr/bin/python3.11

    amount = float(input("Enter Amount : "))
    rate = float(input("Enter rate of interest : "))

    interest = amount*rate/100
    print ("Amount: ", amount, "Interest: ", interest)
    The program ask user to enter amount and rate; and displays the result as follows −

    Enter Amount: 12500
    Enter rate of interest: 6.5
    Amount: 12500.0 Interest: 812.5
    The print() Function
    Python's print() function is a built-in function. It is the most frequently used function, that displays value of Python expression given in parenthesis, on Python's console, or standard output (sys.stdout).

    print ("Hello World ")
    Any number of Python expressions can be there inside the parenthesis. They must be separated by comma symbol. Each item in the list may be any Python object, or a valid Python expression.

    #! /usr/bin/python3.11

    a = "Hello World"
    b = 100
    c = 25.50
    d = 5+6j
    print ("Message: a)
    print (b, c, b-c)
    print(pow(100, 0.5), pow(c,2))
    The first call to print() displays a string literal and a string variable. The second prints value of two variables and their subtraction. The pow() function computes the square root of a number and square value of a variable.

    Message Hello World
    100 25.5 74.5
    10.0 650.25
    If there are multiple comma separated objects in the print() function's parenthesis, the values are separated by a white space " ". To use any other character as a separator, define a sep parameter for the print() function. This parameter should follow the list of expressions to be printed.

    In the following output of print() function, the variables are separated by comma.

    #! /usr/bin/python3.11

    city="Hyderabad"
    state="Telangana"
    country="India"
    print(city, state, country, sep=',')
    The effect of sep=',' can be seen in the result −

    Hyderabad,Telangana,India
    The print() function issues a newline character ('\n') at the end, by default. As a result, the output of the next print() statement appears in the next line of the console.

    city="Hyderabad"
    state="Telangana"
    print("City:", city)
    print("State:", state)
    Two lines are displayed as the output −

    City: Hyderabad
    State: Telangana
    To make these two lines appear in the same line, define end parameter in the first print() function and set it to a whitespace string " ".

    Open Compiler
    city="Hyderabad"
    state="Telangana"
    country="India"

    print("City:", city, end=" ")
    print("State:", state)
    Output of both the print() functions appear in continuation.

    City: Hyderabad State: Telangana
  •  Comments

    Python Comments

    Python comments are programmer-readable explanation or annotations 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. Comments enhance the readability of the code and help the programmers to understand the code very carefully.

    Example

    If we execute the code given below, the output produced will simply print “Hello, World!” to the console, as comments are ignored by the Python interpreter and do not affect the execution of the program −

    # This is a commentprint("Hello, World!")

    Python supports three types of comments as shown below −

    • Single-line comments
    • Multi-line comments
    • Docstring Comments

    Advertisement

    Single Line Comments in Python

    Single-line comments in Python start with a hash symbol (#) and extend to the end of the line. They are used to provide short explanations or notes about the code. They can be placed on their own line above the code they describe, or at the end of a line of code (known as an inline comment) to provide context or clarification about that specific line.

    Example: Standalone Single-Line Comment

    A standalone single-line comment is a comment that occupies an entire line by itself, starting with a hash symbol (#). It is placed above the code it describes or annotates.

    In this example, the standalone single-line comment is placed above the “greet” function “−

    # Standalone single line comment is placed heredefgreet():print("Hello, World!")
    greet()

    Example: Inline Single-Line Comment

    An inline single-line comment is a comment that appears on the same line as a piece of code, following the code and preceded by a hash symbol (#).

    In here, the inline single-line comment follows the print(“Hello, World!”) statement −

    print("Hello, World!")# Inline single line comment is placed here

    Multi Line Comments in Python

    In Python, multi-line comments are used to provide longer explanations or notes that span multiple lines. While Python does not have a specific syntax for multi-line comments, there are two common ways to achieve this: consecutive single-line comments and triple-quoted strings −

    Consecutive Single-Line Comments

    Consecutive single-line comments refers to using the hash symbol (#) at the beginning of each line. This method is often used for longer explanations or to section off parts of the code.

    Example

    In this example, multiple lines of comments are used to explain the purpose and logic of the factorial function −

    # This function calculates the factorial of a number# using an iterative approach. The factorial of a number# n is the product of all positive integers less than or# equal to n. For example, factorial(5) is 5*4*3*2*1 = 120.deffactorial(n):if n <0:return"Factorial is not defined for negative numbers"
       result =1for i inrange(1, n +1):
    
      result *= i
    return result number =5print(f"The factorial of {number} is {factorial(number)}")

    Multi Line Comment Using Triple Quoted Strings

    We can use triple-quoted strings (”’ or “””) to create multi-line comments. These strings are technically string literals but can be used as comments if they are not assigned to any variable or used in expressions.

    This pattern is often used for block comments or when documenting sections of code that require detailed explanations.

    Example

    Here, the triple-quoted string provides a detailed explanation of the “gcd” function, describing its purpose and the algorithm used −

    """
    This function calculates the greatest common divisor (GCD)
    of two numbers using the Euclidean algorithm. The GCD of
    two numbers is the largest number that divides both of them
    without leaving a remainder.
    """defgcd(a, b):while b:
    
      a, b = b, a % b
    return a result = gcd(48,18)print("The GCD of 48 and 18 is:", result)

    Using Comments for Documentation

    In Python, documentation comments, also known as docstrings, provide a way to incorporate documentation within your code. This can be useful for explaining the purpose and usage of modules, classes, functions, and methods. Effective use of documentation comments helps other developers understand your code and its purpose without needing to read through all the details of the implementation.

    Python Docstrings

    In Python, docstrings are a special type of comment that is used to document modules, classes, functions, and methods. They are written using triple quotes (”’ or “””) and are placed immediately after the definition of the entity they document.

    Docstrings can be accessed programmatically, making them an integral part of Pythons built-in documentation tools.

    Example of a Function Docstring

    defgreet(name):"""
       This function greets the person whose name is passed as a parameter.
    
       Parameters:
       name (str): The name of the person to greet
    
       Returns:
       None
       """print(f"Hello, {name}!")
    greet("Alice")

    Accessing Docstrings

    Docstrings can be accessed using the .__doc__ attribute or the help() function. This makes it easy to view the documentation for any module, class, function, or method directly from the interactive Python shell or within the code.

    Example: Using the .__doc__ attribute

    defgreet(name):"""
    
    This function greets the person whose name is passed as a parameter.
    Parameters:
    name (str): The name of the person to greet
    Returns:
    None
    """print(greet.__doc__)</pre>

    Example: Using the help() Function

    Open Compiler

    defgreet(name):"""
    
    This function greets the person whose name is passed as a parameter.
    Parameters:
    name (str): The name of the person to greet
    Returns:
    None
    """help(greet)</pre>
  • Operator Precedence

    Python Operator Precedence

    An expression may have multiple operators to be evaluated. The operator precedence defines the order in which operators are evaluated. In other words, the order of operator evaluation is determined by the operator precedence.

    If a certain expression contains multiple operators, their order of evaluation is determined by the order of precedence. For example, consider the following expression

    >>> a =2+3*5

    Here, what will be the value of a? – yes it will be 17 (multiply 3 by 5 first and then add 2) or 25 (adding 2 and 3 and then multiply with 5)? Pythons operator precedence rule comes into picture here.

    If we consider only the arithmetic operators in Python, the traditional BODMAS rule is also employed by Python interpreter, where the brackets are evaluated first, the division and multiplication operators next, followed by addition and subtraction operators. Hence, a will become 17 in the above expression.

    In addition to the operator precedence, the associativity of operators is also important. If an expression consists of operators with same level of precedence, the associativity determines the order. Most of the operators have left to right associativity. It means, the operator on the left is evaluated before the one on the right.

    Let us consider another expression:

    >>> b =10/5*4

    In this case, both * (multiplication) and / (division) operators have same level of precedence. However, the left to right associativity rule performs the division first (10/5 = 2) and then the multiplication (2*4 = 8).

    Python Operator Precedence Table

    The following table lists all the operators in Python in their decreasing order of precedence. Operators in the same cell under the Operators column have the same precedence.

    Sr.No.Operator & Description
    1(),[], {}Parentheses and braces
    2[index], [index:index]Subscription, slicing,
    3await xAwait expression
    4**Exponentiation
    5+x, -x, ~xPositive, negative, bitwise NOT
    6*, @, /, //, %Multiplication, matrix multiplication, division, floor division, remainder
    7+, –Addition and subtraction
    8<<, >>Left Shifts, Right Shifts
    9&Bitwise AND
    10^Bitwise XOR
    11|Bitwise OR
    12in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership tests and identity tests
    13not xBoolean NOT
    14andBoolean AND
    15orBoolean OR
    16if elseConditional expression
    17lambdaLambda expression
    18:=Walrus operator

    Python Operator Precedence Example

    a =20
    b =10
    c =15
    d =5
    e =0
    
    e =(a + b)* c / d       #( 30 * 15 ) / 5print("Value of (a + b) * c / d is ",  e)
    
    e =((a + b)* c)/ d     # (30 * 15 ) / 5print("Value of ((a + b) * c) / d is ",  e)
    
    e =(a + b)*(c / d);# (30) * (15/5)print("Value of (a + b) * (c / d) is ",  e)
    
    e = a +(b * c)/ d;#  20 + (150/5)print("Value of a + (b * c) / d is ",  e)

    When you execute the above program, it produces the following result −

    Value of (a + b) * c / d is  90.0
    Value of ((a + b) * c) / d is  90.0
    Value of (a + b) * (c / d) is  90.0
    Value of a + (b * c) / d is  50.0