0% found this document useful (0 votes)
61 views78 pages

PYTHON

The document provides an overview of Python programming, highlighting its features, applications, and key concepts such as variables, operators, control structures, and data types. It explains the use of lists, tuples, and dictionaries, detailing their methods and functionalities. Python's simplicity and versatility make it a popular choice among both beginners and professionals in various fields.

Uploaded by

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

PYTHON

The document provides an overview of Python programming, highlighting its features, applications, and key concepts such as variables, operators, control structures, and data types. It explains the use of lists, tuples, and dictionaries, detailing their methods and functionalities. Python's simplicity and versatility make it a popular choice among both beginners and professionals in various fields.

Uploaded by

heenamujassem07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 78
+B = ChatGPT GB: . e marks ke hisaab se expand ho sakta hai: For 4 Marks: Python Programming Language: Python is a high-level, interpreted programming language. It was created by Guido van Rossum and released in 1991. Python is known for its simple syntax and readability, which makes it easy for beginners. It is used in various fields like web development, data science, machine learning, and automation. Python supports object-oriented, procedural, and functional programming styles. Message ChatGPT @ @ Search Q Reas... Q @ = ChatGPT v For 8-12 Marks: (Expanded Version) Python Programming Language: Python is a powerful, high-level, interpreted programming language created by Guido van Rossum and first released in 1991. It is designed to be easy to read and write, with a clean and simple syntax. Key Features: * Easy to learn: Simple syntax like English. + Interpreted language: Code runs line by line. * Portable: Works on different operating systems. * Open-source: Free to use and modify. abate dan ofan natn |Message ChatGPT 9 gs) = @® Search @ Reas... = ® * Versatile: Supports multiple programming paradigms — object-oriented, procedural, and functional. * Large standard library: Comes with many built-in functions and modules. Applications of Python: * Web development (using Django, Flask) « Data science and machine learning (using Pandas, NumPy, scikit-learn) * Automation and scripting ° Game development * Mobile and desktop app development Conclusion: Beca “its simplicity and flexibility Python is widely used hv Message ChatGPT @ @® Search © Reas... Q @ T1o4 i ee ll = ChatGPT G@ : * Large standard library: Comes with many built-in functions and modules. Applications of Python: ¢ Web development (using Django, Flask) e Data science and machine learning (using Pandas, NumPy, scikit-learn) e Automation and scripting * Game development * Mobile and desktop app development Conclusion: Because of its simplicity and flexibility, Python is widely used by both beginners and professionals. It is one of the most popular programming languages in the world today. Vv Message ChatGPT @! @® Search @ Reas... Q © 4+ ) 8 = ChatGPT & 4 Marks Answer: Variables in Python: A variable is a name that is used to store data in a program. It holds a value that can change during the execution of the program. Example: Python () Copy code x = 10 name = "Ravi" Python does not need a data type to be declared. It automatically assigns the type based on the value. Message ChatGPT 0, @) @ Search © Reas... g @ = ChatGPT eC 12 Marks Answer: Variables in Python: A variable is a container used to store data values in a Python program. It allows programmers to use and update information during program execution. Python is a dynamically typed language, which means you don't need to declare the data type of a variable. How to Create a Variable: In Python, a variable is created when a value is assigned using the equal sign =. Example: Message ChatGPT 0 & © Search @ Reas... g @ Example: Python () Copy bone x = 25 name = “Ravi" price = 99.50 Rules for Naming Variables: 1. Must begin with a letter or an underscore (_) 2. Can contain letters, digits, and underscores 3. Cannot begin with a digit 4. Cannot use reserved keywords like if, for, while. om Vv Message ChatGPT @ @ Search © Reas... a @ = ChatGPT @ eee Types of Values Variables Can Store: * Integers (e.g., 10) * Strings (e.g., "Hello") * Floats (¢.g., 5.67) * Booleans (e.g., True, False) Advantages: « Helps store and reuse values ¢ Makes code readable and manageable ° Allows changes in values without changing the whole program Message ChatGPT @ @ Search @ Reas... g @ = ChatGPT Operators in Python: Operators are special symbols that perform operations on variables and values. Types of Operators: 1. Arithmetic Operators: FB Lie TA, ** Example: x + y 2. Comparison Operators: ==, ! =, >, < a) >=, <= Example: a == 3. Assignment Operators: =, +=, --=, *=, /=, etc. Example: x += 5 4. Logical Operators: and, or, not Example: a > 5 and a < 10 Vv Message ChatGPT @ @®Search © Reas... a @ = ChatGPT tz 12 Marks Answer: Operators in Python: Operators are symbols that are used to perform operations on variables and values. Python provides several types of operators to handle different tasks in programming. 1. Arithmetic Operators: Used for mathematical calculations. | Operator | Meaning | Example + Addition x+y - Subtraction | x - y Message ChatGPT @ @ Search © Reas... g @ Share a link to chat? This creates a copy that others can chat with Used for mathematical calculations. _ Operator Meaning Example F if Addition x+y - Subtraction | x - y * Multiplicati | x * y on / Division x /y % Modulus xX BY ff Floor x // y Division *% Exponentia | x ** y tion Message ChatGPT &) @ Search Q Reas.. o @& = ChatGPT Z 2. Comparison (Relational) Operators: Used to compare two values. Operator Meaning Example == Equal to x == y l= Not equal x l= y to > Greater x>y than < Less than x = y equal aS Less or x <= y equal Message ChatGPT @) @ Search @ Reas... © 12:01 = ChatGPT W 3. Assignment Operators: Used to assign values to variables. Operator Meaning Example = Assign x = 5 a= Add and xX += 3 assign “= Subtract % = g and assign *s Multiply x *= 4 and assign i= Divide and | x /= 2 assign Vv AP eH an om ~~ ae Message chatepr oe ® Search @ Reas.., KO TAL ChatGPT 4. Logical Operators: & Used to combine conditional statements. Operator Meaning Example and True if both | x > 5 and true x < 10 or True ifone | x > 5 or true me not Reverse not(x > the result 5) 5. Bitwise Operators (Advanced use): Message ChatGPT @) @ Search Q Reas... g = ChatGPT CG: 9. Bitwise Operators (Advanced use): Works with binary values. Operator Symbol AND & OR XOR ‘ NOT ~ Left Shift << Right Shift 7 Message ChatGPT > @ Sp @D Search @ Reas.. = = ChatGPT @ 4 Marks Answer: Control Structures in Python: Control structures are used to control the flow of a program. They decide which part of the code should run based on conditions or repetitions. Types: 1. Conditional Statements (if, if-else, elif) Example: Python () Copy code if «= OF print(”" Positive”). Message ChatGPT @! @ Search © Reas... Q @ — ChatGPT G : 1. Conditional Statements (if, if-else, elif) Example: Python () Copy code if x > 0: print("Positive") 2. Loops (for, while) Example: Python () Copy code for i in range(5): print(i) These help in making decisions and repeating tasks in Python. 12 Marks Answer: Message ChatGPT @ @ Search Q Reas... g @ = ChatGPT G 12 Marks Answer: Control Structures in Python: Control structures are the backbone of programming logic. They determine the flow of execution in a Python program based on conditions or repetitions. 1. Conditional Statements: Used to make decisions based on conditions. ¢ if statement: Python C) Copy code if age >= 18: print("Eligible to vote") Message ChatGPT @! @® Search © Reas... Q @ Share a link to chat? This creates a copy that (2) others can chat with e if-else statement: python QO Copy code 18: if age 7* cradult"> print else: print (“Minor”) ° elif ladder: Q copy code python if marks 77 de AN int C'S ade ori One a an Cc) Ss: oopind stateme”" 2s nage chatGPT ° 2. Looping Statements: Used to repeat a block of code. * for loop: Pyaon ©) Copy code for iin range(5): print¢i) * while loop: Python () Copy code i=1 while i <= 5: print¢i) i += 1 Message ChatGPT @) @® Search © Reas... Q © : eal Uf This creates a copy that others can chat with 3. Loop Control Statements: ° break — exits the loop Python (°) Copy code for i in range(i0): if i == 5: break print(i) continue — skips current iteration Python C0) Copy code for i in range(5): if i == 2: continue print(i) ° pass — does nothing (placeholder) python 0) copy code Message ChatGPT @ & Search @ Reas-. 2 @ ChatGPT GQ : 4 WMiarKS ANSWEr: Looping Statements in Python: Looping statements are used to repeat a block of code multiple times. Types of loops: 1. for loop — Repeats for a fixed number of times. Python C) Copy code for i in range(5): print(i) 2. while loop — Repeats as long as a condition is true. Python C) Copy code oe while i <= 5: print(i) i+= 1 Message ChatGPT @ Search © Reas... gd @ = ChatGPT GZ IZ Marks answer: Looping Statements in Python: Loops are used to execute a block of code repeatedly based on a condition. Python supports two main types of loops: for and while. 1. for Loop: Used when we know how many times to repeat. Syntax: Python C) Copy code for variable in range(start, stop, step): Message ChatGPT @® Search © Reas... Q @ T2407 — ChatGPT Z for variable in range(start, stop, step): Example: Python (°) Copy code for i in range(1, 6): print(i) This prints numbers from 1 to 5. 2. while Loop: Used when we don’t know the exact number of repetitions but we have a condition. Syntax: Message ChatGPT @ Search © Reas... gQ @ others can chat with & 2. while Loop: Used when we don’t know the exact number of repetitions but we have a condition. Syntax: Python () Copy code while condition: Example: Python ©) Copy code i= 1 while i <= 5: printqi) i+ Message ChatGPT ® Search © Reas... g am — ChatGPT G 3. Loop Control Statements: * break — exits the loop early Python (°) Copy code for i in range(5): if i = break print(i) * continue — skips current iteration Python () Copy code for i in range(5): 4h a Be ee continue print(i) * pass — placeholder, does nothing Python (0) Copy code for i in rang pass Message ChatGPT co @ Search © Reas... —- ChatGPT Z 3. Loop Control Statements: * break — exits the loop early Python () Copy code for i in range (5): if i == break print(i) * continue — skips current iteration Python (°) Copy code for i in range(5): if i == 2: continue print (i) * pass — placeholder, does nothing Python () Copy code for i in range(3): pass Message ChatGPT = ChatGPT G : 4 Marks Answer: Methods of List in Python: Lists in Python come with many built-in methods to perform operations. 1. append() - Adds an element at the end of the list. Example: Python () Copy code my_list = [1, 2, 3] my_list.append(4) 2. insert() — Inserts an element at a specific position. Example: Python C) Copy code my_list.insert(1, 10) Message ChatGPT @® Search © Reas... Q @ wwE ELE ' iy e rye Ly wvpy vevus my_list.insert(¢1, 10) 3. remove() — Removes the first occurrence of a value. Example: Python Copy code my _list.remove(2) 4. pop() — Removes and returns the last element. Example: Python (] Copy code my_list.pop() Vv 19 AAarlke Ancwar- Nessage ChatGPT = ChatGPT @ Methods of Tuples in Python: A tuple is a collection data type in Python that is ordered and immutable. Tuples are similar to lists, but they cannot be modified once created. Python provides only a few methods for working with tuples since they are immutable. 1. count(): The count() method returns the number of occurrences of a specified element in the tuple. Syntax: Message ChatGPT @® Search © Reas... Q © 4 ) — ChatGPT & 1. count(): The count() method returns the number of occurrences of a specified element in the tuple. Syntax: Python ©) Copy code tuple. count(element) Example: Python ©) Copy code my_tuple = (1, 2, 3, 2, 4) print(my_tuple.count(2)) This counts how many times the element 2 appears in the tuple. Message ChatGPT @® Search © Reas... g @ 2. index(): The index() method returns the index of the first occurrence of the specified element. If the element is not found, it raises a ValueError. Syntax: Python () Copy code tuple.index(element, start, end) e start and end are optional parameters to specify a range within which to search for the element. Example: Python (°) Copy code Message ChatGPT @® Search © Reas... Q @ — ChatGPT Z Syntax: Python (°) Copy code tuple. index(element, start, end) e start and end are optional parameters to specify a range within which to search for the element. Example: Python () Copy code my_tuple = (10, 20, 30, 40, 50) print(my_tuple. index(30)) This returns the index 2 where 30 is first found. Vv Message ChatGPT ® Search © Reas... Q @ = ChatGPT Methods of Dictionaries in Python: A dictionary in Python is an unordered collection of items. Each item ina dictionary is a Pair consisting of a key and a value. Python dictionaries provide various methods for adding, removing, updating, and retrieving data. 1. clear(): The clear() method removes all the items from the dictionary, leaving it empty. Syntax: mn Message ChatGPT @ Search @ Reas... g @ Share a link to chat? This creates a copy that others can chat with Syntax: Python () Copy code dict.clear() Example: Python C) Copy code my_dict = {'a': 1, “b': 2} my _dict.clear() print(my_dict) 2. copy(): The copy() meth ~w rns ashallow copy of the diction. ,. fhis means it Message ChatGPT @ Search © Reas... Q © co.rtr = ChatGPT ZG 2. copy(): The copy() method returns a shallow copy of the dictionary. This means it creates a new dictionary with the same keys and values as the original one. Syntax: Python () Copy code dict.copy() Example: Python (°] Copy code my_dict = {'a': 1, ‘b': 2} new_dict = my_dict.copy() print(new_dict) Vv Message ChatGPT @® Search © Reas... Q @ Share a link to chat? This creates a copy that others can chat with 3. get(): The get() method returns the value associated with the specified key. If the key is not found, it returns None (ora specified default value). Syntax: Python O) Copy code dict.get(key, default=None) Example: Python (°) Copy code my dict = {'a': 1. ‘b's: 2} print(my_dict. ge ) print(my_dict.g ™“ 4 Message ChatGPT @ Search @ Reas... Q @ sn ra 4 | OC This creates a copy that others can chat with 4. items(): The items()} method returns a view object that displays a list of dictionary’s key-value tuple pairs. Syntax: Python () Copy code dict.items() Example: Python CO) Copy code my_dict = {'a': 1, ‘b': 2} print(my_dict.items()) Vv Message ChatGPT ® Search QReas. @ Share a link to chat? This creates a copy that others can chat with 5. keys(): The keys() method returns a view object that displays a list of all the keys in the dictionary. Syntax: Python ©) Copy code dict. keys() Example: Python C) Copy code my_dict = {'a"': 1, 'b': 2} print(my_dict.keys()) Vv Message ChatGPT ChatGPT has detected this screenshot Wy ocdren ‘ef Meds... wy @® 12:11 4+ ?» = 7D) = ChatGPT GB: 6. pop(): The pop() method removes the item with the specified key and returns its value. If the key is not found, it raises a KeyError. Syntax: Python () Copy code dict.pop(key, default) Example: Python () Copy code my_dict = {‘a": V7, "BG": '2} print(my_dict.pop¢ ‘a')) print¢(my_dict) Message ChatGPT @ Search @ Reas... Q @ Share a link to chat? This creates a copy that & others can chat with The popitem() method removes and returns the last key-value Pair from the dictionary. If the dictionary is empty, it raises a KeyError. Syntax: Python O Copy code dict.popitemc Example: Python , OQ Copy code My_dict = {'ats 4 ‘bes 2 Print¢my_, dict. Popitem¢)) , Print(my dicty Message ChatGpt ® Search etl +Fa = ChatGPT S 8. update(): The update) method updates the dictionary with elements from another dictionary or from an iterable of key-value pairs. Syntax: Python CO) Copy code dict.update([other]) Example: Python () Copy code my diet: = 4a: 4, "Bi: 2} my _dict.update({‘'c’: 3, ‘d*: 4}) print¢my_dict) Vv Message ChatGPT @ Search © Reas... g @ Share a link to chat? This creates a copy that others can chat with 9. values(): The values() method returns a view object that displays a list of all the values in the dictionary. Syntax: Python (°] Copy code dict.values¢) Example: python (°) Copy code "p': 2} my_dict = {fav's 1; print(my_dict.values()) Vv Message ChatGPT — ChatGPT eee Methods of Dictionaries in Python: A dictionary in Python is an unordered collection of items. Each item in a dictionary is a pair consisting of a key and a value. Python dictionaries provide various methods for adding, removing, updating, and retrieving data. 1. clear(): The clear() method removes all the items from the dictionary, leaving it empty. Syntax: Message ChatGPT ©) @® Search © Reas... g @ Share a link to chat? This creates a copy that e& others can chat with Syntax: Python (°) Copy code dict.clear() Example: Python () Copy code my_dict = {'a': 1, "b's 2} my_dict.clear() print¢(my_dict) 2. copy(): Vv The copy() methe drns a shallow Message ChatGPT ChatGPT has detected this screenshot @) yy oearcil \y keas... yw @ -his creates a copy that others can chat with 2. copy(): The copy() method returns a shallow copy of the dictionary. This means it creates a new dictionary with the same keys and values as the original one. Syntax: Python CO) Copy code dict.copy() Example: Python (©) Copy code my dict = {'a': 1, 'b': 2} new_dict = my_dict.copy() print(new_dict) Vv Message ChatGPT = ChatGPT @ 3. get(): The get() method returns the value associated with the specified key. If the key is not found, it returns None (ora specified default value). Syntax: Python () Copy code dict.get(key, default=None) Example: Python () Copy code my_dict = {'a': 1, 'b': 2} print(my_dict.get('a’)) print(my_dict.geté'")) Vv Message ChatGPT q @ Search © Reas... Q @ This creates a copy that others can chat with 4. items(): The items() method returns a view object that displays a list of dictionary’s key-value tuple pairs. Syntax: Python () Copy code dict.items() Example: Python () Copy code my_dict = {'a': 1, "b': 2} print(my_dict.items()) Message ChatGPT @) @ Search © Reas... Q @ This creates a copy that others can chat with 5. keys(): The keys() method returns a view object that displays a list of all the keys in the dictionary. Syntax: Python () Copy code dict. keysq) Example: Python () Copy code my_dict = {'a': 1, ‘b': 2} print(my_dict.keys()) Vv Message ChatGPT @ @search QReas.. Q @ Share a link to cl This creates a copy that e& others can chat with 6. pop(): The pop() method removes the item with the specified key and returns its value. If the key is not found, it raises a KeyError. Syntax: Python (°) Copy code dict.pop(key, default) Example: Python () Copy code my_dict = {'a': 1, ‘b": 2 print(my_dict.pop('a')) print(my_dict) Vv Message ChatGPT @) @Search © Reas.. g @ ociw = ChatGPT Z 7. popitem(): The popitem() method removes and returns the last key-value Pair from the dictionary. If the dictionary is empty, it raises a KeyError. Syntax: Python ©) Copy code dict. popitem¢) Example: Python ©) Copy code mMy_dict = ¢'a:. 1, "b': 2} print(my dict. popitem()) print(my_dict) vw Message ChatGPT @ @ Search @ Rea... 1 e Share a link to t? his creates a copy that others can chat with 8. update(): The update() method updates the dictionary with elements from another dictionary or from an iterable of key-value pairs. Syntax: Python (°] Copy code dict.update( [other] ) Example: Python () Copy code my_dict = {'a': 1, ‘b': 2} my_dict.update({ = Mads aD print(my_dict) Vv Message ChatGPT @) @ Search © Reas... Q @ This creates a copy that others can chat with 9. values(): The values() method returns a view object that displays a list of all the values in the dictionary. Syntax: Python () Copy code dict.values() Example: Python () Copy code my_dict = {*a': 1, ‘b': 2} print(my_dict.values()) Vv Message ChatGPT @) yp oearcn \/ meas... yw © = ChatGPT G : 4 Marks Answer - String Methods in Python: Python provides several built-in methods to work with strings. These methods help with searching, modifying, formatting, and analyzing strings. 1. upper() Converts all characters to uppercase, Python () Copy code “"heena". upper () 2. lower() Converts all characters to lowercase. Python () Copy code Message ChatGPT @) @® Search @ Reas... g @ m This creates a copy that e& others can chat with 2. lower() Converts all characters to lowercase. Python (°) Copy code “HEENA". lower() 3. strip() Removes leading and trailing spaces. Python () Copy code "hello ".strip() 4. replace() Renlaces a nart of the string with Message ChatGPT @ @® Search © Reas... g © Share a link to chat? This creates a copy that e& others can chat with mea eourapus 4. replace() Replaces a part of the string with another. Python () Copy code "hello".replace("h", “j") 12 Marks Answer -— String Methods in Python: Strings in Python ° aquences of characters enclo. “ ingle or double quotes. Python proviues many useful Message ChatGPT @ @® Search © Reas... g @ Pe = ChatGPT Z 12 Marks Answer — String Methods in Python: Strings in Python are sequences of characters enclosed in single or double quotes. Python provides many useful string methods that do not change the original string (strings are immutable), but return a new modified string. 1. upper() Returns the string with all uppercase letters. Python (°) Copy code Vv name = "heena” 4 tinamn tm fxn Message ChatGPT @ @® Search Q Reas... Q @ 1214 Vv wat = ChatGPT Gi: 1. upper() Returns the string with all uppercase letters. Python (() Copy code name = “heena” print(name. upper ()) 2. lower() Returns the string with all lowercase letters. Python (°] Copy code name = “HEENA" print (name. lower ()) Message ChatGPT @! @® Search © Reas... & @® — ChatGPT 3. capitalize() Capitalizes the first character of the string. Python (7] Copy code "heena". capitalize() 4. title() Capitalizes the first letter of every word. Python () Copy code "my name is heena”.title() Message ChatGPT @) ® Search Q Ress 5 sas Q @ This creates a copy that others can chat with 5. strip() Removes leading and trailing spaces. Python () Copy code hello “.strip() 6. replace(old, new) Replaces all occurrences of a substring. Python () Copy code “banana”. replace("a", "o"y) Message ChatGPT @Q = @® Search @ Reas... g @ = ChatGPT G : 7. find() Returns the index of the first occurrence of a substring. Returns -1 if not found. Python (°) Copy code "heena".find("e") 8. count() Returns the number of times a substring appears. Python (°] Copy code “heena”. count("e") Vv Message ChatGPT @ @ Search © Reas... g @ — ChatGPT ZG 9, startswith() / endswith() Checks if a string starts or ends with a specific substring. () Copy code Python "hello". startswith("h") "hello". endswith("o") 10. split() Splits a string into a list based ona delimiter. Python (°] Copy code “heena rani".split() Message ChatGPT @ @ Search © Reas... Q @ T2168 GS U1) = ChatGPT G : Python provides several built-in math functions and also has a math module for advanced calculations. Common Built-in Math Functions: 1. abs(x): Returns the absolute value of x. Python () Copy code abs(-5) 2. pow(x, y): Returns x raised to the power y. Python () Copy code pow(2, 3) 3. max(a, b, ...): Returns the largest value. Python () Copy code Message ChatGPT @) @® Search @ Reas... Q @ Share a link to chat? This creates a copy that (2) others can chat with pow(2, 3) 3. max(a, b, ..-): Returns the largest value. Python (() Copy code max(10, 5, 7) 4. min(a, b, ...): Returns the smallest value. Python (] Copy code min(10, 5, 7) 12 Marks Ane +*-— Math Functions in “ on: Message ChatGPT @ @® Search © Reas... Q @ & = ChatGPT Using the math Module: To use the advanced math functions, we must import the math module. (°) Copy code Python import math 6. math.sqrt(x): Returns the square root of x. Python () Copy code math.sqrt(25) Message ChatGPT Oo @& @® Search © Reas... 7. math. floor(x): Returns the largest integer less than or equal to x. Python (°) Copy code math.floor(3.7) 8. math.ceil(x): Returns the smallest integer greater than or equal to x. Python (() Copy code math.ceil(3.2) Message ChatGPT ©) @ Search © Reas... Q @ 12:17 = ChatGPT G : 12. math.log(x): Returns the natural logarithm of x. Python () Copy code math. log(10) Conclusion: Math functions in Python help with both simple and complex calculations. They make it easy to perform operations like power, square root, rounding, trigonometry, and logarithms — all essential in scier id engineering Vv applications. Message ChatGPT @ 4 Search © Reas... g @ Va et eS U0) = ChatGPT @ 4 Marks Answer — Functions and its Uses in Python What is a Function? A function is a block of code that performs a specific task, It can be called multiple times to reuse the same code. Syntax: Python (°) Copy code def function_name(): Example: Python () Copy code def greet(): print("Hello, Heena!") greet() Message ChatGPT @! @ Search © Reas... gd @ Share a link to chat? This creates a copy that others can chat with Uses of Functions: * Reuse code (no need to write again and again) * Makes program modular ¢ Easy to debug and understand 12 Marks Answer — Functions and its Uses in Python What is a Function? A function is a reusable block of code that performs a specific operation. Functions help br 3 program into Vv smaller, manageé its. Message ChatGPT @ @® Search Q Reas... Qd @ Types of Functions: L. Built-in functions — Already Provided by Python Example: Print(), lenc), type() 2. User-defined functions — Created by the programmer Example: Python O) Copy code def welcome(): . print("welcome Heena!") welcome() Syntax of Use Vv ved Function: Share a (to chat? This creates a copy that others can chat with Syntax of User-defined Function: Python () Copy code def function_name(parameters ): return value Example with Parameters: Python () Copy code def add(a, b): return a+b printcadd(5, 3)) Message ChatGPT @ @ Search © Reas... Q @ = ChatGPT Z : Uses of Functions in Python: 1. Code Reusability: You can use the same function multiple times without writing code again. 2. Modularity: Divides a large program into smaller parts. 3. Debugging: Errors can be found and fixed easily in a small function. 4. Easy Maintenance: Functions make code neat and organized. 5. Avoids Repetition: No need to repeat the same code block again. Message ChatGPT @ @ Search @ Reas... Q @ i = ChatGPT G Files in Python: Python allows reading and writing data using files. Basic File Operations: 1. open() — Opens a file 2. read(), write() - To read or write content 3. close() — Closes the file Example: Python () Copy code f = open("demo.txt", "“w") f.write("Hello Heena!") f.close() Message ChatGPT @ @ Search © Reas... Q @ = ChatGPT G Exceptions in Python: Exceptions are errors that occur during program execution. Example: Python (() Copy code try: a=10/0 except ZeroDivisionError. print("Cannot divide by zero”) 12 Marks Answer - Files and Exceptions in Python 1. File Handlinr © °ython: Vv Python allows you w work with files |Vessage ChatGPT gy ® Search © Reas... g @ = ChatGPT GC : 1. File Handling in Python: Python allows you to work with files using built-in functions. Opening a File: Python C) Copy code file = open("example.txt", "mode") Modes: e 'r' — Read * 'w' — Write (overwrites) * 'a' - Append ° 'b' — Binary Message ChatGPT @!) © Search © Reas... g © Share a link to chat? This cr SSE BAO that e& others can chat with e 'b' — Binary ° 't' — Text (default) Writing to a File: Python ((] Copy code f = open("heena. txt" "w") f.writec"Python is fun!” ) f.close() Reading from a File: Vv () Copy code Python Message ChatGPT @) @ Search © Reas... Qa @ Reading from a File: Python °) Copy code f = open("heena.txt", "r”) data = f.read() print(data) f.close() 2. Exceptions in Python: An exception is an error that breaks the normal flow of a program. Python handles them using try-except blocks. Basic Syntax: Python () Copy code trys except ErrorType: Message ChatGPT @ @ Search Q Reas... Q @

You might also like