0% found this document useful (0 votes)
8 views20 pages

Unit 3 Built-In Functions, Data Types, and Operators

data types in python

Uploaded by

upendra maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views20 pages

Unit 3 Built-In Functions, Data Types, and Operators

data types in python

Uploaded by

upendra maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

In [ ]:

Python Data Types


Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and
variables are instances (object) of these classes.

The following are the standard or built-in data types in Python:


1. Numeric (i.e. Integer, float and complex number)

2. Sequence Type (Strings, List and Tuple)

3. Boolean (True, False)

4. Set

5. Dictionary

6. Binary Types

In [1]: # we can use type() to find type of data type

a=25;
print(type(a))

<class 'int'>

In [5]: # we can find the memory address of variable a, where it is stored


# built-in function id() is used for this purpose

a=25
id(a)

2127243668528
Out[5]:

1. Example of Numeric Data type


In [13]: # example of Numeric type
# lets start some variable
a=5
b=3.5
c=2+2j
d="i love python"
print(type(a))
print(type(b))
print(type(c))
print(type(d))

# lets do some operation


print(a+7)
print(a+b)
print(a+c)

<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
12
8.5
(7+2j)

2. Sequence Data type in Python (String)


In [2]: # let's create some String data type

string1='Hello world' # we have created string variable using single quote


string2="Python is awesome " # we have created string variable using double quote
string2='''Python is awesom''' # we have created string variable using tripple quote
string3='''i love python
but there are other languages
for mechanical MATLAB is also good''' # We can define multi-line string literals by usi

print(string1)
print(string2)
print(string3)
print(type(string2))

Cell In[2], line 4


string2="Python is awesome
^
SyntaxError: EOL while scanning string literal

2. Sequence Data type in Python (List)


Lists are just an ordered collection of data. It is very flexible as the items in a list do not
need to be of the same type.

Lists in Python can be created by just placing the sequence inside the square brackets [
].

In [16]: # Example of a list


list1=[4,5,8,101] # all are numbers
list2=[4,5+10j,8.09,101] # number + complex number + fractions
list3=[4,'escape','how are you',7j] # number + strings
print(list1)
print(list2)
print(list3)

# from above example it is clear that list can consist of any data type

[4, 5, 8, 101]
[4, (5+10j), 8.09, 101]
[4, 'escape', 'how are you', 7j]

2. Sequence Data type in Python (Tuple)


Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot be
modified after it is created. It is represented by a tuple class.

In Python, tuples are created by placing a sequence of values separated by a ‘comma’


with or without the use of parentheses for grouping the data sequence. Tuples can
contain any number of elements and of any datatype (like strings, integers, lists, etc.).
In [17]: tuple1=('python','c++',85,75,4.2,'program')
print(tuple1)

('python', 'c++', 85, 75, 4.2, 'program')

3. Boolean Data Type in Python


Data type with one of the two built-in values, True or False.

In [21]: a=5
print(a==7-2)
print(a==8-2)

# lets see class type of these boolean

print(type(a==7-2))
print(type(a==8-2))

True
False
<class 'bool'>
<class 'bool'>

4. Set Data Type in Python


a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.

Set items cannot be accessed by referring to an index, since sets are unordered the
items has no index. But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in the keyword.

In [23]: set1=set([8,7,5,4,8,8,7,5])
set2=set("python is fun")
print(set1)
print(set2)

{8, 4, 5, 7}
{'p', 'n', 'y', 'h', 'i', ' ', 'o', 'f', 'u', 's', 't'}

5. Dictionary Data Type in Python


A dictionary in Python is an unordered collection of data values, used to store data
values like a map, unlike other Data Types that hold only a single value as an element, a
Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it
more optimized. Each key-value pair in a Dictionary is separated by a colon : , whereas
each key is separated by a ‘comma’.

In Python, a Dictionary can be created by placing a sequence of elements within curly {}


braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be
duplicated, whereas keys can’t be repeated and must be immutable.

In [26]: Dict = {1: 'Vijay', 2: 'Dinanath', 3: 'Chauhan'}


print(Dict)

# In order to access the items of a dictionary refer to its key name. Key can be used in
print(Dict[1])
print(Dict[3])

{1: 'Vijay', 2: 'Dinanath', 3: 'Chauhan'}


Vijay
Chauhan

In [ ]:

Python Operators
Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical
and arithmetic operations.

Types of Operators in Python


1. Arithmetic Operators

2. Comparison Operators

3. Logical Operators

4. Bitwise Operators

5. Assignment Operators

6. Identiy Operators and Membership Operators

1. Arithmetic Operators
Operators Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

% Modulus: returns the remainder when the first operand is divided by the second x%y

** Power: Returns first raised to power second x ** y

In [3]: a=5
a+=3
print(a)

In [30]: # example of Arithmatic Operators


a=9
b=2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a//b)
print(a%b)
print(a**b)

11
7
18
4.5
4
1
81

2.Comparison Operators
Operator Description Syntax

> Greater than: True if the left operand is greater than the right x>y

< Less than: True if the left operand is less than the right x<y

== Equal to: True if both operands are equal x == y

!= Not equal to – True if operands are not equal x != y

>= Greater than or equal to True if the left operand is greater than or equal to the right x >= y

<= Less than or equal to True if the left operand is less than or equal to the right x <= y

Students should remember that. = is an assignment operator and ==


comparison operator.

In [32]: # Example of comparision operators in Python

x=25
y=30

print(a>b)
print(a<b)
print(a==b)
print(a!=b)
print(a>=b)
print(a<=b)

True
False
False
True
True
False

3.Logical Operators
Operator Description Syntax

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if the operand is false not x

In [7]: # Logical operator


1 and 0 # this is only true if both are true
Out[7]: 0

In [2]: 1 and 1
1
Out[2]:

In [3]: 0 or 1

1
Out[3]:

In [4]: 0 or 0
0
Out[4]:

In [5]: not 1
False
Out[5]:

In [6]: not 5
False
Out[6]:

In [36]: # example of logical operator


a=20
b=15
# and
print(a<30 and a>b)
print(a<30 and a>50)

# or
print(a<30 or a<b)
print(a<5 or a>50)

# not
print(a<30 and a>b)
print(not(a<30 and a>b))

True
False
True
False
True
False

4.Bitwise Operators
Operator Description Syntax

& Bitwise AND x&y

verticle line Bitwise OR

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

In [37]: # Example of bitwise operator


a = 10
b = 4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

0
14
-11
14
2
40

5.Assignment Operators
Operator Description Syntax

= Assign the value of the right side of the expression to the left side operand x=y+z

+= Add AND: Add right-side operand with left-side operand and then assign to left operand a+=b a=a+b

-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b a=a-b

*= Multiply AND: Multiply right operand with left operand and then assign to left operand a=b a=ab

/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b a=a/b

Modulus AND: Takes modulus using left and right operands and assign the result to left
%= a%=b a=a%b
operand

Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to
//= a//=b a=a//b
left operand

Exponent AND: Calculate exponent(raise power) value using operands and assign value to
**= a=b a=ab
left operand

&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b

^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b

>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b

a <<= b a= a
<<= Performs Bitwise left shift on operands and assign value to left operand
<< b

In [38]: # Example of assignment operator


a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

10
20
10
100
102400
6 Identity Operators and Membership Operators
In Python, is and is not are the identity operators both are used to check
if two values are located on the same part of the memory. Two variables
that are equal do not imply that they are identical.
Operator Description

is True if the operands are identical

is not True if the operands are not identical

In [39]: # Example of Identity Operators in Python

a = 10
b = 20
c = a

print(a is not b)
print(a is c)

True
True

In [17]: list1=["one","two","three"]
list2=["one","two","three"]
print(id(list1))
print(id(list2))
print(list1 is list2)
print(list1 is not list2) # reference comaprison (is & is not)
print(list1 == list2) # content comparison (==)

1883756003584
1883756013888
False
True
True

7. Membership Operators
We can use Membership operators to check whether the given object
present in the given collection.(It may be String,List,Set,Tuple or Dict)
Operator Description

in True if True if the given object present in the specified Collection

not in True if the given object not present in the specified Collection

In [18]: # Example1 of Membership Operators


x="hello learning Python is very easy!!!"
print('h' in x)
print('d' in x)
print('d' not in x)
print('python' in x) # case sensitivity
print('Python' in x)

True
False
True
False
True

In [19]: # Example2 of Membership Operators


list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1)
print("tunny" in list1)
print("tunny" not in list1)

True
False
True

8. Ternary Operator or conditional operator


1. If the operator operates on only one operand, we will call such operator as unary operator. For eg:, !a.
2. If the operator operates on Two operands, we will call such operator as binary operator. For eg:, a + b.
3. If the operator operates on Three operands, we will call such operator as Ternary operator.

Syntax:

x = firstValue if condition else secondValue

If condition is True then firstValue will be considered else secondValue


will be considered.
In [9]: a,b=23,43 # a =23 b = 43
c = "Palak Paneer" if a>b else "Gobhi Manchurian"
print(c)

Gobhi Manchurian

In [10]: # Read two integer numbers from the keyboard and print minimum value using ternary opera
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)

Enter First Number:15


Enter Second Number:25
Minimum Value: 15

In [13]: # Nesting of ternary operator is possible.


# Program for finding minimum of 3 numbers using nesting of ternary operators
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
min= a if a<b and a<c else b if b<c else c
print("Minimum Value:",min)

Enter First Number:45


Enter Second Number:85
Enter Third Number:75
Minimum Value: 45

In [14]: a=int(input("Enter First Number:"))


b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
max=a if a>b and a>c else b if b>c else c
print("Maximum Value:",max)

Enter First Number:45


Enter Second Number:75
Enter Third Number:95
Maximum Value: 95

Assume that there are two numbers, x and y, whose values to be read
from the keyboard, and print the following outputs based on the values
of x and y.
case 1: If both are equal, then the output is : Both numbers are equal
case 2: If first number is smaller than second one, then the output is: First Number is Less than Second
Number
case 3: If the firts number is greater than second number, then the output is : First Number Greater than
Second Number

In [15]: a=int(input("Enter First Number:"))


b=int(input("Enter Second Number:"))
print("Both numbers are equal" if a==b else "First Number is Less than Second Number"
if a<b else "First Number Greater than Second Number")

Enter First Number:45


Enter Second Number:45
Both numbers are equal

In [ ]:

In [ ]:

In [ ]:

In [ ]:

Functions in Python
In [ ]:

Python Functions is a block of statements that return the specific task.


The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code
contained in it over and over again.

Some Benefits of Using Functions


Increase Code Readability
Increase Code Reusability

There are two types of function in Python


1. Built-in library function: These are Standard functions in Python that are available to use.
2. User-defined function: We can create our own functions based on our requirements.
Let's see some built in functions
1. String Formatting functions
Operator Description

len(string) # Returns the length of the string

lower() # converts uppercase alphabates into lowercase.

upper() # converts lowercase alphabates into uppercase

capitalize() # first character of every sentence is capitalized

title() # First character of all words are capitalized

rstrip() # To remove blank spaces present at end of the string (i.e.,right hand side)

lstrip() # To remove blank spaces present at the beginning of the string (i.e.,left hand side)

strip() # To remove spaces both sides

In [9]: text_1="Hey! Python is Fun and easy"


text_2="Hellow world"

# let's use above functions


print("**************************** len()***********************************************
print(len(text_1))
print(len(text_2))

**************************** len()****************************************************
27
12

In [10]: print("**************************** lower()*********************************************


print(text_1.lower())
print(text_2.lower())

**************************** lower()****************************************************
hey! python is fun and easy
hellow world

In [11]: print("**************************** upper()*********************************************


print(text_1.upper())
print(text_2.upper())

**************************** upper()****************************************************
HEY! PYTHON IS FUN AND EASY
HELLOW WORLD

In [12]: print("**************************** capitalize()****************************************


print(text_1.capitalize())
print(text_2.capitalize())

**************************** capitalize()***********************************************
*****
Hey! python is fun and easy
Hellow world

In [13]: print("**************************** title()*********************************************


print(text_1.title())
print(text_2.title())

**************************** title()****************************************************
Hey! Python Is Fun And Easy
Hellow World

In following code, while entering city name, User can type


blank spaces, small letters etc. Using python function lets
make it full proof that whatever user enter we will be getting
desired output.
In [11]: # this code will give error unless user type exact city name given in if statement.

scity=input("Enter your city Name:")

if scity=='Pune':
print("Hello Punekar..Jai Shivaji")
elif scity=='Ahmdabad':
print("Hello Ahmdabadi...Jai Shree Krishna")
elif scity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("your entered city is invalid")

Enter your city Name:Pune


Hello Punekar..Jai Shivaji

In [12]: ''' lets full proof that if user enter correct spelling we should get desired output wit
bothering white spaces and capital and small letters. '''

scity=input("Enter your city Name:")


scity=scity.strip() # remove any blank spaces entered before and after the te
scity=scity.title() # makes first letter capitalized

if scity=='Pune':
print("Hello Punekar..Jai Shivaji")
elif scity=='Ahmdabad':
print("Hello Ahmdabadi...Jai Shree Krishna")
elif scity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("your entered city is invalid")

Enter your city Name:ahmdabad


Hello Ahmdabadi...Jai Shree Krishna

To check type of characters present in a string:


Python contains the following methods for this purpose.
1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 ) 2) isalpha(): Returns True if
all characters are only alphabet symbols(a to z,A to Z) 3) isdigit(): Returns True if all characters are digits
only( 0 to 9) 4) islower(): Returns True if all characters are lower case alphabet symbols 5) isupper(): Returns
True if all characters are upper case aplhabet symbols 6) istitle(): Returns True if string is in title case 7)
isspace(): Returns True if string contains only spaces

Note : We can't pass any arguments to these functions.

In [13]: print('UpendraJayesh154'.isalnum()) # True


print('UpendraJayesh154'.isalpha()) #False
print('Upendra'.isalpha()) #True
print('Upendra'.isdigit()) #False
print('123456'.isdigit()) #True
print('abc'.islower()) #True
print('Abc'.islower()) #False
print('abc123'.islower()) #True
print('ABC'.isupper()) #True
print('Learning python is Easy'.istitle()) #False
print('Learning Python Is Easy'.istitle()) #True
print(' '.isspace()) #True

True
False
True
False
True
True
False
True
True
False
True
True

Lets use above functions to write code which gives details about type of
values entered by the user
In [17]: s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")

Enter any character:A


Alpha Numeric Character
Alphabet character
Upper case alphabet character

Q. Write a program to display unique vowels present in the


given word.
In [23]: vowels=['a','e','i','o','u']
word=input("Enter the word to search for vowels: ")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("The number of different vowels present in",word,"is",len(found))

Enter the word to search for vowels: hey how are you
['e', 'o', 'a', 'u']
The number of different vowels present in hey how are you is 4

In [24]: # Suppose if you want lower case and upper case vowels, what you can do is as follows:
vowels=['a','e','i','o','u','A','E','I','O','U']
word=input("Enter the word to search for vowels: ")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("The number of different vowels present in",word,"is",len(found))

Enter the word to search for vowels: hey I know YOU are smart
['e', 'I', 'o', 'O', 'U', 'a']
The number of different vowels present in hey I know YOU are smart is 6

2. List Formatting functions


Function/Methods Description

len(list) # Gives the total lenght of the list

max(list) # gives item from the list with maximum value

min(list) # returns item from the list with minimum value

list.append(obj) # append/add an object (obj) passed to existing list

list.count(obj) # Retuns how many times the object obj appears in a list

list.remove(obj) # Removes obj from the list

list.index(obj) # Returns index of the object if found.

list.reverse() # reverse objects in a list

list.insert(index,obj) Return a list with object inserted at the given index

list.pop() # Removes or returns the last object of the list

lets see above Functions and Methods


In [21]: L=[14,85,77,45,45.36,66]

In [8]: print(len(L))
6

In [9]: print(max(L))

85

In [10]: print(min(L))

14

In [14]: L.append(101)
print(L)

[14, 85, 77, 45, 45.36, 66, 101]

In [17]: print(L.count(66))

In [18]: L.remove(45)
print(L)

[14, 85, 77, 45.36, 66, 101]

In [19]: print(L.index(66))
4

In [22]: L.reverse()
print(L)

[66, 45.36, 45, 77, 85, 14]

In [23]: L.insert(4,999)
print(L)

[66, 45.36, 45, 77, 999, 85, 14]

In [24]: L.pop()
print(L)

[66, 45.36, 45, 77, 999, 85]

In [ ]:

In [19]: # using append funtion to generate list

list=[]
list.append("A")
list.append("B")
list.append("C")
list.append("85")
list.append("C75.3")
print(list)

['A', 'B', 'C', '85', 'C75.3']

Example: To add all elements to list upto 100 which are


divisible by 10
In [20]: list=[]
for i in range(101):
if i%10==0:
list.append(i)
print(list)

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

In [21]: # lets use insert function to add value at specific place in a list
n=[1,2,3,4,5]
n.insert(1,888)
print(n)

[1, 888, 2, 3, 4, 5]

In [22]: n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
print(n.index(777))
print(n.index(999))

[999, 1, 2, 3, 4, 5, 777]
6
0
Q. Write a program to take a tuple of numbers from the
keyboard and print its sum and average.
In [25]: t=eval(input("Enter Tuple of Numbers:"))
print(type(t))
l=len(t)
sum=0
for x in t:
sum = sum + x
print("The Sum=",sum)
print("The Average=",sum/l)

Enter Tuple of Numbers:(10,20,30,50)


<class 'tuple'>
The Sum= 110
The Average= 27.5

Write a program to find number of occurrences of each


letter present in the given string.
In [29]: word=input("Enter any word: ")
d={}
for x in word:
d[x]=d.get(x,0)+1 # we are creating dictionary with the given word ====
for k,v in d.items():
print(k,"occurred ",v," times")

Enter any word: mumbai


m occurred 2 times
u occurred 1 times
b occurred 1 times
a occurred 1 times
i occurred 1 times

Write a program to find number of occurrences of each


vowel present in the given string.
In [30]: word=input("Enter any word: ")
vowels={'a','e','i','o','u'}
d={}
for x in word:
if x in vowels:
d[x]=d.get(x,0)+1
for k,v in sorted(d.items()):
print(k,"occurred ",v," times")

Enter any word: python


o occurred 1 times

Display student marks from stored dictonary.


In [48]: d={'rahul':85,'suresh':89,'mahesh':99,'khushi':100}

while True:
name=input("Enter Student Name to get Marks: ")
if name in d:
marks=d[name]
print(f"hey {name}, your marks is {marks}")
else:
print("the student does not exist")

option=input("Do you want to find another student marks[Yes|No]")


if option=="No":
break
print("Thanks for using our application")

Enter Student Name to get Marks: rahul


hey rahul, your marks is 85
Do you want to find another student marks[Yes|No]Yes
Enter Student Name to get Marks: mahesh
hey mahesh, your marks is 99
Do you want to find another student marks[Yes|No]Yes
Enter Student Name to get Marks: khushi
hey khushi, your marks is 100
Do you want to find another student marks[Yes|No]No
Thanks for using our application

There are Dozzens of functions and methods,similar to


above. use folloing links to see details
https://docs.python.org/3/library/functions.html
https://docs.python.org/3/library/stdtypes.html

Now lets see user defined funtions in Python


While creating functions we can use 2 keywords:

1. def (mandatory)
2. return (optional)

Eg.1. Write a function to print Hello message


In [4]: def wish():
print("Hello Good Morning")
wish()
wish()

Hello Good Morning


Hello Good Morning

Parameters:
Parameters are inputs to the function.
If a function contains parameters,then at the time of calling,compulsory we should provide
values,otherwise we will get error.

In [6]: def wish(name,sub):


print("Hello",name," Good Morning")
print("and you love ", sub)

wish("upendra","Python")
wish("Jayesh","MATLAB")

Hello upendra Good Morning


and you love Python
Hello Jayesh Good Morning
and you love MATLAB

2. Write a function to take number as input and print its


square value
In [7]: def squareIt(number):
print("The Square of",number,"is", number*number)
squareIt(4)
squareIt(5)
squareIt(7)

The Square of 4 is 16
The Square of 5 is 25
The Square of 7 is 49

return statement
Function can take input values as parameters and executes business logic, and returns output to the
caller with return statement.
Python function can return any number of values at a time by using a return statement.
Default return value of any python function is None.

3. Write a function to accept 2 numbers as input


and return sum.
In [8]: def add(x,y):
return x+y
result=add(10,20)
print("The sum is",result)
print("The sum is",add(100,200))

The sum is 30
The sum is 300

Write a function to check whether the given


number is even or odd?
In [9]: def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")
even_odd(10)
even_odd(15)

10 is Even Number
15 is Odd Number

Write a function to find factorial of given number.


In [49]: def fact(num):
result=1
while num>=1:
result=result*num
num=num-1
return result
num=int(input("enter a number : "))
for i in range(1,num):
print("The Factorial of",i,"is :",fact(i))

enter a number : 5
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24

Python program to return multiple values at a


time using a return statement.
In [10]: def calc(a,b): # Here, 'a' & 'b' are called positional arguments
sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div
a,b,c,d = calc(100,50) # Positional arguments
print(a,b,c,d)

150 50 5000 2.0

In [11]: def wish(marks,age,name = 'Guest', msg = 'Good Morning'):


print('Student Name:',name)
print('Student Age:',age)
print('Student Marks:',marks)
print('Message:',msg)
wish(99,48,'Upendra')

Student Name: Upendra


Student Age: 48
Student Marks: 99
Message: Good Morning

In [ ]:

Assignments Questions

1. Write a python program mimiking KBC (Kaun Banega Crorepati). the code should include:

ask user to enter the number of questions he/she wish to attempt


Few question may be MCQ type
Few questions may be such that user type those answer.
Eliminate any type of typo error which may be associated with blank space, capital/small letters etc.
At the end tell user the amount he/she won based on correct anser given.
Ask user if he/she wish to play again.
1. Write a python program which gives list of prime number between 1-1000.

2. take a string input from user and use atleast 8 builtin function for string and display their result.

3. take a list input from user and use atleast 8 builtin function for list and display their result.

4. write a python function which gives factorial of only odd numbers between 1-10.

5. write a python program solving any real-life question using python concepts which you have learnt
upto now.

In [ ]:

You might also like