Python Programming

Please leave a remark at the bottom of each page with your useful suggestion.


Table of Contents

  1. Python Introduction
  2. Python Startup
  3. Python Examples Program Collection 1
  4. Python Examples Program Collection 2
  5. Python Examples Program Collection 3
  6. Python Examples Program Collection 4
  7. Python Examples Program Collection 5
  8. Python Examples Program Collection 6
  9. Python Examples Program Collection 7
  10. Python Examples Program Collection 8

Python hash()

text = 'Python Programming'
# compute the hash value of text hash_value = hash(text)
print(hash_value) # Output: -966697084172663693

Python hash()

Example 1: How hash() works in Python?

# hash for integer unchanged
print('Hash for 181 is:', hash(181))
# hash for decimal
print('Hash for 181.23 is:',hash(181.23))
# hash for string
print('Hash for Python is:', hash('Python'))

Python hash()

Example 3: hash() for Custom Objects by overriding __hash__()

class Person:
    def __init__(self, age, name):
        self.age = age
        self.name = name
    def __eq__(self, other):
        return self.age == other.age and self.name == other.name
def __hash__(self): print('The hash is:') return hash((self.age, self.name))
person = Person(23, 'Adam') print(hash(person))

Python hex()

Example 1: How hex() works?

number = 435
print(number, 'in hex =', hex(number))
number = 0
print(number, 'in hex =', hex(number))
number = -34
print(number, 'in hex =', hex(number))
returnType = type(hex(number))
print('Return type from hex() is', returnType)

Python hex()

Example 2: Hexadecimal representation of a float

number = 2.5
print(number, 'in hex =', float.hex(number))
number = 0.0
print(number, 'in hex =', float.hex(number))
number = 10.5
print(number, 'in hex =', float.hex(number))

Python id()

a = 5
b = 6
sum = a + b
# id of sum variable
print("The id of sum is", id(sum))
# Output: The id of sum is 9789312

Python id()

Example 1: Python id()

# id of 5
print("id of 5 =", id(5))
a = 5
# id of a
print("id of a =", id(a))
b = a
# id of b
print("id of b =", id(b))
c = 5.0
# id of c
print("id of c =", id(c))

Python id()

Example 2: id() with Classes and Objects

class Food:
    banana = 15
dummyFood = Food()
# id of the object dummyFood print("id of dummyFoo =", id(dummyFood))

Python id()

Example 3: id() with Sets

fruits = {"apple", "banana", "cherry", "date"}
# id() of the set fruits print("The id of the fruits set is", id(fruits))

Python id()

Example 4: id() with Tuples

vegetables = ("asparagus", "basil", "cabbage")
# id() with vegetable print("The id of the vegetables set is", id(vegetables))

Python Tuple index()

# tuple containing vowels
vowels = ('a', 'e', 'i', 'o', 'u')
# index of 'e' in vowels index = vowels.index('e')
print(index) # Output: 1

Python Tuple index()

Example 1: Python Tuple index()

# tuple containing vowels
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# index of 'e' in vowels index = vowels.index('e')
print('Index of e:', index)
# index of the first 'i' is returned index = vowels.index('i')
print('Index of i:', index)

Python Tuple index()

Example 2: index() throws an error if the specified element is absent in the Tuple

# tuple containing numbers
numbers = (0, 2, 4, 6, 8, 10)
# throws error since 3 is absent in the tuple index = numbers.index(3)
print('Index of 3:', index)

Python Tuple index()

Example 3: index() With Start and End Parameters

# alphabets tuple
alphabets = ('a', 'e', 'i', 'o', 'g', 'l', 'i', 'u')
# returns the index of first 'i' in alphabets
index = alphabets.index('i') 
print('Index of i in alphabets:', index)
# scans 'i' from index 4 to 7 and returns its index index = alphabets.index('i', 4, 7)
print('Index of i in alphabets from index 4 to 7:', index)

Python input()

name = input("Enter your name: ")
print(name) # Output: # Enter your name: James # James

Python input()

Example 1: How input() works in Python?

# get input from user
inputString = input()
print('The inputted string is:', inputString)

Python input()

Example 2: Get input from user with a prompt

# get input from user
inputString = input('Enter a string:')
print('The inputted string is:', inputString)

Python List insert()

# create a list of vowels
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 (4th position) vowel.insert(3, 'o')
print('List:', vowel) # Output: List: ['a', 'e', 'i', 'o', 'u']

Python List insert()

Example 1: Inserting an Element to the List

# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]
# insert 11 at index 4 prime_numbers.insert(4, 11)
print('List:', prime_numbers)

Python List insert()

Example 2: Inserting a Tuple (as an Element) to the List

mixed_list = [{1, 2}, [5, 6, 7]]
# number tuple
number_tuple = (3, 4)
# inserting a tuple to the list mixed_list.insert(1, number_tuple)
print('Updated List:', mixed_list)

Python int()

# returns the integer representation of the binary string 1010 print("For 1010, int is:", int("1010", 2))
# Output: For 1010, int is: 10

Python int()

Example 1: Python int() with a Single Argument

# int() with an integer value
print("int(123) is:", int(123))
# int() with a floating point value
print("int(123.23) is:", int(123.23))
# int() with a numeric-string value
print("int('123') is:", int("123"))

Python int()

Example 2: int() with Two Arguments

# converting a binary to integer with int()
print("For 0b101, int is:", int("0b101", 2))
# converting a binary to integer with int())
print("For 0o16, int is:", int("0o16", 8))
# converting a binary to integer with int()
print("For 0xA, int is:", int("0xA", 16))

Python Set intersection()

A = {2, 3, 5}
B = {1, 3, 5}
# compute intersection between A and B print(A.intersection(B))
# Output: {3, 5}

Python Set intersection()

Example 1: Python Set intersection()

A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
print(B.intersection(A))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))

Python Set intersection()

More Examples

A = {100, 7, 8}
B = {200, 4, 5}
C = {300, 2, 3}
D = {100, 200, 300}
print(A.intersection(D))
print(B.intersection(D))
print(C.intersection(D))
print(A.intersection(B, C, D))

Python Set intersection_update()

A = {1, 2, 3, 4}
B = {2, 3, 4, 5}
# updates set A with the items common to both sets A and B A.intersection_update(B)
print('A =', A) # Output: A = {2, 3, 4}

Python Set intersection_update()

Example: Python Set intersection_update()

A = {1, 2, 3, 4}
B = {2, 3, 4, 5, 6}
C = {4, 5, 6, 9, 10}
# performs intersection between A, B and C and updates the result to set A A.intersection_update(B, C)
print('A =', A) print('B =', B) print('C =', C)

Python String isalnum()

# string contains either alphabet or number 
name1 = "Python3"
print(name1.isalnum()) #True
# string contains whitespace name2 = "Python 3"
print(name2.isalnum()) #False

Python String isalnum()

Example 1: Python isalnum()

# contains either numeric or alphabet
string1 = "M234onica"
print(string1.isalnum()) # True
# contains whitespace string2 = "M3onica Gell22er"
print(string2.isalnum()) # False
# contains non-alphanumeric character string3 = "@Monica!"
print(string3.isalnum()) # False

Python String isalnum()

Example 2: isalnum() in if..else Statement

text = "Python#Programming123"
# checks if all the characters are alphanumeric if text.isalnum() == True:
print("All characters of string are alphanumeric.") else: print("All characters are not alphanumeric.")

Python String isalpha()

Example 1: Working of isalpha()

name = "Monica"
print(name.isalpha())
# contains whitespace
name = "Monica Geller"
print(name.isalpha())
# contains number
name = "Mo3nicaGell22er"
print(name.isalpha())

Python String isalpha()

Example 1: Working of isalpha()

name = "MonicaGeller"
if name.isalpha() == True:
   print("All characters are alphabets")
else:
    print("All characters are not alphabets.")

Python String isdecimal()

Example 1: Working of isdecimal()

s = "28212"
print(s.isdecimal())
# contains alphabets
s = "32ladk3"
print(s.isdecimal())
# contains alphabets and spaces
s = "Mo3 nicaG el l22er"
print(s.isdecimal())

Python String isdecimal()

Example 2: String Containing digits and Numeric Characters

s = '23455'
print(s.isdecimal())
#s = '²3455'
s = '\u00B23455'
print(s.isdecimal())
# s = '½'
s = '\u00BD'
print(s.isdecimal())

Python String isdigit()

str1 = '342'
print(str1.isdigit())
str2 = 'python'
print(str2.isdigit())
# Output: True # False

Python String isdigit()

Example 1: Working of isdigit()

s = "28212"
print(s.isdigit())
# contains alphabets and spaces s = "Mo3 nicaG el l22er"
print(s.isdigit())

Python String isdigit()

Example 2: String Containing digits and Numeric Characters

s = '23455'
print(s.isdigit())
#s = '²3455' # subscript is a digit s = '\u00B23455'
print(s.isdigit())
# s = '½' # fraction is not a digit s = '\u00BD'
print(s.isdigit())

Python Set isdisjoint()

A = {1, 2, 3, }
B = {4, 5, 6}
# checks if set A and set B are disjoint print(A.isdisjoint(B))
# Output: True

Python Set isdisjoint()

Example 1: Python Set disjoint()

A = {1, 2, 3}
B = {4, 5, 6}
C = {6, 7, 8}
print('A and B are disjoint:', A.isdisjoint(B)) print('B and C are disjoint:', B.isdisjoint(C))

Python Set isdisjoint()

Example 2: isdisjoint() with Other Iterables as Arguments

# create a set A
A = {'a', 'e', 'i', 'o', 'u'}
# create a list B
B = ['d', 'e', 'f']
# create two dictionaries C and D 
C = {1 : 'a', 2 : 'b'}
D = {'a' : 1, 'b' : 2}
# isdisjoint() with set and list
print('A and B are disjoint:', A.isdisjoint(B))
# isdisjoint() with set and dictionaries
print('A and C are disjoint:', A.isdisjoint(C))
print('A and D are disjoint:', A.isdisjoint(D))

Python String isidentifier()

Example 1: How isidentifier() works?

str = 'Python'
print(str.isidentifier())
str = 'Py thon'
print(str.isidentifier())
str = '22Python'
print(str.isidentifier())
str = ''
print(str.isidentifier())

Python String isidentifier()

Example 2: More Example of isidentifier()

str = 'root33'
if str.isidentifier() == True:
  print(str, 'is a valid identifier.')
else:
  print(str, 'is not a valid identifier.')
  
str = '33root'
if str.isidentifier() == True:
  print(str, 'is a valid identifier.')
else:
  print(str, 'is not a valid identifier.')
  
str = 'root 33'
if str.isidentifier() == True:
  print(str, 'is a valid identifier.')
else:
  print(str, 'is not a valid identifier.')



Write Your Comments or Suggestion...