While Loop Termination in Python
While Loop Termination in Python
syntax of elif:
statements are of 3 types: if(condition):
Statement1
Sequential statements elif(condition):
Selection control statements Statement2
else:
Loop control statements statement3
o/p:
Enter a number: 152 Example14 :Test a string is palindrome or not
Answer:
152 is not an Armstrong number string=input("Enter a string:")
if(string==string[::-1]):
Example11: Test a number is strong or not print("The string is a palindrome")
Program: else:
# Python Program to find Strong Number print("Not a palindrome")
Number = int(input(" Please Enter any Number: "))
Sum = 0 Example15 : Find GCD or 2 numbers
Temp = Number Answer:solution1
while(Temp > 0): # Python Program to find GCD of Two Numbers
Factorial = 1
i=1 a = float(input(" Please Enter the First Value a: "))……12
Reminder = Temp % 10 b = float(input(" Please Enter the Second Value b: "))……18
while(i <= Reminder):
Factorial = Factorial * i i=1
i=i+1 while(i <= a and i <= b):
print("\n Factorial of %d = %d" %(Reminder, Factorial)) if(a % i == 0 and b % i == 0):
Sum = Sum + Factorial gcd = i
Temp = Temp // 10 i=i+1
print("\n Sum of Factorials of a Given Number %d = %d" %(Number, print("\n HCF of {0} and {1} = {2}".format(a, b, gcd))
Sum))
solution2:
if (Sum == Number):
print(" %d is a Strong Number" %Number) num1 = float(input(" Please Enter the First Value Num1 : "))
else: num2 = float(input(" Please Enter the Second Value Num2 : "))
print(" %d is not a Strong Number" %Number)
o/p: a = num1
b = num2
Example12 :Test a number is palindrome or not
Program: while(num2 != 0):
n=int(input("Enter number:")) temp = num2
temp=n num2 = num1 % num2
rev=0 num1 = temp
while(n>0):
dig=n%10 gcd = num1
rev=rev*10+dig print("\n HCF of {0} and {1} = {2}".format(a, b, gcd))
n=n//10
if(temp==rev): Example16 : Generate Fibonacci series
print("The number is a palindrome!") Answer:
By - Murali Krishna Senapaty
# Program to display the Fibonacci sequence up to n-th term This is less like the for keyword in other programming languages, and works
nterms = int(input("How many terms? ")) more like an iterator method as found in other object-orientated programming
# first two terms languages.
n1, n2 = 0, 1 With the for loop we can execute a set of statements, once for each item in a list,
count = 0 tuple, set etc.
The syntax of for loop in python is given below.
# check if the number of terms is valid for iterating_var in sequence:
if nterms <= 0: statement(s)
print("Please enter a positive integer")
elif nterms == 1: Example
print("Fibonacci sequence upto",nterms,":") Print each fruit in a fruit list:
print(n1) fruits = ["apple", "banana", "cherry"]
else: for x in fruits:
print("Fibonacci sequence:") print(x)
while count < nterms:
nth = n1 + n2 ex:
print(nth) >>> # Measure some strings:
n1 = n2 ... words = ['cat', 'window', 'defenestrate']
n2 = nth >>> for w in words:
count += 1 ... print(w, len(w))
...
o/p:
How many terms? 7 ex:
Fibonacci sequence: tuple1=(1,2,3)
0 for item in tuple1:
1 print(item)
1
2 ex:
3 mylist1=[(1,2), (3,4), (5,6)]
5 for (a,b) in mylist:
8 print(a)
print(b)
o/p:
Example17: Print reverse of a number 1
Solution: 2
# Python Program to Reverse a Number using While loop 3
Number = int(input("Please Enter any Number: ")) 4
Reverse = 0 5
while(Number > 0): 6
Reminder = Number %10
Reverse = (Reverse *10) + Reminder Ex:
Number = Number //10 mylist1=[(1,2,3), (4,5,6), (7,8,9)]
print("\n Reverse of entered number is = %d" %Reverse) for a,b,c in mylist1:
print(b)
o/p:
Python For Loops 2
A for loop is used for iterating over a sequence 5
(that is either a list, a tuple, a dictionary, a set, or a string). 8
By - Murali Krishna Senapaty
i=1
Ex:
Dict1={‘K1’:100, ‘K2’:200, ‘K3’:300}
For i in dict1:
Print(i) num=int(input(“enter a no”))
o/p: for i in range(1,11):
‘K1’ print(%d X %d = %d”%(num,i,num*i))
‘K2’
‘K3’ o/p:
//here by default the keys will be printed as because in dictionary we iterate only 10X1 = 10
through keys 10X2 = 20
…..
Ex:
Dict1={‘K2’:1, ‘K2’:2, ‘K3’:3} Example4:
For i in dict1.item(): Suppose we have a list and we need to print items of it.
Print(i) mylist1=[1,2,3,4,5]
o/p: for i in mylist1:
(‘K1’,1) print(i)
(‘K2’,2) o/p:
(‘K3’,3) 1
2
Ex: 3
Dict1={‘K1’:1, ‘K2’:2, ‘K3’:3} 4
For key, value in dict1.item(): 5
Print(value)
o/p: Example5:
1 Suppose we have a list and we need to print items of it.
2 mylist1=[1,2,3,4,5]
3 for i in mylist1:
print(“hello”)
Or o/p:
d={‘K1’:1, ‘K2’:2, ‘K3’:3} hello
For x in d.values(): hello
Print(x) hello
o/p: hello
1 hello
2
3 Example6:
Suppose we have a list and we need to print even items of it.
Example2: mylist1=[1,2,3,4,5,6]
for i in range(1, 100): for i in mylist1:
print(i, end= ‘ ‘) If i%2==0:
print(i)
o/p: 1 2 …..99 o/p:
2
Example3: 4
generate multiplication table: 6
Example Example3:
Exit the loop when x is "banana", but this time the break comes before the print: Increment the sequence with 3 (default is 1):
fruits = ["apple", "banana", "cherry"] for x in range(2, 30, 3):
for x in fruits: print(x)
if x == "banana": o/p:
break 2
print(x) 5
8
The continue Statement 11
With the continue statement we can stop the current iteration of the loop, and 14
continue with the next: Etc
Example
Do not print banana: Ex4:
fruits = ["apple", "banana", "cherry"] for x in range(100,0,-5):
for x in fruits: print(x)
if x == "banana": o/p:
continue 100
print(x) 95
Etc
The range() Function
Ex5:using the range() for inputting values for a list.
To loop through a set of code a specified number of times, we can use the
List1(range(0,11,1))
range() function,
The range() function returns a sequence of numbers, starting value is 0 by
default, and increments by 1 (by default), and ends at a specified number. Enumerate(): it is used with any iterative control statement
Syntax: to represent the index count.
Range(starting value, last value, change in value) Ex:
word=”hello”
for i in enumerate(word):
Example1 print(i)
Using the range() function: o/p:
for x in range(6): (0,’h’)
print(x) (1, ‘e’)
Etc
Here Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
Zip(): the zip method is used with lists to combine multiple lists
The range() function defaults to 0 as a starting value, together.
however it is possible to specify the starting value by adding a parameter: Ex:
range(2, 6), Mylist1=[1,2,3]
which means values from 2 to 6 (but not including 6): Mylist2=[‘a’,’b’,’c’]
For item in zip(mylist1,mylist2):
Example2: Print(item)
Using the start parameter: o/p:
By - Murali Krishna Senapaty
(1, ‘a’) mylist
(2, ‘b’) o/p:
(3,’c’) [‘w’,’o’,’r’,’d’]
Note: the zip method can combine the lists as per the shortest list. Ex:
mylist=[x for x in range(1,11)]
Else in For Loop mylist
The else keyword in a for loop specifies a block of code to be executed
when the loop is finished: o/p:
Example [1,2,3,4,5,6,7,8,9,10]
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6): Ex: create a list having elements from 1 to n, where n is given as input
print(x) n=int(input(“enter a no”))
else: mylist=[x for x in range(1,n+1)]
print("Finally finished!") mylist
Here parameters are the arguments to be passed and they are optional. Ex2: a function to find absolute value.
return statement is optional. It is used to return a value. def absvalue(num):
The body statements are to be written with indenting. if num>=0:
Ex1: return num
else:
def fun(): return (-num)
print(“hello python”)
print(absvalue(-2))
def add(a,b): o/p:
c=a+b 2
By - Murali Krishna Senapaty
Scope and life time of variable: ex4:
c1=1
The variables can be local and global. def add():
Local variables: c=c+2
The local variables defined inside a function is not visible outside. print(c)
Hence they are having local scope. add()
The life time is also local. o/p:
error
Global variables:
A variable written outside having a global scope. ex5:
We can read these variables inside a function but we cannot change. c1=1
To get accessibility to change we need to use keyword global. def add():
Ex1: global c
def myfun(): c=c+2
X=10 print(c)
print(“values inside “,x) add()
print(c)
X=20 o/p:
myfun() 3
print(“value outside”,x) 3
ex2: Built in functions are the library functions which we are using
def fun(): such as: abs(), max(), min() etc.
global x
print(x) User defined functions are defined by programmer.
x=”hi” Parameters: Using these we pass input data to a function.
print(x) The parameters are actual parameters and formal parameters.
The actual parameters are the variables we represent in a function
x=”hello” calling statement.
fun() The formal parameters are the variables which
print(x) we represent in the function body definition. These variables receive
the input for the function.
o/p: In a function we can write any number of parameters separated by comma.
hello Ex1:
hi WAp to perform multiplication of 2 numbers.
hi def product(a,b): #here a and b are formal parameters
return (a*b)
ex3: x=int(input(“enter 1st no”))
c1=1 y=int(input(“enter 2nd no”))
def add(): print(“the product is “,product(x,y)) # here a and y are actual parameters
print(c) o/p:
add() enter 1st no 10
o/p: 1 enter 2nd no 20
By - Murali Krishna Senapaty
product is 200 ````````````````````````````````````````````
call by reference: In python we can define a function which can take variable no. of arguments.
================== They are 4 types:
in python all the functions are called by reference, 1) required arguments
i.e: all the changes made to the reference variable 2) default arguments
inside the function reverts back to the original variable 3) keyword arguments
outside. 4) arbitrary arguments
Note: the changes made to the immutable objects will not
reflect outside the function.
Required arguments or positional
++++++++++++++++++++++++++++++++++++++
Mutable vs Immutable Objects in Python
++++++++++++++++++++++++++++++++++++++
arguments:
‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’
The mutable objects can change their state or contents It is the general way of writing the function and calling the function. Here the
and immutable objects can’t change their state or content. arguments are required at the time of function call. If they are not provided
properly during calling statement then it leads to error.
Immutable Objects : These are of in-built types Ex:
like int, float, bool, string, unicode, tuple def fun(name):
msg=”hello ”+name
Mutable Objects : These are of type list, dict, set return msg
name=input(“enter your name”)
print(fun(name))
Ex1: using mutable object :list o/p:
def update(list1): enter your name alok
list1.append(22) hello alok
list1.append(33)
print(“inside”,list1) questions:
list1=[10,30,40,50] 1) Write a program to find greatest among 3 numbers.
update(list1) 2) Write a program to find sum of 10 numbers given.
print(“outside”,list1) 3) Write a program to find LCM, GCD of 2 numbers.
o/p:
inside 10,30,40,50,20,30
outside 10,30,40,50,20,30
default arguments:
the function arguments can have default values in python. We can provide a
default value to an argument by using assignment operator =
Ex:using immutable object :string
def upstr(str1):
Ex:
str1=str1+”how are you”
def greet(name, msg=”good morning”):
print(“inside”,str1)
print(“hello”,name+msg)
str1=”hi”
greet(“kate”)
upstr(str1)
greet(“bruce”,”how are you”)
print(“outside”,str)
o/p:
o/p:
hello kate good morning
inside hi how are you
hello bruce how are you
outside hi
note:
variable function arguments:
By - Murali Krishna Senapaty
Example
when a parameter having a default value then during function call it is
optional to input for the parameter.
when we provide a value then it sill over write the default Value.
In a function any no. of parameters can have default value. But they need def myfun(*args):
to be written as per right side as possible. return sum(args*5)
myfun(40,60,100)
It means if we write: o/p:
def greet(msg=”good morning”,name): 1000
print(“hello”,msg+name)
o/p:
error myfun(40,60,100, 1,34)
o/p:
python allows to change the position of the arguments.
Ex1: greet(name=”bruce”,msg=”hello”)
Ex2: greet(msg=”hello”, name=”bruce”)
Example
Introduction to *args and **kwargs in myfun(*args):
print(args)
Python myfun(40,60,100,1,34)
In Python, we can pass a variable number of arguments to a o/p:
function using special symbols. There are two special symbols: 40,60,100,1,34
1. *args (Arbitrary Arguments)
2. **kwargs (Keyword Arguments) Example
def my_function(*kids):
Python *args print("The youngest child is " + kids[2])
Example
# Python program to illustrate **kwargs for
Example
# variable number of keyword arguments with def myfunc(*args, **kwargs):
# one extra argument. print(args)
print(kwargs)
def myFun(arg1, **kwargs): myfunc(10,20,30, fruit=’orange’, food=’eggs’, animal=’dog’)
for key, value in kwargs.items(): o/p:
print ("%s == %s" %(key, value)) (10,20,30)
{ ‘fruit’:’orange’, ‘food’: ‘eggs’, ‘animal’:’dog’}
# Driver code
myFun("Hi", first ='murali', mid ='for',last='krishna') Example
Output: def myfunc(*args, **kwargs):
last == krishna print(“I like {} {}”.format(args[0], kwargs[‘food’]))
myfunc(10,20,30, fruit=’apples’, food=’eggs’, dryfruit=’dates’)
mid == for o/p:
I like 10 eggs
first == murali
Example Exercises:
1) Write a program to create an UDF which tests a number is prime or not.
def myfun(**kwargs): 2) Write a program to generate Fibonacci series using UDF
if “fruit” in kwargs: 3) Write a program to store 10 no.s into a list. Find largest and smallest
print(“my fruit of choice is element present using UDF.
{}”.format(kwargs[‘fruit’]))
else:
print(“I did not find any fruit”) Python recursion:
myfun(fruit=”apple”)
When a function calls itself then the process is called recursion.
myfun(fruit=”apple”, veggie=”lettuce”)
o/p: advantages:
my fruit of choice is apple. 1) It makes the code look clean
my fruit of choice is apple. 2) Complex program can be broken into simple sub programs
o/p: Syntax
ex3: find GCD of 2 no.s using recursion. lambda arguments : expression
def gcd(x.y):
if x>y:
small=y Example
else:
small=x Add 10 to argument a, and return the result:
for i in range(1,small+1):
if((x%i==0) and (y%i==0)): x = lambda a : a + 10
gcd=i
print(x(5))
return gcd
Example Solution:
def compare(text):
By - Murali Krishna Senapaty
wordlist=text.split() check(20,5)
print(wordlist) o/p:
first=wordlist[0] False
second=wordlist[1] True
return (first[0]==second[0]) True
4) Write a function that capitalize the 1st and 4th letters of a name.
compare(“Hello Friend”) Solution:
o/p:
def funcap(name):
[‘Hello’, ‘Friend’]
False firstletter=name[0]
inbetween=name[1:3]
Compare(“Hello Hina”) fourthletter=name[3]
o/p: rest=name[4:]
[‘Hello’, ‘Hina’] return
True firstletter.upper()+inbetween+fourthletter.upper()+rest
OR funcap(“oldmcdonald”)
def compare(text): o/p:
wordlist=text.split() OldMcdonald
return (wordlist[0][0]==wordlist[1][0]) Or
compare(“Hello Hina”)
def funcap(name):
o/p: Firstpart=name[:3]
[‘Hello’, ‘Hina’] Secondpart=name[3:]
True
return
Note: Here the sentence’s each word is stored in to a list called wordlist and then firstpart.capitalize()+secondpart.capitalize()
we can refer to each word with index i.e: word index & character index. Funcap(“oldmcdonald”)
We can store all words in lower case or in upper case as: Note : Capitalize() :it makes capital for 1st letter.
o/p:
wordlist=text.lower().split() OldMcdonald
Or
wordlist=text.upper().split()
Ex:To capitalize each word in a sentence:
3) Write a program to create a function which returns True if sum of 2 numbers is def cap(sentence):
20, or any of two numbers is 20 wordlist=sentence.split()
Solution: for word in wordlist:
def check(n1, n2): word.capitalize()
return (((n1+n2)==20) or (n1==20 or n2==20)) print(wordlist)
check(10,5) cap(“hello friends, how are you”)
check(18,2)
By - Murali Krishna Senapaty
o/p: o/p:
Hello Friends, How Are You a+b+c
ex4:
Given a list of integers. Return True if the array contains 3 next to a 3 value
Example: somewhere.
myDict = {"name": "John", "country": "Norway"} For example
mySeparator = "TEST" check(1,3,3,1) = TRUE
x = mySeparator.join(myDict) check(1,3,1,3) = FALSE
print(x) Program:
def check(numberlist):
Example: for i in range(0, len(numberlist)-1):
mylist=[‘a’,’b’,’c’] if numberlist[i]==3 and
‘+’.join(mylist)
By - Murali Krishna Senapaty
numberlist[i+1]==3: 1) Return the sum of numbers from a list, but when the sequence is in
return True between 6 to 9 then ignore that portion for adding.
Ex: list1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
return False 2) Write a program that takes a list of integers and return TRUE if it contains
007 in order.
check([1,3,3]) Ex: check(1,2,0,0,4,7,6,0,0,7]
o/p: true
o/p: Ex: check(1,2,0,0,4,7,6,0,7,0]
True o/p: false
3) Write a program to input a paragraph and find how many palindromes
OR exist in it.
Ex3:
Enter a sentence and print only that words who have even number of characters.
def find(x):
if(len(x)%2==0): filter():
print(x) The filter() function returns an iterator were the items are
filtered through a function to test if the item is accepted or
str1=input("enter sentence") not.
list1=str1.split() The filter() function extracts elements from an iterable (list,
result=list(map(find,list1)) tuple etc.) for which a function returns True .
or Example
list(map(lambda x: x**2,list1)) list1=[1,2,3,4,5,6]
list(filter(lambda x: x%2==0,list1))
Example o/p:
def find(sentence): [2,4,6]
wordlist=sentence.split()
Example
By - Murali Krishna Senapaty
def find(x): print(“Hi”+name)
return(len(x)%2==0)
str1=input("enter:") To import this module or file in another program we can do in two ways:
list1=str1.split() 1) Using import statement
result=list(filter(find,list1)) 2) Using from -import statement
print(result)
Using import:
o/p: Ex:
enter:good morning import file1
['good'] name=input(“enter ur name”)
file1.msg(name)
#we can call any function of module file1 with reference to the module name.
Example
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] Using From – import:
Instead of accessing the whole file if we need to access only some functions then
# a function that returns True if letter is vowel we can use from import.
def filter_vowels(letter): Ex:
vowels = ['a', 'e', 'i', 'o', 'u'] from file1 import msg
return True if letter in vowels else False name=input(“enter ur name”)
msg(name)
filtered_vowels = filter(filter_vowels, letters)
ex2:
# converting to tuple create a module func.py
vowels = tuple(filtered_vowels) def add(x,y):
print(vowels) return x+y
def sub(x,y):
Example return x-y
def mul(x,y):
numbers = [1, 2, 3, 4, 5, 6, 7] return x*y
# the lambda function returns True for even numbers 2nd program: p1.py
even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers) from func import add
print(add(10,20))
# converting to list
even_numbers = list(even_numbers_iterator) to rename a module:
print(even_numbers) python provides flexibility to import a module with another name or alias name.
syntax:
import <module name> as <alternate name>
Python modules: ex:
import calculate as calc
A module can be defined as a python program file which contains python code a=int(input(“enter 1st no”))
that includes functions, classes, variables etc. This file will have extension .py b=int(input(“enter 2nd no”))
print(“sum=”, calc.sum(a,b))
Ex: create a python module file1.py
---------------------------------------------- o/p:
def msg(name): enter 1st no 5
By - Murali Krishna Senapaty
enter 2nd no 10
sum=15 In python we can treat these folders as packages and the .py files as modules
inside package.
python module search: To treat a directory as package, we need to create and store a file
while importing a module python search for it in the _ _init_ _.py inside of it. This file can be an empty file.
1) Current directory.
2) In the directory specified in PYTHONPATH environment variable. Ex: create main directory game as package. It contains sub directories sound,
It is available at: image, levels as sub packages. We need to add _ _init_ _.py in each folder.
This PC, properties, advanced system setting, Environment variables,
3) Default directory of installation. To import a module as can write with dot operator as:
import game.level.start
Where start.py is the module.
If start.py contains a function difficulty.py() then we can access as:
Reloading a module: game.level.start.difficulty(2)
if we need to access the module func.py by again updating some more features
and functions, then to import we need the help of reload function, as import is not otherwise we can import in another way as:
applicable for 2nd time. from game.level import start
For it we need to write: start.difficulty(2)
import importlib
importlib.reload(func)
Built-in Functions:
Global Variables across Python modules: The Python built-in functions are defined as the functions whose functionality is
We can create a module to hold global variables. pre-defined in Python.
Ex:
Create config.py file and store: dir() :
a=0 we can use this built in function to see all the names that are defined inside a
b=”empty” module in sorted manner.
Ex:
create update.py file and change global variable data: >>>dir(mod1)
import config Where mod1.py is the module exist.
config.a=10
config.b=”alphabets” abs() :
The python abs() function is used to return the absolute value of a number. It
now create main.py file and test: takes only one argument, a number whose absolute value is to be returned.
import config
import update # integer number
print(config.a) integer = -20
print(config.b) print('Absolute value of -40 is:', abs(integer))
when we run main.py file the output will be: # floating number
10 floating = -20.83
Alphabets print('Absolute value of -40.83 is:', abs(floating))
Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
Python package:
When we develop project we write any files and stores in different folders and sub all() :
folders and then access them.
By - Murali Krishna Senapaty
This function accepts an iterable object (such as list, dictionary, etc.). It returns If no parameter is passed, then by default it returns False.
true if all items in passed iterable are true. Otherwise, it returns False. If the So, passing a parameter is optional.
iterable object is empty, the all() function returns True.
Example It can return one of the two values.
It returns True if the parameter or value passed is True.
# all values true It returns False if the parameter or value passed is False.
k = [1, 3, 4, 6] Here are few cases, in which Python’s bool() method returns false. Except these all other
print(all(k)) values return True.
Output: If a False value is passed.
True
If None is passed.
# all values false If an empty sequence is passed, such as (), [], ”, etc
k = [0, False] If Zero is passed in any numeric type, such as 0, 0.0 etc
print(all(k)) If an empty mapping is passed, such as {}.
Output: If Objects of Classes having __bool__() or __len()__ method,
False returning 0 or False
# Python program to illustrate
# built-in method bool()
# one false value
k = [1, 3, 7, 0] # Returns False as x is False
print(all(k)) x = False
Output: print(bool(x))
False o/p:
false
# one true value
k = [0, False, 5] # Returns True as x is True
x = True
print(all(k)) print(bool(x))
Output: o/p:
False True
listIter = iter(list)
any() :
function returns true if any item in an iterable is true. Otherwise, it returns False.
# prints '1'
print(next(listIter))
Example
L = [4, 3, 2, 0]
# prints '2'
print(any(L))
print(next(listIter))
o/p:
true
# prints '3'
L = [0, False]
print(next(listIter))
print(any(L))
o/p:
# prints '4'
false
print(next(listIter))
L = [0, False, 5]
# prints '5'
print(any(L))
print(next(listIter))
o/p:
Output:
True 1
2
L = [] 3
print(any(L)) 4
5
o/p:
false
next() :
Python eval() Function This function is used to fetch next item from the collection. It takes two
arguments, i.e., an iterator and a default value, and returns an element.
The python eval() function parses the expression passed to it and runs python
This method calls on iterator and throws an error if no item is present. To avoid
expression(code) within the program.
the error, we can set a default value.
Python next() Function Example
Ex1:
By - Murali Krishna Senapaty
number = iter([256, 32, 82]) # Creating iterator (5, 1)
# Calling function
item = next(number) hex() :
# Displaying result This function is used to generate hex value of an integer argument. It takes an
print(item) integer argument and returns an integer converted into a hexadecimal string.
# second item Ex1:
item = next(number) >>> hex(15)
print(item) o/p:
'0xf'
len() : Ex2:
function is used to return the length (the number of items) of an object. >>> hex(14)
Python len() Function Example o/p:
strA = 'Python' '0xe'
print(len(strA))
Output: sorted() :
6
This function is used to sort elements. By default, it sorts elements in an
ascending order but can be sorted in descending also. It takes four arguments
chr() : and returns a collection in sorted order. In the case of a dictionary, it sorts only
function is used to get a string representing a character which points to a Unicode keys, not values.
code integer. For example, chr(97) returns the string 'a'.
ex: Example
>>>chr(65) >>> str="javatpoint"
o/p: >>> sorted(str)
‘A’ o/p:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
ord():
This function returns ascii value for a character. oct() :
Ex: This function is used to get an octal value of an integer number. This method
>>>ord(‘A’) takes an argument and returns an integer converted into an octal string. It throws
o/p: an error TypeError, if argument type is other than an integer.
65 Python oct() function Example
# Calling function
complex() : val = oct(10)
This function is used to convert numbers or string into a complex number. This # Displaying result
method takes two optional parameters and returns a complex number. The first print("Octal value of 10:",val)
parameter is called a real and second as imaginary parts. Output:
Ex: Octal value of 10: 0o12
>>> complex(1,2)
o/p:
(1+2j) pow() :
This function is used to compute the power of a number. It returns x to the power
divmod() : of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e.
This function is used to get remainder and quotient of two numbers. This function (x, y) % z.
takes two numeric arguments and returns a tuple. Both arguments are required Python pow() function Example
and numeric. # positive x, positive y (x**y)
Ex: print(pow(4, 2))
>>> divmod(21,4)
o/p: # negative x, positive y
By - Murali Krishna Senapaty
print(pow(-4, 2)) print(type(Dict))
Output:
<class 'list'>
<class 'dict'>
reversed() :
This function returns the reversed iterator of the given sequence.
Python reversed() function Example
# for string
String = 'Java'
print(list(reversed(String)))
# for tuple
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))
# for range
Range = range(8, 12)
print(list(reversed(Range)))
# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))
Output:
['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]
round() :
This function rounds off the digits of a number and returns the floating point
number.
Example
# for floating point
print(round(10.8))
# even choice
print(round(6.2))
Output:
11
6
type() :
It returns the type of the specified object if a single argument is passed to the
type() built in function.
Example
List = [4, 5]
print(type(List))