Introduction_to_Python

Python is a commonly used programming language. The content in this and the linked pages is to provide a quick intro to Python programming language.

Illustration

# This is a sample python program
# Lines beginning with '#' are python comments
# Comments can also be the last part of any given side Eg. 
# Print 'Hello World'
print('Hello World')  # Rest of this line after '#' is  a comment

# Following code demonstrates multi-line comments. 
#     "Hello2" and "Hello3" will not be printed 
#      as those statements are commented out 
#      using three apostrophe as shown below.

print("Hello1")

'''   # Block comments begin
print("Hello2")
print("Hello3")
'''  # Block comments end
print("Hello4")
print("Hello5")
  • Variety of data types are supported in Python. Numeric Data types (int, float and complex), String data type and Boolean data type.
  • Type_Casting. Converting the type of a variable. type() function is used to find out the type of a data variable

Illustration

# This program demonstrates type casting
a = 5    # variable a is initialized with an int value 5
b = 5.0 # variable b is initialized with a float value 5.0
# variable a is int type; variable b is float type
# type() function is used find out the type of any object

# Printing the types of input variables 
print("Type of a is: ", type(a), "Type of b is:", type(b))
sum = a+b
# Printing the type of variable sum
print("Type of sum is: ",type(sum))

Illustration

# Get an integer number from user using input() function
N = input()
# Print the value N and type of N
# N will be of the type str
print("N = ", N,"Type of N is ", type(N))

# Convert N to an int type using the int() function
N = int(N)
print("After type conversion to int:")
print("N = ", N,"Type of N is ", type(N))

Illustration

# Get two numbers from user and add them
n1 = input("Enter first number: ")
n2 = input("Enter second number: ")

# Compute the sum of the two numbers and print

sum = n1+n2
print("type of n1 = ", type(n1), "type of n2 = ", type(n2))
print("type of sum = ", type(sum))
print("n1 = ", n1, "n2 = ", n2, "sum = ", sum)

# Convert n1 and n2 into integers using int() function
n1 = int(n1)
n2 = int(n2)

# Compute the sum of the two numbers after they are converted 
#      to int type and print

sum = n1+n2
print("After type conversion:")

print("type of n1 = ", type(n1), "type of n2 = ", type(n2))
print("type of sum = ", type(sum))
print("n1 = ", n1, "n2 = ", n2, "sum = ", sum)


Arithmetic Operators:
+ Addition
- Subtraction
* Multiplication
** Exponent Eg. 2**3 is 2 raised to power of 3
/ Division
// Floor Division Eg. 5//2 results in 2.0
% Remainder Eg. 5%2 results in 1

Comparison Operators: Results in True or False as results
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Logical Operator
and AND Operator. True if both values are True. Else False
or OR Operator. True if one of the values is True. Else False
not NOT Operator. Inverts the status. Unary Operator

Membership Operator
in True if an element is in the object (string, list)
not in True if an element is NOT in the object (string, list)
Eg. 'a' in "I am a string" will result in True
'am' in "I am a string" will result in True
'a' not in "I am a string" will result in False
Eg. list1 = [1,2,3,4]
1 in list1 results in True.
5 in list1 results in False
1 not in list1 results in False
5 not in list1 results in True
# Arithmetic operator Illustration
# Get a and b from user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
a_plus_b = a + b
b_minus_a = b - a
a_product_b = a * b
a_power_b  = a ** b
print ("a = ", a, "b = ", b, "a_plus_b= ", a_plus_b)
print ("a = ", a, "b = ", b, "b_minus_a= ", b_minus_a)
print ("a = ", a, "b = ", b, "a_product_b= ", a_product_b)
print ("a = ", a, "b = ", b, "a_power_b= ", a_power_b)

# Division
print ("a = ", a, "b = ", b, "a/b = ", a/b) 
print ("a = ", a, "b = ", b, "a//b = ", a//b)
print ("a = ", a, "b = ", b, "a%b = ", a%b)
# Comparison Operators
num1 = int(input("Enter num1:"))
num2 = int(input("Enter num2:"))
# < is less than operator. 
#    If LHS is less than RHS, the expression will result in True. 
#    Else, it will result in False.
print("num1:",num1, "num2: ", num2, num1 < num2)
# > greater than operator
print("num1:",num1, "num2: ", num2, num1 > num2)
# == equal to check operator
print("num1:",num1, "num2: ", num2, num1 == num2)
#Conditional Flow
# if
# if..else
# if..elif..else

num1 = int(input("Enter num1:"))
num2 = int(input("Enter num2:"))

#Control flow with only if
print("Control flow with only if statement")
if (num1 < num2):
    print("num1 is lesser than num2")

#Control flow with if and else statements
print("Control flow with if and else statements")
if (num1 < num2):
    print("num1 is lesser than num2")
else:
    print("num1 is not lesser than num2")
    
#Control flow with if, elif and else
print("Control flow with if,elif and else statements")
if (num1 < num2):
    print("num1 is lesser than num2")
elif (num1 > num2):
    print("num1 is greater than num2")
else:
    print("num1 is equal to num2")
# The following code illustrates a  loop using 'for' statement
# A function called range() generates a sequence of numbers
# Eg. range(5) generates a sequence of 5 numbers ie  0,1,2,3,4

# for loop using range
for i in range(5):
   print(i)
# This program illustrates a loop using 'for' statement 

# Let us assume the program needs to get 3 integer scores 
#    from the user and print each of the three scores

# Approach 1: Is there any issue here?
print("Executing Approach 1")
# Get three scores
for i in range(3):
    score = int(input("Enter the score: "))
# Print three scores
for i in range(3):
    print("The ",i,"th score is: ", score)

# Approach 2: 
print("Executing Approach 2")
# Get and print three scores 
for i in range(3):
    score = int(input("Enter the score: "))
    print("The ",i,"th score is: ", score)

Illustration of while loop alongwith break and continue statements

# The following code illustrates creating loop 
#     using while statement

# Approach 1
print("Executing Approach 1")
count = 0
while(count < 5):
    count = count + 1
    print(count, "Hi!")
    
# Approach 2
print("Executing Approach 2")
count = 0
while(1):
    count += 1
    print(count,"Hi!")
    if (count == 5):
        break

# Approach 3
print("Executing Approach 3")
count = 0
while(1):
    count = count + 1
    if(count == 3):
        continue
    print(count,"Hi!")
    if (count == 5):
        break
# Strings in Python

# Use "xxxx" for strings
str1 = "This is string1."
print(str1)

# Or use 'xxxx' for strings
str2 = 'This is string2.'
print(str2)

# Concatenate two strings
str3 = str1 + str2
print(str3)

# Print two strings; space is introduced between 
print(str1,str2)

# Empty String vs String with blanks
emp_str = ""
blank_str = "    "
print("emp_str is :"+emp_str+".")
print("blank_str is :"+blank_str+".")

Illustration

# Multiline strings
mult_line_string = """This is first line
This is second line
This is third line
"""
print(mult_line_string)

Illustration

# String Functions: len() and .upper() and .lower()
str1 = "I_Am_a_String"

# len() - Finds the length of a string
print("str1 is ",str1)
print("Length is ",len(str1))

# upper() - a function of the str object which 
#       converts the string to upper case
print("Upper Case: ", str1.upper())

# lower() - a function of the str object which 
#       converts the string to lower case
print("Lower Case: ", str1.lower())

Illustration

# Finding out presence of a character or 
#    a sequence of characters in a string

str1 = "I am a string"
print("str1 is: ",str1)
# Is 'a' in str1
result = 'a' in str1
print("'a' occurs in str1:", result)  # printing ' ' symbols

# Is 'am' in str1
result = 'am' in str1
print("'am' occurs in str1:", result)  # printing ' ' symbols

# Is 'z' in str1
result = 'z' in str1
print('"z" occurs in str1:', result) # printing " " symbols

# Is 'z' not in str1
result = 'z' not in str1
print('"z" does not occur in str1:', result) 
  • Lists: Lists help in managing variety of datasets. The below section illustrates some basic functionality (Creating a list, Appending elements, Inserting elements, Removing elements, pop() function to remove elements and len() function to count number of elements.

Creating a List in Python

# Creating a list of numbers
mylist = [5,10,15,20]
# Check the type  of the created list using type()
print(type(mylist))
# print the contents of the list
print(mylist)

#Output will look like below:
#     <class 'list'>
#     [5, 10, 15, 20]

Creating more lists..

# Creating a list of strings
mylistofnames = ["amar","akbar","antony"]
# print the contents of the list
#Output will be: ['amar', 'akbar', 'antony']
print(mylistofnames)       

# Creating a list consisting of both numbers and strings
mymixedlist = ["Ram", 18, "BBAH", "Rahim", 25, "MBA-TM"]
# Output will be: ['Ram', 18, 'BBAH', 'Rahim', 25, 'MBA-TM']
print(mymixedlist)  

Indexing of elements:

Lists contain elements of one or more types. The elements are ordered with an index starting from 0 ie. The first element in a list has an index 0. If a list has N elements, the indices range from 0 to N-1. Elements of a list can be accessed using the index.

# Create a list of strings
mylist = ["one", "two", "three", "four"]
# Find the number of elements in the list using len() function
print("mylist is: ",mylist)
print("Length of mylist = ", len(mylist))
# Read and print the elements of a list
N = len(mylist)
for i in range(N):
   print(i,mylist[i])

# Insert empty lines 
print()
print()

# Another way to iterate over the elements in a list
myscores = [52, 98, 100, 87, 77]
print("myscores: ", myscores)
print("Elements of myscores are: ")
for score in myscores:
    print(score)

Operation on lists: Create an empty list and append elements. append()

# Create an empty list and check the length
emptylist = []
print("Elements of emptylist are: ",emptylist)
print("Length of emptylist is: ",len(emptylist))

# Create an empty list and add elements
#     using append() function
mylist = []
mylist.append("one")
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

mylist.append("two")
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

mylist.append("three")
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

mylist.append("four")
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

Operation on lists: Removing first item of a certain value from the list. remove()

mylist = ["one", "two", "one", "three", "two", "four"]
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

# Remove the items with a value "two"
mylist.remove("two")
print("Elements of mylist after removing element 'two': ",mylist)
print("Length of mylist is: ",len(mylist))

Operations on lists: insert() can be used to insert an element in the list at a particular index.

# Usage of insert() function on a list
mylist = ["one", "two", "three", "five"]
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

# Insert "four" between elements "three" and "five" ie at index [3]
mylist.insert(3,"four")
print("Elements of mylist after insertion are: ",mylist)
print("Length of mylist after insertion is: ",len(mylist))

Operation on lists: pop() can be used to remove an item with a specified index from the list

mylist = ["one", "two", "three", "four"]
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

# Remove the item with index 2
mylist.pop(2)
print("Elements of mylist after pop(2) are: ",mylist)
print("Length of mylist is: ",len(mylist))

Operation on lists: use clear() to clear all elements in a list

# Clearing a list of all elements
mylist = ["one", "two", "three", "four"]
print("Elements of mylist are: ",mylist)
print("Length of mylist is: ",len(mylist))

mylist.clear()
print("Elements of cleared mylist are: ",mylist)
print("Length of cleared mylist is: ",len(mylist))

Swapping two variables

# Swapping two variables

# Swap using a temporary variable
a = 5
b = 10
print("Before swapping: ", "a = ", a, "b = ", b)

# Copy the value of variable a into temp
temp = a
# Copy the value of variable b into a
a = b
# temp contains the original value of a
#   copy temp to b
b = temp
print("After swapping: ", "a = ", a, "b = ", b)

Swapping two numeric variables without a temporary variable

# Swap two numeric variables without using a temporary variable
a = 5
b = 10
print("Before swapping: ", "a = ", a, "b = ", b)

# Store value of a in b by adding a to b
b = b+a
# Store value of b to a by subtracting a from current value of b 
a = b - a 
# Now a contains original value of b; 
#      and b contains the sum of (original value of b) and 
#          original value of a
# Subtract original value of b (which is current value of a) 
#      from current value of b and assign to b
b = b - a
print("After swapping: ", "a = ", a, "b = ", b)

Functions

Python Library Functions (Builtin): Refer List of Builtin Functions for details on the built in functions that are available.

User Defined Functions: Defining a Function using def statement

# Defining a Function in Python

def say_hello():
   print("Hello")

# Note the keyword def, name of the function and : symbol
# Indentation of the print statement indicates that 
#       the statement is part of the function definition.  
# Whenever the function is called, 
#       this statement will get executed.

Invoking (Calling) a Function

# Defining a Function in Python and Calling it

def say_hello():
   print("Hello")

# Calling the function

print("About to call the function say_hello()")
say_hello()
print("Returned back after execution of the function")
# Defining a Function in Python with multiple lines and Calling it

def say_hello_new():
   print("First_line")
   print("Second line")
   print("Third line")
   print("Hello!")

# Calling the function

print("About to call the function say_hello_new()")
say_hello_new()
print("Returned back after execution of the function")

Passing Inputs (Arguments) to the Function

# Defining a function to pass one argument (value) to it

def say_hello_one(name):
   print("Entered the function")
   print("Hello "+name)
 
# Calling the function
say_hello_one("Ambani")

# Defining a function to pass two arguments (values) to it

def say_hello_two(name1, name2):
   print("Entered the function")
   print("Hello "+name1+"!")
   print("Hello "+name2+"!")
 
# Calling the function
say_hello_two("Adani", "Ambani")

Returning Values from the Function using return statement

# Defining a function to pass one argument (value) to it and 
#      return one value
# Function name: area_of_square()
# Number of arguments: One
# Number of return values: One

def area_of_square(length_of_side):
   area = length_of_side * length_of_side
   return area

# Calling the function
side = 10
print("Side = ",side, "; Area =  ", area_of_square(side))

# Function name: find_larger(num1, num2)
# Function should return the number which is 
#      larger out of the two
# If the two arguments (numbers) are same, then the function 
#      will return a message 'The numbers are equal'

def find_larger(number1, number2):
   if (number1 > number2):
      print(number1, "is larger than", number2)
   elif (number2 > number1):
      print(number2, "is larger than", number1)
   else:
      print("The numbers are equal") 

# Calling the function

find_larger(5,10)
find_larger(20,5)
find_larger(5,5)

Defining empty function using pass statement (pass_statement):

# Defining a function without any code 
#     so that code can be added later

def myfunction():
   pass

# Calling the function
myfunction()  # Nothing gets done

Recursive functions: Recursive functions are those where the function itself is called from within the body of the function definition recursively. This is used in certain scenarios. A terminating condition should be included.

Illustration

# Recursive Function definition
def factorial(x):
    if(x == 0):
        return(1)
    if(x == 1):
        return(1)
    return(x*factorial(x-1))

# Calling factorial function for 5 values
for num in [0,1,2,3,4]:
    iteration = 0
    print()
    print("The factorial of", num, "is", factorial(num))
# Recursive Function Definition
# Added print statements to illustrate the flow better

def factorial(x):
    global iteration
    iteration = iteration + 1
    print("Iteration: ",iteration,"Called with x = ",x)
    if(x == 0):
        return(1)
    if(x == 1):
        return(1)
    return(x*factorial(x-1))
    
# Calling factorial function for 5 values
for num in [0,1,2,3,4]:
    iteration = 0
    print()
    print("The factorial of", num, "is", factorial(num))

Illustration of 3×3 Matrix Addition

# Addition of two 3 x 3 matrices

# Matrix A
A = [[5,10,15],[10,20,30],[20,40,60]]
print(A)
# Matrix B
B = [[2,3,4],[3,6,9],[4,8,12]]
print(B)
# Matrix Sum_A_B to hold the sum
Sum = [[0,0,0],[0,0,0],[0,0,0]]
print(Sum)

# For i = 0, 1, 2 and j = 0, 1, 2
#    sum(i,j) = a(i,j)+b(i,j)

# Start outer for loop to go through rows
for i in range(3):
    # Start inner for loop to go through columns in each row
    for j in range(3):
        Sum[i][j]=A[i][j]+B[i][j]
print("Sum of A and B:")
print(Sum)

Illustration of a simple calculator

while(1):
    print("Simple Calculator App")
    print("1: Add")
    print("2: Multiply")
    print("0: Exit Calculator")
    cmd = float(input("Enter your command: "))
    if cmd == 0.0:
        break
    match(cmd):
        case 1:
            n1 = float(input("Enter first number: "))
            n2 = float(input("Enter second number: "))
            print("n1 = ", n1, "n2 = ",n2, "sum = ",n1+n2)
        case 2:
            n1 = float(input("Enter first number: "))
            n2 = float(input("Enter second number: "))
            print("n1 = ", n1, "n2 = ",n2, "product = ",n1*n2)
        case 0: 
            print("Thank you for using Calculator App")
            exit
        case _:
            print("Enter a valid command (0/1/2)")
print("End")

References