0% found this document useful (0 votes)
26 views8 pages

Python Function Practice Exercises

The document contains examples of using Python functions. It defines several functions like course(), add(), sum() and uses them to perform operations like addition, input from users, returning values. It also contains examples of built-in functions like print(), eval(), round(), int() being used. Various data types like lists, tuples, dictionaries are passed into functions and returned. Function parameters and return values are demonstrated.

Uploaded by

TheAncient01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views8 pages

Python Function Practice Exercises

The document contains examples of using Python functions. It defines several functions like course(), add(), sum() and uses them to perform operations like addition, input from users, returning values. It also contains examples of built-in functions like print(), eval(), round(), int() being used. Various data types like lists, tuples, dictionaries are passed into functions and returned. Function parameters and return values are demonstrated.

Uploaded by

TheAncient01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Functions_Python_Practice

May 2, 2023

[1]: def course(a,b):


print(a,b)

[2]: x='mba'
course(x,y='mca')

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_14708\[Link] in <module>
1 x='mba'
----> 2 course(x,y='mca')

TypeError: course() got an unexpected keyword argument 'y'

[19]: print(course(55,[]))

55 []
None

[8]: def add(a,b):

c=a+b
print(c)

[9]: add(5,6)

11

[14]: def sum():


a=int(input('1st- '))
b=int(input('2nd- '))
c=a+b
return c

[11]: sum()

1
1st- 5
2nd- 6
11

[12]: sum()

1st- 6
2nd- 5
11

[13]: sum()

1st- 4
2nd- 6
10

[15]: sum()

1st- 6
2nd- 8

[15]: 14

[16]: sum()

1st- 4
2nd- 9

[16]: 13

[ ]: # Create a function that adds two numbers and returns the addition
# Square the result outside the function and store that in an empty list

[39]: def add(a,b):


c=a+b
return(c)

[40]: add(9,4)

[40]: 13

[44]: s=add(9,4)
print(s**2)
lst=[]
[Link](s**2)
print(lst)

169
[169]

2
[11]: def course(*x):
return(x,type(x))

[12]: course('da','ba','ds','engg','bba','mca','mba','bca')

[12]: (('da', 'ba', 'ds', 'engg', 'bba', 'mca', 'mba', 'bca'), tuple)

[15]: a=course('da','ba','ds','engg','bba','mca','mba','bca')
print(a,type(a),list(a))

(('da', 'ba', 'ds', 'engg', 'bba', 'mca', 'mba', 'bca'), <class 'tuple'>) <class
'tuple'> [('da', 'ba', 'ds', 'engg', 'bba', 'mca', 'mba', 'bca'), <class
'tuple'>]

[ ]:

[1]: add(5,7)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15168\[Link] in <module>
----> 1 add(5,7)

NameError: name 'add' is not defined

[12]: int(5.9999999999999999999)

[12]: 6

[14]: import sys

[15]: [Link]

[15]: ['C:\\Users\\mark4\\Desktop\\Data Science and AI\\Python_Mar 10, 2023


Batch\\Python_Practice',
'C:\\ProgramData\\Anaconda3\\[Link]',
'C:\\ProgramData\\Anaconda3\\DLLs',
'C:\\ProgramData\\Anaconda3\\lib',
'C:\\ProgramData\\Anaconda3',
'',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32\\lib',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin',
'C:\\ProgramData\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\mark4\\.ipython']

3
[1]: import math

[4]: [Link](3)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_7804\[Link] in <module>
----> 1 [Link](3)

TypeError: 'float' object is not callable

[5]: print([Link](cel2Fah(28)))

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_7804\[Link] in <module>
----> 1 print([Link](cel2Fah(28)))

AttributeError: module 'math' has no attribute 'round'

[6]: a=82.89380098815465
print(round(a))

83

[8]: str(82.4)

[8]: '82.4'

[11]: a=5.456512263
print(round(a,2))

5.46

[12]: b=82.4
print(round(b,2))

82.4

[1]: a=[2]
print(a[0])
print(a[-1])

2
2

4
[15]: def addFirstAndLast(*x):
lst=eval('x')

print(x,type(x))
print(lst,type(lst))

[17]: addFirstAndLast(5)
addFirstAndLast([5])

(5,) <class 'tuple'>


[5] <class 'list'>
([5],) <class 'tuple'>
[[5]] <class 'list'>

[1]: a=456
print(a[-1])

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_12132\[Link] in <module>
1 a=456
----> 2 print(a[-1])

TypeError: 'int' object is not subscriptable

[14]: def addFirstAndLast(*x):


print(list(x))
print(x[0])

[15]: addFirstAndLast([])

[[]]
[]

[9]: def Cel2Fah(c):


f=(c*9)/5+32.00
g=float(f)
print(round(g,2))

[10]: Cel2Fah(0.00)

32.0

[17]: x=[1,23,456]
s=0
for i in range(len(x)):
s=s+int((str(x[i])[-1]))
print(s)

5
10

[1]: def addOne(x):

return x + 1

[4]: def useFunction(func,num):


s=(num+1)**2
print(s)

[5]: useFunction(addOne,4)

25

[1]: is_prime(5)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_11420\[Link] in <module>
----> 1 is_prime(5)

NameError: name 'is_prime' is not defined

[3]: x=5,4,6,9,8,7,4
list(x)

[3]: [5, 4, 6, 9, 8, 7, 4]

[2]: x='fgg'
print([Link]())

False

[3]: x='45'
print(x*3)

454545

[4]: a='fgd'+'#'
print(a)

fgd#

[ ]: def Dict(x):
L=list([Link]())
for i in L:
if [Link](i) > 1:
print({})

6
else:

[3]: x={'name': 'Rajesh', 'age': 22, 'ID': 101, 'Salary': 45000}


for i in [Link]():
print(i)

Rajesh
22
101
45000

[1]: def swap_key_value(d):


L = list([Link]())
for value in L:
if [Link](value) > 1:
return dict()

new_dict = {}
for k, v in [Link]():
new_dict[v] = k
return new_dict

[2]: swap_key_value({'name': 'Rajesh', 'age': 22, 'ID': 101, 'Salary': 45000})

[2]: {'Rajesh': 'name', 22: 'age', 101: 'ID', 45000: 'Salary'}

[4]: a=input(int('Str- '))


print(list(a))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_14320\[Link] in <module>
----> 1 a=input(int('Str- '))
2 print(list(a))

ValueError: invalid literal for int() with base 10: 'Str- '

[7]: a=1,8,4,5,6
print(list(a))

[1, 8, 4, 5, 6]

[26]: b=(input('N-'))
c=list(b)
print(c)
for i in c:

7
temp=i
i=int(i)
temp=int(i)
print(c)

N-12345
['1', '2', '3', '4', '5']
['1', '2', '3', '4', '5']

[45]: b=input('N-')
print(b,type(b))
print(eval(b),type(eval(b)))
print(list(eval(b)))

x=[]
[Link](b)
print(x,type(x))
print(eval("x"),type(eval("x")))

N-1,2,3,4,5
1,2,3,4,5 <class 'str'>
(1, 2, 3, 4, 5) <class 'tuple'>
[1, 2, 3, 4, 5]
['1,2,3,4,5'] <class 'list'>
['1,2,3,4,5'] <class 'list'>

[ ]:

Common questions

Powered by AI

A function can add two numbers using a structure like def add(a,b): return(a+b). To return the square of the result and store it in a list, you execute the addition and then apply the squaring operation externally: s = add(9,4); lst = []; lst.append(s**2). This demonstrates using return for computed values and managing these outputs in data structures such as lists for further use.

Rounding in Python is significant for controlling the precision of numeric calculations, particularly when dealing with floating-point numbers where precision may vary due to binary representation. For example, using round(a,2) on a=5.456512263 results in 5.46 , which demonstrates how rounding affects the display and precision of numeric results. This can be crucial for applications needing consistent precision, such as financial calculations.

Using input() captures all user input as a string, while converting this string to an integer using int() requires the string to be a valid representation of an integer. A common error that occurs is a ValueError if the string cannot be converted, such as in input(int('Str- ')) where 'Str- ' is not a valid integer string, causing the error 'invalid literal for int() with base 10: 'Str- '' . Proper handling involves either validating the string input before conversion or using try-except blocks to manage errors.

Using eval in Python introduces risks due to the potential execution of arbitrary code, which can be a security vulnerability. For example, evaluating unsanitized user inputs, which could embed malicious code, is a common risk . Alternatives include using safer modules like ast.literal_eval for evaluating literals, or manually parsing and sanitizing inputs to control execution context and maintain security.

Attempting to subscript an integer, as shown by trying a=456 followed by print(a[-1]), is a mistake because integers do not support indexing in Python. This raises a TypeError with the message: 'int' object is not subscriptable . This error occurs because Python integers are scalar and do not have elements that can be accessed via indices.

Missing function definitions lead to runtime errors such as NameError when attempting to call an undefined function, as shown by is_prime(5) causing an error due to the function 'is_prime' not being defined . A common way to prevent this is to ensure that all necessary function definitions are included in the script or module before their invocation. Using Integrated Development Environments (IDEs) with code linters can help identify such missing definitions during development.

A TypeError occurs when a function is called with an unexpected keyword argument, as demonstrated by the attempt to call course(x,y='mca') which resulted in the error message: 'course() got an unexpected keyword argument 'y'' . This can be rectified by either ensuring that the function definition actually includes the keyword argument, or by modifying the call to match the parameters expected by the function definition.

The primary benefits of using variable-length argument tuples, using *args, in Python functions are flexibility and the ability to handle an arbitrary number of positional arguments within a function, enhancing reusability and adaptability for varying input sizes . However, pitfalls include potential confusion over argument order and responsibility for correct tuple unpacking or handling within the function, which can lead to logical errors and complex debugging if not managed properly.

You can modify a function to accept a variable number of arguments by using the *args syntax in the parameter list. For example, def course(*x): return(x,type(x)) allows the course function to accept any number of arguments and package them into a tuple . As shown in the example, calling course('da','ba','ds') returns (('da', 'ba', 'ds'), tuple), demonstrating that all arguments are collected into a tuple.

A function can be structured to return a value by using the return statement with the value to be returned. For example, def add(a,b): c=a+b return(c) ensures that the result of a+b is returned when the function is called . Returning values is important for subsequent operations because it allows the result of the function to be used outside of its scope, enabling further computations or storage, as shown by s = add(9,4); print(s**2).

You might also like