Python Programming
Please leave a remark at the bottom of each page with your useful suggestion.
Table of Contents
- Python Introduction
- Python Startup
- Python Examples Program Collection 1
- Python Examples Program Collection 2
- Python Examples Program Collection 3
- Python Examples Program Collection 4
- Python Examples Program Collection 5
- Python Examples Program Collection 6
- Python Examples Program Collection 7
- Python Examples Program Collection 8
Python String capitalize()
sentence = "i love PYTHON"
# converts first character to uppercase and others to lowercase
capitalized_string = sentence.capitalize()
print(capitalized_string)
# Output: I love python
Python String capitalize()
Example 1: Python capitalize()
sentence = "python is AWesome."
# capitalize the first character
capitalized_string = sentence.capitalize()
print(capitalized_string)
Python String casefold()
text = "pYtHon"
# convert all characters to lowercase
lowercased_string = text.casefold()
print(lowercased_string)
# Output: python
Python String casefold()
Example 1: Python casefold()
text = "PYTHON IS FUN"
# converts text to lowercase
print(text.casefold())
Python String center()
sentence = "Python is awesome"
# returns the centered padded string of length 24
new_string = sentence.center(24, '*')
print(new_string)
# Output: ***Python is awesome****
Python String center()
Example 1: Python center()
sentence = "Python is awesome"
# returns the centered padded string of length 20
new_string = sentence.center(20, '$')
print(new_string)
Python String center()
Example 2: center() with Default Argument
text = "Python is awesome"
# returns padded string by adding whitespace up to length 24
new_text = text.center(24)
print("Centered String: ", new_text)
Python chr()
print(chr(97))
# Output: a
print(chr(98))
# Output: b
Python chr()
Example 1: Python chr() with Integer Numbers
print(chr(97))
print(chr(65))
print(chr(1200))
Python chr()
Example 2: chr() with Out of Range Integer
print(chr(-1000))
print(chr(1114113))
Python chr()
Example 3: chr() with Non-Integer Arguments
print(chr('Ronald'))
print(chr('Lupin'))
Python classmethod()
class Student:
marks = 0
def compute_marks(self, obtained_marks):
marks = obtained_marks
print('Obtained Marks:', marks)
# convert compute_marks() to class method
Student.print_marks = classmethod(Student.compute_marks)
Student.print_marks(88)
# Output: Obtained Marks: 88
Python classmethod()
Example 1: Create class method using classmethod()
class Person:
age = 25
def printAge(cls):
print('The age is:', cls.age)
# create printAge class method
Person.printAge = classmethod(Person.printAge)
Person.printAge()
Python classmethod()
Example 2: Create factory method using class method
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
person = Person('Adam', 19)
person.display()
person1 = Person.fromBirthYear('John', 1985)
person1.display()
Python classmethod()
Example 3: How the class method works for the inheritance?
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
class Man(Person):
sex = 'Male'
man = Man.fromBirthYear('John', 1985)
print(isinstance(man, Man))
man1 = Man.fromFathersAge('John', 1965, 20)
print(isinstance(man1, Man))
Python Set clear()
# set of prime numbers
primeNumbers = {2, 3, 5, 7}
# clear all elements
primeNumbers.clear()
print(primeNumbers)
# set()
Python Set clear()
Example 1: Python Set clear()
# set of vowels
vowels = {'a', 'e', 'i', 'o', 'u'}
print('Vowels (before clear):', vowels)
# clear vowels
vowels.clear()
print('Vowels (after clear):', vowels)
Python Set clear()
Example 2: clear() Method with a String Set
# set of strings
names = {'John', 'Mary', 'Charlie'}
print('Strings (before clear):', names)
# clear strings
names.clear()
print('Strings (after clear):', names)
Python compile()
codeInString = 'a = 8\nb=7\nsum=a+b\nprint("sum =",sum)'
codeObject = compile(codeInString, 'sumstring', 'exec')
exec(codeObject)
# Output: 15
Python compile()
Example: Python compile()
codeInString = 'a = 5\nb=6\nmul=a*b\nprint("mul =",mul)'
codeObject = compile(codeInString, 'sumstring', 'exec')
exec(codeObject)
# Output: mul = 30
Python complex()
Example 1: How to create a complex number in Python?
z = complex(2, -3)
print(z)
z = complex(1)
print(z)
z = complex()
print(z)
z = complex('5-9j')
print(z)
Python Set copy()
numbers = {1, 2, 3, 4}
# copies the items of numbers to new_numbers
new_numbers = numbers.copy()
print(new_numbers)
# Output: {1, 2, 3, 4}
Python Set copy()
Example 1: Python Set copy()
names = {"John", "Charlie", "Marie"}
# items of names are copied to new_names
new_names = names.copy()
print('Original Names: ', names)
print('Copied Names: ', new_names)
Python Tuple count()
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# counts the number of i's in the tuple
count = vowels.count('i')
print(count)
# Output: 2
Python Tuple count()
Example 1: Python Tuple count()
# tuple of numbers
numbers = (1, 3, 4, 1, 6 ,1 )
# counts the number of 1's in the tuple
count = numbers.count(1)
print('The count of 1 is:', count)
# counts the number of 7's in the tuple
count = numbers.count(7)
print('The count of 7 is:', count)
Python Tuple count()
Example 2: count() to Count List and Tuple Elements Inside Tuple
# tuple containing list and tuples
random = ('a', ('a', 'b'), ('a', 'b'), [3, 4])
# count element ('a', 'b')
count = random.count(('a', 'b'))
print("The count of tuple ('a', 'b') is:", count)
# count element [3, 4]
count = random.count([3, 4])
print("The count of list [3, 4] is:", count)
Python delattr()
Example 1: How delattr() works?
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)
delattr(Coordinate, 'z')
print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)
# Raises Error
print('z = ',point1.z)
Python dict()
Example 1: Create Dictionary Using keyword arguments only
numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))
empty = dict()
print('empty =', empty)
print(type(empty))
Python dict()
Example 2: Create Dictionary Using Iterable
# keyword argument is not passed
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)
# keyword argument is also passed
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)
# zip() creates an iterable in Python 3
numbers3 = dict(zip(['x', 'y', 'z'], [1, 2, 3]))
print('numbers3 =',numbers3)
Python dict()
Example 3: Create Dictionary Using Mapping
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)
# you don't need to use dict() in above code
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)
# keyword argument is also passed
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)
Python Set difference()
# sets of numbers
A = {1, 3, 5, 7, 9}
B = {2, 3, 5, 7, 11}
# returns items present only in set A
print(A.difference(B))
# Output: {1, 9}
Python Set difference()
Example 1: Python Set difference()
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
# equivalent to A-B
print(A.difference(B))
# equivalent to B-A
print(B.difference(A))
Python Set difference_update()
# sets of numbers
A = {1, 3, 5, 7, 9}
B = {2, 3, 5, 7, 11}
# computes A - B and updates A with the resulting set
A.difference_update(B)
print('A = ', A)
# Output: A = {1, 9}
Python Set difference_update()
Example: Python difference_update()
A = {'a', 'c', 'g', 'd'}
B = {'c', 'f', 'g'}
print('A before (A - B) =', A)
A.difference_update(B)
print('A after (A - B) = ', A)
Python dir()
number = [12]
# returns valid attributes of the number list
print(dir(number))
# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Python dir()
Example 1: Python dir() with a List
number1 = [1, 2, 3]
#dir with a filled list
print(dir(number1))
number2 = [ ]
# dir() with an empty list
print(dir(number2))
Python dir()
Example 2: dir() with a Set
number = {12, 15, 18, 21}
# dir() with a filled set
print(dir(number))
number1 =[ ]
# dir() with an empty set
print(dir(number1))
Python dir()
Example 3: dir() with a Tuple
number = (21, 10, 81, 25)
#dir with a filled tuple
print(dir(number))
number1 =[]
# dir() with an empty tuple
print(dir(number1))
Python dir()
Example 4: dir() with a User-defined Object
class Person:
def __dir__(self):
return ['age', 'name', 'salary']
teacher = Person()
print(dir(teacher))
Python Set discard()
numbers = {2, 3, 4, 5}
# removes 3 and returns the remaining set
result = numbers.discard(3) )
print(result)
# Output: numbers = {2, 4, 5}
Python Set discard()
Example 1: Python Set discard()
numbers = {2, 3, 4, 5}
# discards 3 from the set
numbers.discard(3)
print('Set after discard:', numbers)
Python Set discard()
Example 2: Python Set discard with a non-existent item()
numbers = {2, 3, 5, 4}
print('Set before discard:', numbers)
# discard the item that doesn't exist in set
numbers.discard(10)
print('Set after discard:', numbers)
Python divmod()
# returns the quotient and remainder of 8/3
result = divmod(8, 3)
print('Quotient and Remainder = ',result)
# Output: Quotient and Remainder = (2, 2)
Python divmod()
Example 1: Python divmod() with Integer Arguments
# divmod() with integer arguments
print('divmod(8, 3) = ', divmod(8, 3))
# divmod() with integer arguments
print('divmod(3, 8) = ', divmod(3, 8))
# divmod() with integer arguments
print('divmod(5, 5) = ', divmod(5, 5))
Python divmod()
Example 2: Python divmod() with Float Arguments
# divmod() with float arguments
print('divmod(8.0, 3) = ', divmod(8.0, 3))
# divmod() with float arguments
print('divmod(3, 8.0) = ', divmod(3, 8.0))
# divmod() with float arguments
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))
# divmod() with float arguments
print('divmod(2.6, 0.5) = ', divmod(2.6, 0.5))
Python divmod()
Example 3: Python divmod() with Non-Numeric Arguments
# divmod() with string arguments
a = divmod("Jeff", "Bezos")
print('The divmod of Jeff and Bezos is = ', a)
Python String encode()
title = 'Python Programming'
# change encoding to utf-8
print(title.encode())
# Output: b'Python Programming'
Python String encode()
Example 1: Encode to Default Utf-8 Encoding
# unicode string
string = 'pythön!'
# print string
print('The string is:', string)
# default encoding to utf-8
string_utf = string.encode()
# print result
print('The encoded version is:', string_utf)
Python String encode()
Example 2: Encoding with error parameter
# unicode string
string = 'pythön!'
# print string
print('The string is:', string)
# ignore error
print('The encoded version (with ignore) is:', string.encode("ascii", "ignore"))
# replace error
print('The encoded version (with replace) is:', string.encode("ascii", "replace"))
Python String endswith()
message = 'Python is fun'
# check if the message ends with fun
print(message.endswith('fun'))
# Output: True
Python String endswith()
Example 1: endswith() Without start and end Parameters
text = "Python is easy to learn."
result = text.endswith('to learn')
# returns False
print(result)
result = text.endswith('to learn.')
# returns True
print(result)
result = text.endswith('Python is easy to learn.')
# returns True
print(result)
Python String endswith()
Example 2: endswith() With start and end Parameters
text = "Python programming is easy to learn."
# start parameter: 7
# "programming is easy to learn." string is searched
result = text.endswith('learn.', 7)
print(result)
# Both start and end is provided
# start: 7, end: 26
# "programming is easy" string is searched
result = text.endswith('is', 7, 26)
# Returns False
print(result)
result = text.endswith('easy', 7, 26)
# returns True
print(result)
Python String endswith()
Example 3: endswith() With Tuple Suffix
text = "programming is easy"
result = text.endswith(('programming', 'python'))
# prints False
print(result)
result = text.endswith(('python', 'easy', 'java'))
#prints True
print(result)
# With start and end parameter
# 'programming is' string is checked
result = text.endswith(('is', 'an'), 0, 14)
# prints True
print(result)
Python enumerate()
languages = ['Python', 'Java', 'JavaScript']
enumerate_prime = enumerate(languages)
# convert enumerate object to list
print(list(enumerate_prime))
# Output: [(0, 'Python'), (1, 'Java'), (2, 'JavaScript')]
Python enumerate()
Example 1: How enumerate() works in Python?
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)
print(type(enumerateGrocery))
# converting to list
print(list(enumerateGrocery))
# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))
Python enumerate()
Example 2: Looping Over an Enumerate object
grocery = ['bread', 'milk', 'butter']
for item in enumerate(grocery):
print(item)
print('\n')
for count, item in enumerate(grocery):
print(count, item)
print('\n')
# changing default start value
for count, item in enumerate(grocery, 100):
print(count, item)
Python eval()
number = 9
# eval performs the multiplication passed as argument
square_number = eval('number * number')
print(square_number)
# Output: 81
Python eval()
Example 1: How eval() works in Python
x = 1
print(eval('x + 1'))
Python eval()
Example 2: Practical Example to Demonstrate Use of eval()
# Perimeter of Square
def calculatePerimeter(l):
return 4*l
# Area of Square
def calculateArea(l):
return l*l
expression = input("Type a function: ")
for l in range(1, 5):
if (expression == 'calculatePerimeter(l)'):
print("If length is ", l, ", Perimeter = ", eval(expression))
elif (expression == 'calculateArea(l)'):
print("If length is ", l, ", Area = ", eval(expression))
else:
print('Wrong Function')
break
Python eval()
Example 3: Passing empty dictionary as globals parameter
from math import *
print(eval('dir()', {}))
# The code will raise an exception
print(eval('sqrt(25)', {}))
Python eval()
Example 4: Making Certain Methods available
from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))
Python exec()
program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)
# Output: Sum = 15
Python exec()
Example 1: Python exec()
program = 'a = 5\nb=10\nprint("Sum =", a+b)'
exec(program)
Python exec()
Example 2: exec() With a Single Line Program Input
# get an entire program as input
program = input('Enter a program:')
# execute the program
exec(program)
Python String expandtabs()
Example 1: expandtabs() With no Argument
str = 'xyz\t12345\tabc'
# no argument is passed
# default tabsize is 8
result = str.expandtabs()
print(result)
Python String expandtabs()
Example 2: expandtabs() With Different Argument
str = "xyz\t12345\tabc"
print('Original String:', str)
# tabsize is set to 2
print('Tabsize 2:', str.expandtabs(2))
# tabsize is set to 3
print('Tabsize 3:', str.expandtabs(3))
# tabsize is set to 4
print('Tabsize 4:', str.expandtabs(4))
# tabsize is set to 5
print('Tabsize 5:', str.expandtabs(5))
# tabsize is set to 6
print('Tabsize 6:', str.expandtabs(6))
Python List extend()
# create a list
prime_numbers = [2, 3, 5]
# create another list
numbers = [1, 4]
# add all elements of prime_numbers to numbers
numbers.extend(prime_numbers)
print('List after extend():', numbers)
# Output: List after extend(): [1, 4, 2, 3, 5]
Python List extend()
Example 1: Using extend() Method
# languages list
languages = ['French', 'English']
# another list of language
languages1 = ['Spanish', 'Portuguese']
# appending language1 elements to language
languages.extend(languages1)
print('Languages List:', languages)
Python List extend()
Example 2: Add Elements of Tuple and Set to List
# languages list
languages = ['French']
# languages tuple
languages_tuple = ('Spanish', 'Portuguese')
# languages set
languages_set = {'Chinese', 'Japanese'}
# appending language_tuple elements to language
languages.extend(languages_tuple)
print('New Language List:', languages)
# appending language_set elements to language
languages.extend(languages_set)
print('Newer Languages List:', languages)
Python filter()
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# returns True if number is even
def check_even(number):
if number % 2 == 0:
return True
return False
# Extract elements from the numbers list for which check_even() returns True
even_numbers_iterator = filter(check_even, numbers)
# converting to list
even_numbers = list(even_numbers_iterator)
print(even_numbers)
# Output: [2, 4, 6, 8, 10]
Python filter()
Example 1: Working of filter()
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
# a function that returns True if letter is vowel
def filter_vowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u']
return True if letter in vowels else False
filtered_vowels = filter(filter_vowels, letters)
# converting to tuple
vowels = tuple(filtered_vowels)
print(vowels)
Python filter()
Example 2: Using Lambda Function Inside filter()
numbers = [1, 2, 3, 4, 5, 6, 7]
# the lambda function returns True for even numbers
even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers)
# converting to list
even_numbers = list(even_numbers_iterator)
print(even_numbers)
Python filter()
Example 3: Using None as a Function Inside filter()
# random list
random_list = [1, 'a', 0, False, True, '0']
filtered_iterator = filter(None, random_list)
#converting to list
filtered_list = list(filtered_iterator)
print(filtered_list)
Python String find()
message = 'Python is a fun programming language'
# check the index of 'fun'
print(message.find('fun'))
# Output: 12
Python String find()
Example 1: find() With No start and end Argument
quote = 'Let it be, let it be, let it be'
# first occurance of 'let it'(case sensitive)
result = quote.find('let it')
print("Substring 'let it':", result)
# find returns -1 if substring not found
result = quote.find('small')
print("Substring 'small ':", result)
# How to use find()
if (quote.find('be,') != -1):
print("Contains substring 'be,'")
else:
print("Doesn't contain substring")
Python String find()
Example 2: find() With start and end Arguments
quote = 'Do small things with great love'
# Substring is searched in 'hings with great love'
print(quote.find('small things', 10))
# Substring is searched in ' small things with great love'
print(quote.find('small things', 2))
# Substring is searched in 'hings with great lov'
print(quote.find('o small ', 10, -1))
# Substring is searched in 'll things with'
print(quote.find('things ', 6, 20))
Python float()
int_number = 25
# convert int to float
float_number = float(int_number)
print(float_number)
# Output: 25.0
Python float()
Example 1: How float() works in Python?
# for integers
print(float(10))
# for floats
print(float(11.22))
# for string floats
print(float("-13.33"))
# for string floats with whitespaces
print(float(" -24.45\n"))
# string float error
print(float("abc"))
Python float()
Example 2: float() for infinity and Nan(Not a number)?
# for NaN
print(float("nan"))
print(float("NaN"))
# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))
Python String format()
Example 1: Basic formatting for default, positional and keyword arguments
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
Python String format()
Example 2: Simple number formatting
# integer arguments
print("The number is:{:d}".format(123))
# float arguments
print("The float number is:{:f}".format(123.4567898))
# octal, binary and hexadecimal format
print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12))
Python String format()
Example 3: Number formatting with padding for int and floats
# integer numbers with minimum width
print("{:5d}".format(12))
# width doesn't work for numbers longer than padding
print("{:2d}".format(1234))
# padding for float numbers
print("{:8.3f}".format(12.2346))
# integer numbers with minimum width filled with zeros
print("{:05d}".format(12))
# padding for float numbers filled with zeros
print("{:08.3f}".format(12.2346))
Python String format()
Example 4: Number formatting for signed numbers
# show the + sign
print("{:+f} {:+f}".format(12.23, -12.23))
# show the - sign only
print("{:-f} {:-f}".format(12.23, -12.23))
# show space for + sign
print("{: f} {: f}".format(12.23, -12.23))
Python String format()
Example 5: Number formatting with left, right and center alignment
# integer numbers with right alignment
print("{:5d}".format(12))
# float numbers with center alignment
print("{:^10.3f}".format(12.2346))
# integer left alignment filled with zeros
print("{:<05d}".format(12))
# float numbers with center alignment
print("{:=8.3f}".format(-12.2346))
Python String format()
Example 6: String formatting with padding and alignment
# string padding with left alignment
print("{:5}".format("cat"))
# string padding with right alignment
print("{:>5}".format("cat"))
# string padding with center alignment
print("{:^5}".format("cat"))
# string padding with center alignment
# and '*' padding character
print("{:*^5}".format("cat"))
Python String format()
Example 7: Truncating strings with format()
# truncating strings to 3 letters
print("{:.3}".format("caterpillar"))
# truncating strings to 3 letters
# and padding
print("{:5.3}".format("caterpillar"))
# truncating strings to 3 letters,
# padding and center alignment
print("{:^5.3}".format("caterpillar"))
Python String format()
Example 8: Formatting class members using format()
# define Person class
class Person:
age = 23
name = "Adam"
# format age
print("{p.name}'s age is: {p.age}".format(p=Person()))
Python String format()
Example 9: Formatting dictionary members using format()
# define Person dictionary
person = {'age': 23, 'name': 'Adam'}
# format age
print("{p[name]}'s age is: {p[age]}".format(p=person))
Python String format()
Example 10: Dynamic formatting using format()
# dynamic string format template
string = "{:{fill}{align}{width}}"
# passing format codes as arguments
print(string.format('cat', fill='*', align='^', width=5))
# dynamic float format template
num = "{:{align}{width}.{precision}f}"
# passing format codes as arguments
print(num.format(123.236, align='<', width=8, precision=2))
Python String format()
Example 11: Type-specific formatting with format() and overriding __format__() method
import datetime
# datetime formatting
date = datetime.datetime.now()
print("It's now: {:%Y/%m/%d %H:%M:%S}".format(date))
# complex number formatting
complexNumber = 1+2j
print("Real part: {0.real} and Imaginary part: {0.imag}".format(complexNumber))
# custom __format__() method
class Person:
def __format__(self, format):
if(format == 'age'):
return '23'
return 'None'
print("Adam's age is: {:age}".format(Person()))
Python String format()
Example 12: __str()__ and __repr()__ shorthand !r and !s using format()
# __str__() and __repr__() shorthand !r and !s
print("Quotes: {0!r}, Without Quotes: {0!s}".format("cat"))
# __str__() and __repr__() implementation for class
class Person:
def __str__(self):
return "STR"
def __repr__(self):
return "REPR"
print("repr: {p!r}, str: {p!s}".format(p=Person()))
Python String format_map()
Example 1: How format_map() works?
point = {'x':4,'y':-5}
print('{x} {y}'.format_map(point))
point = {'x':4,'y':-5, 'z': 0}
print('{x} {y} {z}'.format_map(point))
Python String format_map()
Example 2: How format_map() works with dict subclass?
class Coordinate(dict):
def __missing__(self, key):
return key
print('({x}, {y})'.format_map(Coordinate(x='6')))
print('({x}, {y})'.format_map(Coordinate(y='5')))
print('({x}, {y})'.format_map(Coordinate(x='6', y='5')))
Python Dictionary fromkeys()
# keys for the dictionary
alphabets = {'a', 'b', 'c'}
# value for the dictionary
number = 1
# creates a dictionary with keys and values
dictionary = dict.fromkeys(alphabets, number)
print(dictionary)
# Output: {'a': 1, 'c': 1, 'b': 1}
Python Dictionary fromkeys()
Example 1: Python Dictionary fromkeys() with Key and Value
# set of vowels
keys = {'a', 'e', 'i', 'o', 'u' }
# assign string to the value
value = 'vowel'
# creates a dictionary with keys and values
vowels = dict.fromkeys(keys, value)
print(vowels)
Python Dictionary fromkeys()
Example 2: fromkeys() without Value
# list of numbers
keys = [1, 2, 4 ]
# creates a dictionary with keys only
numbers = dict.fromkeys(keys)
print(numbers)
Python Dictionary fromkeys()
Example 3: fromkeys() To Create A Dictionary From Mutable Object
# set of vowels
keys = {'a', 'e', 'i', 'o', 'u' }
# list of number
value = [1]
vowels = dict.fromkeys(keys, value)
print(vowels)
# updates the list value
value.append(2)
print(vowels)
Python frozenset()
Example 1: Working of Python frozenset()
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())
# frozensets are immutable
fSet.add('v')
Python Dictionary get()
marks = {'Physics':67, 'Maths':87}
print(marks.get('Physics'))
# Output: 67
Python Dictionary get()
Example 1: How does get() work for dictionaries?
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
# value is not provided
print('Salary: ', person.get('salary'))
# value is provided
print('Salary: ', person.get('salary', 0.0))
Python getattr()
class Student:
marks = 88
name = 'Sheeran'
person = Student()
name = getattr(person, 'name')
print(name)
marks = getattr(person, 'marks')
print(marks)
# Output: Sheeran
# 88
Python getattr()
Example 1: How getattr() works in Python?
class Person:
age = 23
name = "Adam"
person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)
Python getattr()
Example 2: getattr() when named attribute is not found
class Person:
age = 23
name = "Adam"
person = Person()
# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))
# when no default value is provided
print('The sex is:', getattr(person, 'sex'))
Python globals()
print(globals())
Python globals()
Example: Python globals()
age = 23
globals()['age'] = 25
print('The age is:', age)
Python hasattr()
class Person:
age = 23
name = "Adam"
person = Person()
print("Person's age:", hasattr(person, "age"))
print("Person's salary:", hasattr(person, "salary"))
# Output:
# Person's age: True
# Person's salary: False
Python hasattr()
Example: Python hasattr()
class Car:
brand = "Ford"
number = 7786
car = Car()
print("The car class has brand:", hasattr(Car, "brand"))
print("The car class has specs: ", hasattr(Car, "specs"))