Untitled

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following scenarios best illustrates the use of a user-defined function (UDF) in Python?

  • Employing the `min()` function to find the smallest value in a list.
  • Using the `print()` function to display text on the console.
  • Creating a function to calculate the area of a rectangle, where the length and width are passed as arguments. (correct)
  • Utilizing a `lambda` function for a simple addition operation within a list comprehension.

What would be the output of the following Python code snippet?

def my_function(x):
  return x * 5

result = my_function(3)
print(result)```

  • `Error`
  • `None`
  • `3`
  • `15` (correct)

Consider the following Python function definition. What happens if you call this function without a return statement, and then try use the result?

  • The function will automatically return a default value of `0`.
  • The function will return `None`. (correct)
  • The function will raise an error.
  • The function will return a random integer.

You are tasked with writing a function that calculates the volume of a cube. Which of the following function definitions is most appropriate according to Python standards?

<pre><code class="language-python">def cubeVolume(side): return side**3``` (C) </code></pre> Signup and view all the answers

Which keyword is used to define a function in Python?

<p><code>def</code> (D)</p> Signup and view all the answers

What is the outcome of the following Python code snippet?

str1 = "Python"
del str1
print(str1)

<p>NameError: name 'str1' is not defined (C)</p> Signup and view all the answers

Which operator is used to concatenate strings in Python?

<ul> <li>(D)</li> </ul> Signup and view all the answers

Which operator is used to access substrings of a string by specifying a starting index (inclusive) and an ending index (exclusive)?

<p>[] (B)</p> Signup and view all the answers

Which of the following data structures is not mutable in Python?

<p>Tuple (B)</p> Signup and view all the answers

Which list method is used to add a single element to the end of a list?

<p>append() (B)</p> Signup and view all the answers

Which list method is used to add elements from another list (or any iterable) to the end of the current list?

<p>extend() (A)</p> Signup and view all the answers

Which list method allows you to insert an element at a specific position within the list?

<p>insert() (B)</p> Signup and view all the answers

What is the primary difference between the append() and extend() methods when adding elements to a list?

<p><code>append()</code> adds a single element to the end of the list, while <code>extend()</code> adds elements from an iterable to the end of the list. (B)</p> Signup and view all the answers

Why are immutable data structures particularly useful in parallel programming?

<p>They prevent race conditions and data corruption by ensuring that data cannot be modified concurrently. (B)</p> Signup and view all the answers

Which of the following statements accurately describes the key difference between tuples and lists in Python?

<p>Tuples are immutable, preventing modification of their elements after creation, whereas lists are mutable. (C)</p> Signup and view all the answers

What will be the output of the following Python code?

t = (1, 2, [3, 4])
t[2][0] = 5
print(t)

<p>(1, 2, [5, 4]) (A)</p> Signup and view all the answers

What happens when you try to delete a specific item inside a tuple in Python?

<p>A <code>TypeError</code> is raised because tuple objects do not support item deletion. (A)</p> Signup and view all the answers

In Python, strings are considered as a sequence of which type of characters?

<p>Unicode characters (A)</p> Signup and view all the answers

Which of the following is the correct way to create a multiline string in Python?

<p>Using triple quotes (<code>'''Hello\nWorld'''</code>) (B)</p> Signup and view all the answers

What does it mean for strings to be 'immutable' in Python?

<p>Once a string is created, its content cannot be changed; any modification results in a new string object. (C)</p> Signup and view all the answers

What is true about reassignment of strings in Python?

<p>A string can only be effectively 'reassigned' by assigning the variable to a completely new string. (A)</p> Signup and view all the answers

What is the primary purpose of defining a function with a default argument?

<p>To allow the function to be called without providing a value for that argument, using a predetermined default if none is given. (C)</p> Signup and view all the answers

In Python, what distinguishes keyword arguments from required arguments when calling a function?

<p>Keyword arguments use parameter names to assign values, allowing them to be passed in any order, while required arguments rely on positional order. (C)</p> Signup and view all the answers

If a Python function is defined to accept two required arguments, what will happen if it is called with only one argument?

<p>The function will raise a TypeError indicating that the required number of arguments was not provided. (C)</p> Signup and view all the answers

Which of the argument types provides the most flexibility when defining a function that needs to accept an unspecified number of inputs?

<p>Variable-length arguments (A)</p> Signup and view all the answers

Consider the following function definition: def calculate(x, y=10): return x * y. What will be the output of calculate(5)?

<p>50 (B)</p> Signup and view all the answers

Given the function def describe_person(name, age): print(f'{name} is {age} years old.'), which of the following calls would correctly use keyword arguments?

<p><code>describe_person(name='Alice', age=30)</code> (B)</p> Signup and view all the answers

A function process_data(file_path, limit=100) is defined. You want to call this function providing a new value for limit but keep the default file_path. What is the correct way to do this?

<p><code>process_data(file_path, 500)</code> (B)</p> Signup and view all the answers

Which of the following scenarios best illustrates the use of variable-length arguments?

<p>A function that sends email to a list of recipients where the number of recipients varies each time. (C)</p> Signup and view all the answers

Which of the following is a key characteristic that distinguishes *args from **kwargs in Python function definitions?

<p><code>*args</code> collects non-keyword arguments into a tuple, while <code>**kwargs</code> collects keyword arguments into a dictionary. (A)</p> Signup and view all the answers

Consider a function defined as def calculate(*numbers):. What data type will numbers be inside the function when it is called with calculate(1, 2, 3)?

<p>A tuple (C)</p> Signup and view all the answers

Which of the following best describes the primary purpose of a Python lambda function?

<p>To create an anonymous, single-expression function. (C)</p> Signup and view all the answers

Given the following code:

x = 10

def my_function():
    x = 5
    print(x)

my_function()
print(x)

What will be the output of this code?

<p>5 10 (B)</p> Signup and view all the answers

In Python, what is the key difference between a local and a global variable in terms of their accessibility?

<p>Local variables are accessible only within the function they are defined in, while global variables are accessible throughout the entire program. (D)</p> Signup and view all the answers

Which of the following data types in Python is immutable?

<p>Tuple (B)</p> Signup and view all the answers

Which characteristic is inherent to immutable data structures in Python?

<p>Operations that appear to modify them actually create new instances. (B)</p> Signup and view all the answers

If a variable x is assigned the value (1, 2, [3, 4]) in Python, can the list [3, 4] within the tuple be modified?

<p>Yes, because lists are mutable, even when they are elements of an immutable tuple. (D)</p> Signup and view all the answers

Which of the following statements accurately describes the key difference between Python dictionaries and sets?

<p>Dictionaries store key-value pairs, while sets store unordered collections of unique items. (A)</p> Signup and view all the answers

What will be the output of the following Python code?

def func(**kwargs):
    for k, v in kwargs.items():
        print(k, '=', v)

func(name='Alice', age=30, city='New York')

<p><code>name=Alice\nage=30\ncity=New York</code> (C)</p> Signup and view all the answers

Given two Python sets, set1 = {1, 2, 3, 4} and set2 = {3, 4, 5, 6}, what will be the result of set1.difference(set2)?

<p><code>{1, 2}</code> (A)</p> Signup and view all the answers

Which function is used to determine the number of key-value pairs in a Python dictionary?

<p><code>len()</code> (D)</p> Signup and view all the answers

Consider the following scenario: You need to store information about students, where each student has a unique ID, a name, and a list of courses they are enrolled in. Which Python data structure would be most suitable for this task?

<p>A dictionary with student IDs as keys and dictionaries containing name and courses as values. (A)</p> Signup and view all the answers

Signup and view all the answers

Signup and view all the answers

Flashcards

def keyword

Keywords used to create functions. Starts the function definition.

Function

A named block of code that performs a specific task. It may accept arguments as input and return a value.

Built-in functions

Built-in functions are pre-defined functions in Python that are readily available for use.

User-Defined Functions (UDFs)

Functions created by the user to perform specific tasks. They are defined using the def keyword.

Signup and view all the flashcards

Anonymous (Lambda) Functions

Functions without a name, often created using lambda. They are typically used for short, simple operations.

Signup and view all the flashcards

Argument

A variable that receives a value when a function is called.

Signup and view all the flashcards

Default Argument

An argument that has a pre-defined value if none is provided.

Signup and view all the flashcards

Keyword Arguments

Arguments passed with a name, not just by the order.

Signup and view all the flashcards

Required Arguments

Arguments that must be included when calling a function.

Signup and view all the flashcards

Variable-Length Arguments

A function receives any number of arguments.

Signup and view all the flashcards

len()

The 'len()' function in Python returns the length of a string (the number of characters).

Signup and view all the flashcards

Function Definition

A named section of a program that performs a specific task. Functions can accept arguments and may return values, promoting code reusability and organization.

Signup and view all the flashcards

*args

Accepts a variable number of non-keyword arguments.

Signup and view all the flashcards

**kwargs

Accepts a variable number of keyword arguments as a dictionary.

Signup and view all the flashcards

Lambda Function

A small anonymous function defined using the lambda keyword.

Signup and view all the flashcards

Local Variable

Variables defined inside a function; their scope is limited to that function.

Signup and view all the flashcards

Global Variable

Variables defined outside any function; accessible throughout the program.

Signup and view all the flashcards

Immutable Data Structure

Data types that cannot be modified after creation. Examples: numbers, strings, tuples.

Signup and view all the flashcards

Integer

A numeric data type representing whole numbers e.g. 1, 2, 3.

Signup and view all the flashcards

Immutable data types

Data types which cannot be changed or modified after they are assigned.

Signup and view all the flashcards

Python Dictionary

A data structure in Python that stores values in key-value pairs, enclosed in curly braces {}.

Signup and view all the flashcards

Accessing Dictionary

An attempt to retrieve a dictionary's value using its key.

Signup and view all the flashcards

len() for Dictionaries

Function that returns the number of key-value pairs in a dictionary.

Signup and view all the flashcards

Python Set

A data structure that stores an unordered collection of unique items, enclosed in curly braces {}.

Signup and view all the flashcards

Tuples

Ordered, immutable collection of Python objects, separated by commas.

Signup and view all the flashcards

Python Strings

Strings are immutable sequence of Unicode characters, enclosed in single, double, or triple quotes.

Signup and view all the flashcards

Immutability of Strings

Strings cannot be changed after creation; attempts to modify them result in an error.

Signup and view all the flashcards

String Slicing

Slice operator [] accesses individual characters; : accesses substrings.

Signup and view all the flashcards

String Reassignment

Assign a new string to the variable. Strings themselves can't be altered.

Signup and view all the flashcards

String Encoding

Strings are stored and manipulated as combinations of 0s and 1s, encoded in ASCII or Unicode.

Signup and view all the flashcards

String Quote Types

Single, double, and triple quotes can be used to create strings.

Signup and view all the flashcards

String (str)

An immutable sequence of characters.

Signup and view all the flashcards

TypeError: string item assignment

The attempt to modify an immutable string.

Signup and view all the flashcards

del str1

Removes the string variable from memory.

Signup and view all the flashcards

String concatenation (+)

Joins strings end-to-end.

Signup and view all the flashcards

String repetition (*)

Repeats a string multiple times.

Signup and view all the flashcards

String slice operator []

Accesses a substring from a string.

Signup and view all the flashcards

Membership operator (in / not in)

Returns True if substring exists in the string.

Signup and view all the flashcards

Study Notes

Functions, Scoping, and abstraction

  • Unit-2 covers functions, scoping and abstraction.
  • The content includes declaring, defining, and invoking functions.
  • The content includes function specification, function arguments, local vs global variables.
  • Function arguments are keyword, default, positional, and variable-length.

Types of Functions

  • There are three types of functions in Python: Built-in functions, User-Defined Functions (UDFs), and Anonymous functions.
  • Built-in functions include help() to ask for help, min() to get the minimum value, and print() to print an object to the terminal.
  • User-Defined Functions (UDFs) are functions that users create.
  • Anonymous functions are also called lambda functions because they are not declared with the standard def keyword.

Declaring, Defining, and Invoking a Function

  • Four steps to defining a function in Python:
  • Use the keyword def to declare the function and follow this up with the function name.
  • Add parameters to the function: they should be within the parentheses of the function and end the line with a colon.
  • Add statements that the functions should execute.
  • End function with a return statement if the function should output something; without it, the function will return an object None.

Syntax of a Python Function

  • def name_of_function(parameters ):
  • Use a docstring to describe the function i.e. """Python Programming"""

Declaring and Defining a User-Defined Function

  • A function defined as def square( num ): returns the square of the number passed to it as an argument.
  • The return keyword returns the value of the function, i.e. return num**2
  • Once a function's framework is complete, it can be called from anywhere in the program.

Function Arguments

  • Types of arguments that call a function: Default arguments, Keyword arguments, Required arguments, and Variable-length arguments.

Default Arguments

  • A parameter with a default value if no value is supplied for the argument when the function is called.
  • For example:
def function(num1, num2 = 40 ):
	print("num1 is: ", num1)
	print("num2 is: ", num2)
## Calling the function and passing only one argument
function(10)

Keyword Arguments

  • Function calls use parameter labels to identify the parameter's value.
  • For example:
def function(num1, num2 ):
  print("num1 is: ", num1)
  print("num2 is: ", num2)

function( num2 = 50, num1 = 30)

Required Arguments

  • These arguments are given to a function in a pre-defined positional sequence during a call.
  • The count of required arguments in the method call must equal the count provided while defining the function.
  • Omitting an argument will cause a syntax error.

Variable-Length Arguments

  • Special characters in Python functions pass as many arguments as are needed.
  • *args are non-keyword arguments.
  • **kwargs are keyword arguments.
  • Example:
def sum(*args):
	resultfinal = 0
	#beginning of for loop
	for arg in args:
		resultfinal = resultfinal + arg  
	return resultfinal
#printing the values
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 2)) #32    

Lambda Functions

  • Lambda Functions in Python are anonymous functions, implying they don't have a name.
  • Use the lambda keyword in Python to define an unnamed function.
  • Syntax lambda arguments: expression
  • Example
add = lambda num: num + 4
print(add(6))
  • A lambda function in code such as lambda num: num+4 has "num" as the parameter and "num +4" as the computed and returned equation.
  • It generates a nameless function object that can be associated with an identifier to refer to it as a standard function.

Local and Global Variables

  • Global variables are not defined inside any function, gives them a global scope.
  • Local variables which are defined inside a function and scope is limited to that function only.
  • Local variables are accessible only inside the function in which it was initialized.
  • Global variables are accessible throughout the program including inside every function.
  • Example of a local variable:
def f():
	# local variable
	s = "Python Programming"
	print(s)
## Driver code
f()
  • Example of a global variable:
## This function uses global variable s
def f():
	print("Inside Function", s)
## Global scope
s = "Python Programming"
f()
print("Outside Function", s)

Immutable Data Types

  • Cannot be changed once declared and consist of Numbers, Strings, and Tuples.
  • Python has four types of number literals: Integer, Long Integer, Floating number, and Complex.
  • Python automatically converts one number type to another in the declaration.
  • Example:
p=10 # Int
py="Python" # String
per=101.20 # Float
  • Immutable data structures are useful when preventing multiple people from modifying a piece of data in parallel programming.
  • Tuples are read-only collections of Python objects separated by commas that are similar to lists in terms of indexing, repetition, and nested objects.
  • Example:
t = ( 0, 1, 2, 3, 4, 5) # Tuple 
t[0]=3 # Invalid
Output: TypeError: 'tuple' object does not support item assignment

Strings

  • Python strings - collections of characters, surrounded by single, double, or triple quotes.
  • Strings are stored internally as a manipulated character combination of 0's and 1's.
  • Each string character is encoded using the ASCII or Unicode standard.
  • Slice operator [] accesses the individual characters of the string.
  • The : (colon) accesses substrings in the string.
  • Examples:
str = "HELLO"
str[0:2] = 'HE' # Returns a string slice
  • A string can only be replaced entirely due to being immutable in Python.
  • del str removes the string.

String operators

  • + is a concatenation operator used to join the strings together.
  • * is a repetition operator is used to concatenate multiple copies of the string.
  • [] - The slice operator is used to access the substrings
  • [:] - The range slice operator is used to access the characters from the specified range.
  • in - Membership operator, tests if substring is present in string.
  • not in - Membership operator, tests if substring is not present in string.
  • r/R - Designates a string as a “raw string”, useful for file paths.
  • % - Performs string formatting (like sprintf in C).

String Functions

  • pf.find(str) - finds first matching string
  • pf.replace(old, new) - replaces old sub string with new
  • split1.split(delimeter) - splits string based on the delimeter
  • sc.count(substring) - counts the occurances of a substring
  • sc.upper() - converts to all uppercase
  • max(s), min(s) - returns the maximum/minimum character respectively

Mutable Data Types

  • Lists, Dictionaries, and Sets can be changed anytime.

Lists

  • Mutable Python data type defined within square brackets []
  • Operations applied on lists: Concatenation, repetition, slicing, append, extend and insert.

List Functions

  • Concatenation adds two or more lists/elements together.
  • Repetition is used to duplicate a list a given number of times.
  • Slicing is same as tuples except it applies to lists.
  • Append is used to add a value to a list.
  • Extend is function of concatenation.
  • Insert includes the use of index value for insertion.

Dictionaries

  • Mutable, consists of group values within a {}-curly braces
  • Contains 2 elements of key, and value.
  • Dictionary functions include:
    • emptyDictionary - No value inside the dictionary
    • Integer Key - Dictionary includes only integer keys
    • Mixed Key - Dictionary includes a mix of keys
    • Pairing - Sequence where each item has a pair
  • Use of len() returns output in numeric as the number of elements in Dictionary.
  • Use of value() return all the values inside the dictionary.
  • Use of key() finds the key to the dictionary.

Sets

  • Sets are mutable and hold unordered collections of unique items within curly braces {}.
  • Sets don't define key-value pairs for elements.
  • Functions for sets include creating a set.
  • Use of Union returns a value from both sets.
  • Use of Intersection returns the common elements from both sets.
  • Use of Difference omits all common values from both sets and returns only that value which is unique and written in the first set.

Variable Length Keyword Arguments

  • Can use multiple keywords as arguments
  • For example
def my_func(**kwargs):
  for k,v in kwargs.items():
    print("%s=%s"%(k,v))

my_func(a_key="Let",b_key="us",c_key="study")

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Untitled
110 questions

Untitled

ComfortingAquamarine avatar
ComfortingAquamarine
Untitled Quiz
6 questions

Untitled Quiz

AdoredHealing avatar
AdoredHealing
Untitled
44 questions

Untitled

ExaltingAndradite avatar
ExaltingAndradite
Untitled
6 questions

Untitled

StrikingParadise avatar
StrikingParadise
Use Quizgecko on...
Browser
Browser