UNIT 01 PYTHON BCA CBCS PDF
Document Details
Uploaded by Deleted User
Yogesh Patil
Tags
Summary
The document is an outline for Python Programming. It provides a general introduction to Python.
Full Transcript
BCA II SEM III CBCS Python Programming Unit I :- Parts of Python Programming Language, Identifiers, Keywords, Statements and Expressions, Variables, Operators, Precedence and Associativity, Data Types, Indentation, Comments, Reading Input, Print Output,...
BCA II SEM III CBCS Python Programming Unit I :- Parts of Python Programming Language, Identifiers, Keywords, Statements and Expressions, Variables, Operators, Precedence and Associativity, Data Types, Indentation, Comments, Reading Input, Print Output, Type Conversions, The type() Function and Is Operator, Dynamic and Strongly Typed Language, Control Flow Statements, The if Decision Control Flow Statement, The if…else Decision Control Flow Statement, The if…elif…else Decision Control Statement, Nested if Statement, The while Loop, The for Loop, The continue and break Statements, Catching Exceptions Using try and except Statement, Functions, Built-In Functions, Commonly Used Modules, Function Definition and Calling the Function, The return Statement and void Function, Scope and Lifetime of Variables, Default Parameters, Keyword Arguments, *args and **kwargs, Command Line Arguments. ============================================================== What is Python? Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures. Python programming language is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for Application Development. Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting and rapid application development. Python supports multiple programming pattern including object-oriented, imperative, and functional or procedural programming styles. Python is not intended to work in a particular area, such as web programming. That is why it is known as multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc. We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign an integer value in an integer variable. Python makes Notes By Yogesh Patil (9403256832) Page | 1 BCA II SEM III CBCS Python Programming the development and debugging fast because there is no compilation step included in Python development, and edit-test-debug cycle is very fast. Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of Python programming. Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc. The biggest strength of Python is huge collection of standard library which can be used for the following: Machine Learning GUI Applications (like Kivy, Tkinter, PyQt etc. ) Web frameworks like Django (used by YouTube, Instagram, Dropbox) Image processing (like OpenCV, Pillow) Web scraping (like Scrapy, BeautifulSoup, Selenium) Test frameworks Multimedia Scientific computing Text processing and many more.. Why to Learn Python? Python is currently the most widely used multi-purpose, high-level programming language, which allows programming in Object-Oriented and Procedural paradigms. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and the indentation requirement of the language, makes them readable all the time. Parts of Python Programming Language Following are the main parts of the python programming language:- Keywords Statements and Expressions Variables Operators Notes By Yogesh Patil (9403256832) Page | 2 BCA II SEM III CBCS Python Programming Precedence and Associativity Data Types Indentation Comments Reading Input Print Output Identifiers Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a combination of character digits and an underscore. They are case- sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good programming practice to give meaningful names to identifiers to make the code understandable. Rules for Naming Python Identifiers It cannot be a reserved python keyword. It should not contain white space. It can be a combination of A-Z, a-z, 0-9, or underscore. It should start with an alphabet character or an underscore ( _ ). It should not contain any special character other than an underscore ( _ ). Keywords Python Keywords are some predefined and reserved words in python that have special meanings. Keywords are used to define the syntax of the coding. The keyword cannot be used as an identifier, function, or variable name. All the keywords in python are written in lowercase except True and False. There are 35 keywords in Python. Rules for Keywords in Python Python keywords cannot be used as identifiers. All the keywords in python should be in lowercase except None, True and False. Notes By Yogesh Patil (9403256832) Page | 3 BCA II SEM III CBCS Python Programming List of Keywords and continue finally is raise as def for lambda return assert del from None try async elif global nonlocal TRUE await else if not while break except import or with class FALSE in pass yield Statements and Expressions Statements Any Instruction that a python interpreter can execute (carry out) is called a Statement. Each and every line or a sentence in any programming language is called an instruction. A Statement is the smallest executable unit of code that has an effect, like creating a variable or displaying a value. e.g.: x=3 print(x) Expressions An expression is a combination of operators and operands that is interpreted to produce some other value. In any programming language, an expression is evaluated as per the precedence of its operators. So that if there is more than one operator in an expression, their precedence decides which operation will be perform first. We have many different types of expressions in Python. Variables Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program. Notes By Yogesh Patil (9403256832) Page | 4 BCA II SEM III CBCS Python Programming The value stored in a variable can be changed during program execution. A Variable in Python is only a name given to a memory location, all the operations done on the variable effects that memory location. Rules for Python variables A Python variable name must start with a letter or the underscore character. A Python variable name cannot start with a number. A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). Variable in Python names are case-sensitive (name, Name, and NAME are three different variables). The reserved words (keywords) in Python cannot be used to name the variable in Python. Declaration and Initialization of Variables Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Example x=5 y = "Hello" print(x) print(y) Variables do not need to be declared with any particular type, and can even change type after they have been set. Example x=4 # x is of type int x = "CMCS" # x is now of type str print(x) Notes By Yogesh Patil (9403256832) Page | 5 BCA II SEM III CBCS Python Programming Python Assign Values to Multiple Variables Also, Python allows assigning a single value to several variables simultaneously with “=” operators. Ex. a = b = c = 10 print(a) print(b) print(c) Assigning different values to multiple variables Python allows adding different values in a single line with “,” operators. Ex. a, b, c = 1, 20.2, "CMCS" print(a) print(b) print(c) Global and Local Python Variables Local variables in Python are the ones that are defined and declared inside a function. We cannot call this variable outside the function. Example: # This function uses global variable s def f(): s = "Welcome CMCS" print(s) f() Global variables in Python are the ones that are defined and declared outside a function, and we need to use them inside a function. Notes By Yogesh Patil (9403256832) Page | 6 BCA II SEM III CBCS Python Programming Example: # This function has a variable with # name same as s. def f(): print(s) # Global scope s = "I love CMCS" f() 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. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. E.g. + , * , /, etc. OPERAND: It is the value on which the operator is applied. Types of Operators in Python Arithmetic Operators Comparison Operators Logical Operators Bitwise Operators Assignment Operators Identity Operators and Membership Operators 1. Arithmetic Operators Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division. In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used. Notes By Yogesh Patil (9403256832) Page | 7 BCA II SEM III CBCS Python Programming Operator 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 / x/y second Division (floor): divides the first operand by the // x // y second Modulus: returns the remainder when the first % x%y operand is divided by the second ** Power: Returns first raised to power second x ** y 2. Comparison Operators In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition. Operator Description Syntax Greater than: True if the left operand is greater > x>y than the right Less than: True if the left operand is less than < x= x >= y is greater than or equal to the right Less than or equal to - True if the left operand is Bitwise right shift x>> = a>>=b a=a>>b and assign value to left operand Performs Bitwise left shift on operands 10: print("x is greater than 10") else: Notes By Yogesh Patil (9403256832) Page | 31 BCA II SEM III CBCS Python Programming print("x is not greater than 10") In this example, the condition `x > 10` is evaluated. Since `x` is not greater than 10 (it's 7), the code inside the `else` block is executed, and the output will be: x is not greater than 10 The `if...else` statement is essential for handling cases where there are two possible outcomes based on a condition. It allows your code to take different paths depending on whether the condition is true or false. The if…elif…else Decision Control Statement The `if...elif...else` statement in Python is used when you have multiple conditions to check in sequence. It allows you to define a series of conditions, and the code associated with the first condition that evaluates to `True` will be executed. If none of the conditions are true, the code inside the `else` block will be executed. The basic syntax of the `if...elif...else` statement: if condition1: # code to execute if condition1 is true elif condition2: # code to execute if condition2 is true elif condition3: # code to execute if condition3 is true else: # code to execute if none of the conditions are true Following is an example to illustrate how the `if...elif...else` statement works: Notes By Yogesh Patil (9403256832) Page | 32 BCA II SEM III CBCS Python Programming x=7 if x > 10: print("x is greater than 10") elif x > 5: print("x is greater than 5 but not greater than 10") else: print("x is 5 or less") In this example, the first condition `x > 10` is not true, so Python moves on to the next condition. The second condition `x > 5` is true, so the code inside the corresponding `elif` block is executed, and the output will be: x is greater than 5 but not greater than 10 If none of the conditions were true, the code inside the `else` block would be executed. Example:- age = 25 if age < 18: print("You are a minor") elif age >= 18 and age < 65: print("You are an adult") else: print("You are a senior citizen") In this case, depending on the value of the `age` variable, the appropriate message will be printed. The `if...elif...else` statement is particularly useful when you have a series of mutually exclusive conditions to check, and you want to execute the code associated with the first condition that matches. Notes By Yogesh Patil (9403256832) Page | 33 BCA II SEM III CBCS Python Programming Nested if Statement A nested `if` statement in Python is an `if` statement that is placed inside another `if` statement. This allows you to create more complex decision structures where the outcome of one condition determines whether another condition should be evaluated. In other words, you have an `if` statement within another `if` statement. The basic syntax of a nested `if` statement: if outer_condition: # code to execute if outer_condition is true if inner_condition: # code to execute if inner_condition is true Following is an example to illustrate how nested `if` statements work: age = 17 has_id = True if age >= 18: print("You are eligible to vote") if has_id: print("Don't forget to bring your ID") else: print("Make sure to bring your ID to vote") else: print("You are not eligible to vote") In this example, the outer `if` statement checks if the `age` is greater than or equal to 18. If it is, the code inside that block is executed, and the nested `if` statement checks whether the person has an ID. Depending on the value of `has_id`, different messages will be printed. Notes By Yogesh Patil (9403256832) Page | 34 BCA II SEM III CBCS Python Programming Keep in mind that while nesting `if` statements can help handle more complex logic, excessive nesting can lead to code that's hard to read and understand. In some cases, using other control structures like `elif` or breaking the logic into separate functions can make your code more manageable. Example of a more complex nested `if` structure: x = 10 y=5 if x > 0: if y > 0: print("Both x and y are positive") else: print("x is positive but y is not") else: print("x is not positive") In this example, the first condition checks if `x` is positive. If it is, it moves to the inner `if` statement to check if `y` is positive. Depending on the values of `x` and `y`, different messages will be printed. Nested `if` statements provide flexibility in handling intricate decision-making situations, but it's essential to maintain code readability and structure while using them. The while Loop The `while` loop in Python is used to repeatedly execute a block of code as long as a given condition remains true. This allows you to create loops that continue until a certain condition is no longer satisfied. The loop continues iterating as long as the condition evaluates to `True`. Notes By Yogesh Patil (9403256832) Page | 35 BCA II SEM III CBCS Python Programming The basic syntax of the `while` loop: while condition: # code to execute while the condition is true Following is an example to illustrate how the `while` loop works: count = 0 while count < 5: print(count) count += 1 In this example, the initial value of `count` is 0. The loop continues as long as `count` is less than 5. During each iteration, the value of `count` is printed, and then it is incremented by 1 (`count += 1`). The loop will stop when `count` becomes 5, as the condition `count < 5` will no longer be true. The output of this loop will be: 0 1 2 3 4 Be cautious when using `while` loops, as an incorrect or improperly structured condition might lead to an infinite loop (a loop that never ends), which could hang your program or system. Another example that demonstrates how you can use a `while` loop to repeatedly ask the user for input until a valid input is provided: Notes By Yogesh Patil (9403256832) Page | 36 BCA II SEM III CBCS Python Programming while True: user_input = input("Enter a number: ") if user_input.isdigit(): number = int(user_input) print(f"Entered number: {number}") break else: print("Invalid input. Please enter a valid number.") In this example, the loop continues indefinitely (`while True`) until a valid integer input is provided. If the input is a valid number, the loop is exited using the `break` statement. The `while` loop is a powerful tool for creating repetitive behavior in your code. However, be sure to include a mechanism within the loop to eventually break out of it, or ensure that the loop's condition will eventually become false to prevent infinite loops. The for Loop The `for` loop in Python is used to iterate over a sequence of elements, such as a list, tuple, string, or range, and perform a block of code for each element in the sequence. It simplifies the process of repeating an action for each item in a collection. The basic syntax of the `for` loop: for variable in sequence: # code to execute for each item in the sequence Notes By Yogesh Patil (9403256832) Page | 37 BCA II SEM III CBCS Python Programming Examples to illustrate how the `for` loop works: 1. Looping through a List: fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) In this example, the `for` loop iterates through the `fruits` list, assigning each element to the variable `fruit`, and then printing it. The output will be: apple banana cherry 2. Looping through a String: message = "Hello" for char in message: print(char) The `for` loop iterates through each character in the string `message` and prints each character on a new line: H e l l o 3. Looping using the range function: for i in range(5): print(i) Notes By Yogesh Patil (9403256832) Page | 38 BCA II SEM III CBCS Python Programming In this example, the `for` loop uses the `range(5)` function to generate a sequence of numbers from 0 to 4. The loop then iterates through this sequence and prints each number: 0 1 2 3 4 4. Looping with an index: fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(f"Index: {index}, Fruit: {fruit}") The `enumerate()` function is used here to get both the index and the value of each element in the `fruits` list. The output will be: Index: 0, Fruit: apple Index: 1, Fruit: banana Index: 2, Fruit: cherry The `for` loop is a versatile construct that allows you to efficiently iterate through sequences, collections, and ranges, making it a fundamental tool in Python programming. Notes By Yogesh Patil (9403256832) Page | 39 BCA II SEM III CBCS Python Programming The continue and break Statements The `continue` and `break` statements are control flow statements in Python that affect the behavior of loops. They allow you to control the flow of execution within loops, making your code more flexible and efficient. 1. continue Statement: The `continue` statement is used within loops to skip the rest of the current iteration and move on to the next one. It's often used when you want to skip certain iterations based on a specific condition. Example using `continue`: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for num in numbers: if num % 2 == 0: continue # Skip even numbers print(num) In this example, the loop iterates through the `numbers` list. If a number is even, the `continue` statement is executed, skipping the rest of the loop's code for that iteration. This results in only odd numbers being printed: 1 3 5 7 9 2. break Statement: The `break` statement is used to exit the current loop prematurely, regardless of whether the loop condition is still met. It's commonly used when you want to terminate a loop early based on a certain condition. Notes By Yogesh Patil (9403256832) Page | 40 BCA II SEM III CBCS Python Programming Example using `break`: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for num in numbers: if num > 5: break # Exit the loop when num is greater than 5 print(num) In this example, the loop iterates through the `numbers` list. When the value of `num` becomes greater than 5, the `break` statement is executed, causing the loop to terminate immediately. As a result, only numbers 1 to 5 will be printed. 1 2 3 4 5 Both the `continue` and `break` statements are useful for controlling the flow of loops and designing more efficient and specific loop behavior. They help you avoid unnecessary iterations or exit loops when certain conditions are met. Catching Exceptions Using try and except Statement In Python, the `try` and `except` statements are used for handling exceptions (errors) in a controlled manner. They allow you to write code that can gracefully handle errors without causing the program to crash. This is especially useful when you anticipate that a certain part of your code might raise an exception. Notes By Yogesh Patil (9403256832) Page | 41 BCA II SEM III CBCS Python Programming The basic syntax of the `try` and `except` statement: try: # code that might raise an exception except ExceptionType: # code to handle the exception Following is an example to illustrate how to catch exceptions using the `try` and `except` statement: try: x = 10 / 0 # This will raise a ZeroDivisionError except ZeroDivisionError: print("Division by zero is not allowed") In this example, the code inside the `try` block attempts to perform a division by zero, which raises a `ZeroDivisionError` exception. However, instead of crashing the program, the `except` block catches the exception and prints a user-friendly error message: Division by zero is not allowed You can also use multiple `except` blocks to handle different types of exceptions: try: value = int("hello") # This will raise a ValueError except ValueError: print("Conversion to int failed") except ZeroDivisionError: print("Division by zero is not allowed") Notes By Yogesh Patil (9403256832) Page | 42 BCA II SEM III CBCS Python Programming In this example, the `try` block attempts to convert the string "hello" to an integer, which raises a `ValueError` exception. The first `except` block catches the `ValueError` and prints an appropriate error message. You can also use a generic `except` block without specifying the exception type to catch all exceptions, but it's generally recommended to catch specific exceptions whenever possible to handle them more accurately: try: x = 10 / 0 except: print("An error occurred") Using the `try` and `except` statement allows you to create robust programs that gracefully handle errors, improving the overall stability and user experience of your application. Functions A function in Python is a block of organized, reusable code that performs a specific task or set of tasks. Functions provide a way to encapsulate logic and make code more modular, allowing you to break down complex problems into smaller, more manageable parts. Functions can be called multiple times with different inputs, making your code more efficient and readable. The basic structure of a function in Python: def function_name(parameters): # Function body # Perform tasks using parameters return result Notes By Yogesh Patil (9403256832) Page | 43 BCA II SEM III CBCS Python Programming def : This keyword is used to define a function. function_name: This is the name you give to the function. Choose a descriptive name that reflects what the function does. parameters: These are the input values that the function takes as arguments. You can have zero or more parameters. return: This keyword is used to specify the value that the function should return after performing its tasks. If there is no `return` statement, the function returns `None`. A simple example of a function that calculates the square of a number: def square(number): result = number ** 2 return result # Call the function result = square(5) print(result) # Output: 25 In this example, the `square` function takes a single parameter `number`, calculates its square, and returns the result. When you call the function with an argument of `5`, it returns `25`. Functions allow you to organize your code, promote code reusability, and improve maintainability. They are a fundamental concept in programming and are used extensively to build complex applications in Python. Built-In Functions Built-in functions in Python are pre-defined functions that are available for use without needing to import any external libraries or modules. These functions are an integral part of the Python language and provide a wide range of functionality, from Notes By Yogesh Patil (9403256832) Page | 44 BCA II SEM III CBCS Python Programming performing simple tasks to complex operations. You can use built-in functions directly in your code without needing to write the implementation yourself. A few examples of commonly used built-in functions in Python: 1. print(): This function is used to display output to the console. print("Hello, world!") 2. len(): This function returns the length (number of elements) of a sequence, like a string, list, tuple, or dictionary. string_length = len("Hello") print(string_length) # Output: 5 list_length = len([1, 2, 3, 4, 5]) print(list_length) # Output: 5 3. input(): This function is used to take user input from the console. name = input("Enter your name: ") print("Hello, " + name) 4. int(), float(), str(): These functions are used to convert values from one type to another. string_number = "42" integer_number = int(string_number) print(integer_number + 10) # Output: 52 float_number = float("3.14") print(float_number * 2) # Output: 6.28 integer_value = 42 string_value = str(integer_value) print("The answer is " + string_value) # Output: "The answer is 42" Notes By Yogesh Patil (9403256832) Page | 45 BCA II SEM III CBCS Python Programming 5. range(): This function generates a sequence of numbers that can be used in loops. for num in range(5): print(num) Output: 0 1 2 3 4 These are just a few examples of the many built-in functions available in Python. You can explore the Python documentation to discover more built-in functions and their usage. Built-in functions make programming in Python more convenient and efficient, as they provide essential functionality out of the box. Commonly Used Modules Python modules are files containing Python code, usually with functions, classes, and variables, that can be imported and used in other Python scripts. Python's standard library includes a wide range of modules that provide various functionalities. Here are some commonly used modules and examples of their usage: 1. math: Provides mathematical functions and constants. import math print(math.sqrt(25)) # Output: 5.0 print(math.pi) # Output: 3.141592653589793 print(math.sin(math.pi)) # Output: 1.2246467991473532e-16 Notes By Yogesh Patil (9403256832) Page | 46 BCA II SEM III CBCS Python Programming 2. random: Generates random numbers and performs random selections. import random print(random.randint(1, 6)) # Output: Random integer between 1 and 6 print(random.choice([1, 2, 3])) # Output: Random choice from the list 3. datetime: Provides classes for working with dates and times. import datetime current_date = datetime.date.today() print(current_date) # Output: Current date in YYYY-MM-DD format current_time = datetime.datetime.now() print(current_time) # Output: Current date and time 4. os: Allows interaction with the operating system, such as file operations and environment variables. import os current_directory = os.getcwd() print(current_directory) # Output: Current working directory file_list = os.listdir('.') print(file_list) # Output: List of files in the current directory Notes By Yogesh Patil (9403256832) Page | 47 BCA II SEM III CBCS Python Programming 5. json: Provides functions for working with JSON (JavaScript Object Notation) data. import json data = '{"name": "John", "age": 30, "city": "New York"}' parsed_data = json.loads(data) print(parsed_data["name"]) # Output: John 6. re: Provides regular expression operations for pattern matching and manipulation. import re pattern = r'\b\w+\b' text = "Hello, world! This is a sample text." matches = re.findall(pattern, text) print(matches) # Output: ['Hello', 'world', 'This', 'is', 'a', 'sample', 'text'] 7. csv: Provides functionality for working with CSV (Comma-Separated Values) files. import csv with open('data.csv', 'r') as file: csv_reader = csv.reader(file) for row in csv_reader: print(row) Notes By Yogesh Patil (9403256832) Page | 48 BCA II SEM III CBCS Python Programming These are just a few examples of commonly used modules from Python's standard library. Depending on your specific needs, you can explore and use various modules to simplify and enhance your Python programs. Function Definition and Calling the Function Function definition and calling are fundamental concepts in Python programming that allow you to encapsulate a block of code into a reusable unit and use it whenever needed. Let's explore how to define and call functions using examples. Function Definition: To define a function in Python, you use the `def` keyword followed by the function name and a set of parentheses containing any parameters the function will accept. The function body follows, indented underneath the `def` line. The function body consists of the code that the function executes when called. The basic structure of a function definition: def function_name(parameters): # Function body # Perform tasks using parameters return result Example of a function that calculates the square of a number: def square(number): result = number ** 2 return result Function Calling: To call a function, you use the function's name followed by parentheses. If the function requires parameters, you provide them within the parentheses. The function is then executed, and its return value (if any) can be used. Notes By Yogesh Patil (9403256832) Page | 49 BCA II SEM III CBCS Python Programming Example of calling the `square` function: result = square(5) print(result) # Output: 25 A more comprehensive example: def greet(name): message = "Hello, " + name return message user_name = input("Enter your name: ") greeting = greet(user_name) print(greeting) In this example, the `greet` function takes a `name` parameter, constructs a greeting message, and returns it. The user's input is stored in the `user_name` variable, and then the `greet` function is called with that input. The returned greeting message is stored in the `greeting` variable and printed. Functions allow you to modularize your code, make it more readable, and reuse code logic in multiple places. You can define a function once and call it as many times as needed with different arguments, enhancing the efficiency and maintainability of your programs. The return Statement and void Function The `return` statement is used in Python to specify the value that a function should return after it has executed its tasks. When a function encounters a `return` statement, it immediately exits the function and returns the specified value. The `return` statement is crucial for functions that are designed to produce an output that can be used in other parts of your code. Notes By Yogesh Patil (9403256832) Page | 50 BCA II SEM III CBCS Python Programming A "void function" is a term commonly used to describe functions that do not return a value. In Python, functions can be considered "void" if they do not have a `return` statement or if they have a `return` statement without any expression to return. However, it's important to note that in Python, even if a function does not explicitly return a value, it implicitly returns `None`. Here are examples to illustrate the concept of the `return` statement and "void functions": Function with a Return Value: def add_numbers(a, b): result = a + b return result sum_result = add_numbers(5, 3) print(sum_result) # Output: 8 In this example, the `add_numbers` function takes two arguments and returns their sum. When the function is called with `5` and `3`, it computes the sum and returns `8`. Function without a Return Value (Void Function): def greet(name): message = "Hello, " + name print(message) greet("Alice") # Output: Hello, Alice In this example, the `greet` function constructs a greeting message but does not have a `return` statement. Instead, it uses `print` to display the message directly. Notes By Yogesh Patil (9403256832) Page | 51 BCA II SEM III CBCS Python Programming This function is considered a "void function" because it doesn't explicitly return a value. Function with an Implicit Return (Void Function): def show_message(): print("This is a message") returned_value = show_message() print(returned_value) # Output: None In this example, the `show_message` function doesn't have a `return` statement. However, when you call it and store the result in the `returned_value` variable, the value stored is `None`, indicating that the function didn't return a specific value. Remember that a function can have a `return` statement even if you don't need the returned value immediately. The `return` statement is essential for functions that compute results or perform actions that need to be utilized in other parts of your program. Scope and Lifetime of Variables Scope and lifetime are fundamental concepts in programming that deal with the visibility and availability of variables in different parts of your code. In Python, variables have different scopes and lifetimes depending on where they are defined and used. Scope refers to the region of code where a variable is accessible. It defines the part of the program where the variable can be referred to and manipulated. Python has four main types of variable scope: 1. Local Scope: Variables defined within a function have local scope. They are only accessible within the function they are defined in. Notes By Yogesh Patil (9403256832) Page | 52 BCA II SEM III CBCS Python Programming def my_function(): local_variable = 10 print(local_variable) my_function() # Output: 10 # print(local_variable) # Raises an error: NameError: name 'local_variable' is not defined 2. Enclosing Scope: For variables defined in a nested function, the enclosing function's scope is considered enclosing scope. The variables are accessible in both the nested function and the enclosing function. def outer_function(): outer_variable = "Hello" def inner_function(): print(outer_variable) # Can access the outer_variable inner_function() outer_function() # Output: Hello 3. Global Scope: Variables defined at the top level of a script or module have global scope. They are accessible throughout the entire module or script. global_variable = "I'm global" def my_function(): print(global_variable) my_function() # Output: I'm global Notes By Yogesh Patil (9403256832) Page | 53 BCA II SEM III CBCS Python Programming 4. Built-in Scope: Variables that are part of Python's built-in namespaces have built-in scope. They include functions like `print()` and constants like `True` and `False`. print(len("Hello")) # Output: 5 # len_variable = len("Hello") # print(len_variable) # Raises an error: NameError: name 'len_variable' is not defined Lifetime refers to the duration for which a variable remains in memory and is accessible during the program's execution. The lifetime of a variable depends on its scope: Variables with local scope are created when the function is called and destroyed when the function exits. Variables with global scope are created when the program starts and destroyed when the program ends. The relationship between scope and lifetime: Local variables: Limited scope and short lifetime (created and destroyed within the function). Enclosing variables: Limited scope and longer lifetime (exist as long as the enclosing function is alive). Global variables: Broad scope and long lifetime (exist throughout the program's execution). Built-in variables: Broad scope and longest lifetime (exist throughout the program's execution). Understanding scope and lifetime is crucial for writing maintainable and error-free code. It ensures that variables are used in appropriate contexts and that they're available when needed. Notes By Yogesh Patil (9403256832) Page | 54 BCA II SEM III CBCS Python Programming Default Parameters Default parameters, also known as default arguments, are a feature in Python that allow you to provide default values for function parameters. These default values are used when the function is called without providing a value for that parameter. Default parameters make your functions more flexible and allow you to provide sensible defaults for optional arguments. How you define a function with default parameters: def function_name(param1=default_value1, param2=default_value2,...): # Function body # Perform tasks using parameters Example of a function with default parameters: def greet(name, greeting="Hello"): message = greeting + ", " + name print(message) greet("Alice") # Output: Hello, Alice greet("Bob", "Hi") # Output: Hi, Bob In this example, the `greet` function takes two parameters: `name` and `greeting`. The `greeting` parameter has a default value of "Hello". If you provide a value for `greeting` when calling the function, that value will be used. Otherwise, the default value "Hello" will be used. Default parameters allow you to create functions that are more versatile and can be called with varying numbers of arguments. It's important to note that default parameter values are evaluated only once when the function is defined. If a mutable object (like a list or dictionary) is used as a default value, it might lead to unexpected behavior, as the same object could be modified across multiple function calls. Notes By Yogesh Patil (9403256832) Page | 55 BCA II SEM III CBCS Python Programming Keyword Arguments Keyword arguments, also known as named arguments, are a feature in Python that allows you to pass arguments to a function using their parameter names. This provides greater clarity and flexibility when calling functions, as it allows you to specify which argument corresponds to which parameter, even if they are in a different order. How you use keyword arguments when calling a function: function_name(param1=value1, param2=value2,...) Example of using keyword arguments: def greet(name, age): print(f"Hello, {name}! You are {age} years old.") greet(name="Alice", age=25) # Output: Hello, Alice! You are 25 years old. greet(age=30, name="Bob") # Output: Hello, Bob! You are 30 years old. In this example, the `greet` function takes two parameters: `name` and `age`. When calling the function, you provide the values for these parameters using their names. The order of the arguments doesn't matter as long as you specify which parameter each value corresponds to. Keyword arguments are especially useful when a function has multiple parameters or when you want to make the function call more self-explanatory by explicitly indicating which value goes with which parameter. They also allow you to skip optional parameters that have default values and only provide values for the parameters you need to change. Notes By Yogesh Patil (9403256832) Page | 56 BCA II SEM III CBCS Python Programming *args and **kwargs In Python, `*args` and `**kwargs` are special syntaxes used to pass a variable number of arguments to a function. They provide flexibility when defining functions that can accept an arbitrary number of positional arguments (`*args`) and keyword arguments (`**kwargs`). 1. *args (Positional Arguments): The `*args` syntax allows you to pass a variable number of positional arguments to a function. These arguments are collected into a tuple within the function, and you can iterate over them or access them by index. Example using *args: def add_numbers(*args): total = 0 for num in args: total += num return total result = add_numbers(1, 2, 3, 4) print(result) # Output: 10 In this example, the `add_numbers` function can accept any number of arguments. The `*args` parameter collects these arguments into a tuple, allowing you to add them up. 2. **kwargs (Keyword Arguments): The `**kwargs` syntax allows you to pass a variable number of keyword arguments to a function. These arguments are collected into a dictionary within the function, and you can access them using their specified keys. Example using **kwargs: Notes By Yogesh Patil (9403256832) Page | 57 BCA II SEM III CBCS Python Programming def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=25, city="New York") In this example, the `print_info` function can accept any number of keyword arguments. The `**kwargs` parameter collects these arguments into a dictionary, allowing you to print their key-value pairs. You can use `*args` and `**kwargs` together in a function definition, but remember that `*args` should appear before `**kwargs`. def complex_function(arg1, *args, kwarg1="default", **kwargs): # Function body Using `*args` and `**kwargs` makes your functions more versatile, as they can handle a varying number of arguments without needing to specify them individually. This is particularly useful when you're designing functions that need to be flexible and accommodate different use cases. Command Line Arguments Command line arguments are values provided to a Python script when it is executed from the command line. These arguments allow you to pass information to your script without modifying the script itself. Python provides the `sys.argv` list from the `sys` module to access command line arguments. Notes By Yogesh Patil (9403256832) Page | 58 BCA II SEM III CBCS Python Programming How you can access command line arguments in a Python script: import sys # The command line arguments are stored in sys.argv # sys.argv is the script name itself # sys.argv[1:] are the actual arguments provided print("Script name:", sys.argv) print("Arguments:", sys.argv[1:]) For example, if you run the script from the command line like this: python my_script.py arg1 arg2 arg3 The output would be: Script name: my_script.py Arguments: ['arg1', 'arg2', 'arg3'] You can access and use these command line arguments within your script. Remember that the command line arguments are always treated as strings, so you might need to convert them to appropriate data types if needed. Below is an example of a script that calculates the sum of numeric command line arguments: import sys def calculate_sum(args): total = 0 for arg in args: total += int(arg) Notes By Yogesh Patil (9403256832) Page | 59 BCA II SEM III CBCS Python Programming return total if len(sys.argv) > 1: arguments = sys.argv[1:] result = calculate_sum(arguments) print("Sum of arguments:", result) else: print("No arguments provided.") If you run this script with the command `python sum_script.py 10 20 30`, it will calculate and print the sum of the provided numbers: Sum of arguments: 60 Command line arguments provide a way to make your scripts more dynamic and customizable, as you can modify their behavior without altering the code itself. Notes By Yogesh Patil (9403256832) Page | 60