0% found this document useful (0 votes)
41 views40 pages

Joc Shubham

Python is a versatile programming language that can be used for a variety of tasks like web development, data analysis, machine learning, and more. It has a simple syntax, large standard library, and support for object-oriented programming. Functions allow you to organize and reuse code in Python. Functions can return single or multiple values using tuples.

Uploaded by

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

Joc Shubham

Python is a versatile programming language that can be used for a variety of tasks like web development, data analysis, machine learning, and more. It has a simple syntax, large standard library, and support for object-oriented programming. Functions allow you to organize and reuse code in Python. Functions can return single or multiple values using tuples.

Uploaded by

RUTUJA LOKHANDE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

1. Why to choose python? What can we do with python?

Python is a popular programming language that is versatile, easy to learn, and widely used in various
industries. Here are some reasons why you might choose Python:

1. Ease of Learning: Python is known for its simplicity and ease of learning. It has a straightforward
syntax, making it an excellent choice for beginners.

2. Wide range of Applications: Python is used in many applications, including web development,
data analysis, machine learning, scientific computing, game development, and more.

3. Large Community and Support: Python has a vast and active community that regularly
contributes to the language's development. There are numerous online resources and forums
where you can find help and support.

4. Third-Party Libraries: Python has a vast collection of third-party libraries that you can use to add
functionality to your code. These libraries cover various domains, including data science, web
development, and more.

With Python, you can do a wide variety of things, including:

1. Web Development: Python is used for web development, including building dynamic websites, web
applications, and web APIs.

2. Data Analysis and Visualization: Python is commonly used for data analysis and visualization. With
libraries like Pandas and Matplotlib, you can analyze and visualize data in various formats.

3. Machine Learning: Python is a popular language for machine learning and artificial intelligence. With
libraries like TensorFlow, PyTorch, and Scikit-Learn, you can build machine learning models and train
them on large datasets.

4. Scientific Computing: Python is used for scientific computing, including numerical simulations,
statistical analysis, and more.

5. Game Development: Python is used for game development. With libraries like Pygame, you can
build 2D games, and with libraries like Panda3D, you can build 3D games.

Overall, Python is a powerful and versatile language that you can use for a wide range of applications
1. Write a python program to find factorial of a given number using function.

def factorial(num):

if num == 0:

return 1

else:

return num * factorial(num-1)

# Take input from the user

num = int(input("Enter a number: "))

# Check if the number is negative, positive or zero

if num< 0:

print("Factorial cannot be calculated for negative numbers.")

elifnum == 0:

print("The factorial of 0 is 1.")

else:

print(f"The factorial of {num} is {factorial(num)}.")

In this program, we define a function factorial that takes a single parameter num. If num is equal to 0,
the function returns 1. Otherwise, the function calculates the factorial by multiplying num with the
factorial of num-1.

Then, we take an input from the user and check whether the number is negative, positive, or zero. If the
number is negative, we print a message indicating that the factorial cannot be calculated for negative
numbers. If the number is zero, we print a message indicating that the factorial of 0 is 1. Otherwise, we
call the factorial function with the given number and print the result.
1. How to create user defined functions in python?
In Python, you can define your own functions using the def keyword. Here's the general syntax
for defining a function:

def function_name(parameters):
"""
Docstring - This is where you can document what the function does, its parameters, and its
return value(s).
"""
# Code block - This is where you write the code for the function.
# You can use the parameters in this block.
# You can use the return statement to return a value from the function.

Let's say you want to create a function that takes two numbers as arguments and returns their
sum. Here's how you can do it:
def add_numbers(num1, num2):
"""
This function takes two numbers and returns their sum.
"""
sum = num1 + num2
return sum
In this example, the add_numbers function takes two parameters num1 and num2, adds them
together and returns the result. You can call this function and pass two arguments to it like this:
result = add_numbers(10, 20)
print(result) # Output: 30
When you call the add_numbers function with the arguments 10 and 20, it returns the sum 30,
which is then assigned to the variable result. Finally, we print the value of result which is 30.
2. Can python function return multiple values? Justify your answer with example

Yes, in Python, a function can return multiple values as a tuple. Here's an example:

def calculate_stats(numbers):

"""

This function takes a list of numbers and returns their sum, average, and maximum value.

"""

length = len(numbers)

total = sum(numbers)

average = total / length

maximum = max(numbers)

return total, average, maximum

# Call the function with a list of numbers

result = calculate_stats([10, 20, 30, 40, 50])

# Print the returned values

print(result)

In this example, the calculate_stats function takes a list of numbers and returns their sum, average, and
maximum value. We calculate the length, total, average, and maximum of the input list, and return
these values as a tuple.

When we call the calculate_stats function with the list [10, 20, 30, 40, 50], it returns a tuple with the
values (150, 30.0, 50). We assign this tuple to the variable result and print it. The output will be:

(150, 30.0, 50)

You can also use tuple unpacking to assign the returned values to separate variables like this:

total, average, maximum = calculate_stats([10, 20, 30, 40, 50])

print(total) # Output: 150


print(average) # Output: 30.0

print(maximum) # Output: 50

In this example, we use tuple unpacking to assign the returned values to the variables total, average,
and maximum. We can then print these variables to display their values.

1. What is kwargs in python? Explain its use

In Python, kwargs is a special syntax that allows you to pass a variable number of keyword arguments to
a function. kwargs stands for "keyword arguments", and it is usually used in combination with another
special syntax called *args, which allows you to pass a variable number of positional arguments to a
function.

Here's the general syntax for using kwargs:

def function_name(**kwargs):

# Code block - This is where you can use the keyword arguments.

In this syntax, the double asterisks before kwargs indicate that this function will accept a variable
number of keyword arguments. The keyword arguments are passed to the function as a dictionary,
where the keys are the argument names and the values are the argument values.

Here's an example of how to use kwargs in a function:

def print_info(name, **kwargs):

print(f"Name: {name}")

for key, value in kwargs.items():

print(f"{key.capitalize()}: {value}")

# Call the function with some keyword arguments

print_info("John", age=30, city="New York", occupation="Engineer")

In this example, we define a function called print_info that takes a required argument name and a
variable number of keyword arguments using **kwargs. The function first prints the value of the name
argument, and then it loops through all the keyword arguments and prints them with their
corresponding values.

When we call the print_info function with the arguments "John" and age=30, city="New York", and
occupation="Engineer", the function prints the following output:

Name: John

Age: 30

City: New York

Occupation: Engineer

As you can see, the kwargs syntax makes it easy to pass a variable number of keyword arguments to a
function, and to work with these arguments inside the function using a dictionary.
q.6 explain input() and print() function with example
Sure, I'd be happy to explain the input() and print() functions in Python.

input() is a built-in function in Python that allows you to receive input


from a user. It prompts the user to enter some value and then waits for
the user to enter the value and press Enter. The function then returns the
value entered by the user as a string.

Here's an example of how to use input() function:

name = input("What is your name? ")

print("Hello, " + name + "!")

In this example, the input() function prompts the user to enter their
name, and the value entered by the user is stored in the name variable.
The print() function is then used to print out a greeting message that
includes the user's name.

print() is another built-in function in Python that allows you to display


output on the screen. It takes one or more arguments, and it displays the
values of those arguments on the screen.

Here's an example of how to use print() function:

name = "John"
age = 25

print("My name is", name, "and I am", age, "years old.")

In this example, the print() function is used to display a message that


includes the values of the name and age variables. The function takes
multiple arguments, which are separated by commas, and it
automatically adds a space between each argument when it displays
them on the screen. The output of this code would be:

My name is John and I am 25 years old.


Q,7 list datatypes used in python with example
Sure, I'd be happy to explain the different types of lists in Python with
examples.

1. List: A list is an ordered collection of elements, which can be of any data


type, such as integers, strings, or other objects. Lists are mutable, which
means their elements can be modified. Here's an example of how to
create a list:
my_list = [1, 2, 3, "four", "five"]

In this example, my_list is a list that contains five elements. The first
three elements are integers, and the last two elements are strings.
2. Tuple: A tuple is an ordered collection of elements, just like a list.
However, tuples are immutable, which means their elements cannot be
modified once they are created. Here's an example of how to create a
tuple:
my_tuple = (1, 2, 3, "four", "five")

In this example, my_tuple is a tuple that contains five elements. The first
three elements are integers, and the last two elements are strings.
3. Set: A set is an unordered collection of unique elements. Sets are
mutable, which means you can add or remove elements from a set.
Here's an example of how to create a set:
my_set = {1, 2, 3, "four", "five"}

In this example, my_set is a set that contains five elements. The first
three elements are integers, and the last two elements are strings.
4. Dictionary: A dictionary is an unordered collection of key-value pairs,
where each key is unique. Dictionaries are mutable, which means you
can add or remove key-value pairs from a dictionary. Here's an example
of how to create a dictionary:
my_dict = {"name": "John", "age": 25, "city": "New York"}

In this example, my_dict is a dictionary that contains three key-value


pairs. The keys are strings, and the values can be of any data type, such
as strings, integers, or other objects.

Q 8 how to declare list ? can we change or update


list element ?justify your answer
In Python, a list can be declared by enclosing a comma-separated
sequence of elements inside square brackets []. Here's an example:

my_list = [1, 2, 3, "four", "five"]

In this example, my_list is a list that contains five elements. The first
three elements are integers, and the last two elements are strings.

Yes, we can change or update list elements in Python. Lists are mutable,
which means that we can modify the elements of a list after it has been
created. Here are some examples of how to modify a list:

1. Changing an element at a specific index: We can change the value of an


element at a specific index in a list by assigning a new value to that
index. For example:
my_list[3] = "FOUR"

In this example, the value at index 3 of my_list is changed from "four"


to "FOUR".
2. Appending an element to the end of the list: We can add a new element
to the end of a list by using the append() method. For example:
my_list.append("six")

In this example, the string "six" is added to the end of my_list.


3. Inserting an element at a specific index: We can insert a new element at
a specific index in a list by using the insert() method. For example:
my_list.insert(1, "TWO")

In this example, the string "TWO" is inserted at index 1 of my_list,


which pushes the previous element at that index to index 2.

So, to sum up, we can change or update list elements in Python because
lists are mutable. We can modify the elements of a list by changing the
value of an element at a specific index, appending an element to the end
of the list, or inserting an element at a specific index.

Q 9 explain for loop in python with example


In Python, a for loop is used to iterate over a sequence, such as a list,
tuple, or string, and perform some operation on each element of the
sequence. The basic syntax of a for loop in Python is as follows:

yamlCopy code
for variable in sequence: # code to be executed for each element of the
sequence

Here, variable is a new variable that will take on the value of each
element in the sequence, one at a time, and sequence is the sequence of
elements over which the loop will iterate. The code inside the loop's
block will be executed for each element of the sequence.

Here's an example that uses a for loop to iterate over a list of numbers
and print each number:
my_list = [1, 2, 3, 4, 5]

for num in my_list:


print(num)

In this example, we first define a list called my_list that contains five
numbers. We then use a for loop to iterate over each element in my_list.
For each element, we assign its value to the variable num, and then we
print the value of num using the print() function. The output of this code
will be:
1

2
3
4
5

Q 10 compare between list and dictionary


ists and dictionaries are two of the most commonly used data structures
in Python, but they have different properties and are used for different
purposes.

Lists:

 Lists are ordered collections of elements, where each element can be of


any data type.
 Elements in a list can be accessed using their index, which starts at 0 for
the first element.
 Lists are mutable, meaning that their elements can be modified after they
are created.
 Lists are denoted by square brackets [ ].
Here's an example of a list in Python:
my_list = [1, 2, 3, "four", "five"]
Dictionaries:

 Dictionaries are collections of key-value pairs, where each key is


associated with a value.
 Elements in a dictionary are not ordered, so they cannot be accessed
using an index. Instead, they are accessed using their key.
 Dictionaries are mutable, meaning that their keys and values can be
modified after they are created.
 Dictionaries are denoted by curly braces { }.

Here's an example of a dictionary in Python:

my_dict = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}

Comparison:

 Lists are useful when we need to store an ordered collection of elements,


and we want to access these elements by their index. For example, if we
want to store a list of temperatures for each day of the week, we can use
a list.
 Dictionaries are useful when we need to store a collection of key-value
pairs, and we want to access the values by their key. For example, if we
want to store the phone numbers of our friends, we can use a dictionary
where the keys are the names of our friends and the values are their
phone numbers.
 Lists can have duplicate elements, while dictionaries require unique
keys.
 Lists are best used when order is important, while dictionaries are best
used when we need to look up values based on their associated keys.
11. Why use recursion in programming? What are the advantage and
disadvantage of recursion Recursion is a powerful programming technique in
which a function calls itself to solve a problem. It can be used to solve problems
that can be broken down into smaller sub-problems, such as sorting algorithms,
tree traversals, and mathematical calculations. The advantages of using recursion
in programming include:

1)Simplicity: Recursion can often simplify code and make it easier to understand,
as it breaks down a problem into smaller, more manageable parts.

2)Readability: Recursive code can be more readable than iterative code in some
cases, as it closely mirrors the problem-solving process.

3)Efficiency: Recursive algorithms can be more efficient than their iterative


counterparts in some cases, particularly when dealing with complex data
structures.

However, there are also some disadvantages of using recursion in programming,


including:

1)Stack Overflow: If a recursive function calls itself too many times, it can cause a
stack overflow error, which can crash the program.

2)Performance: Recursive algorithms can be less efficient than iterative


algorithms in some cases, particularly when dealing with large data sets or
complex problems.

3)Debugging: Recursive code can be more difficult to debug than iterative code,
as it can be hard to trace the execution path of a recursive function. In Python,
recursion can be implemented using function calls. The language allows for tail
recursion optimization, which can help to reduce the risk of stack overflow errors.
However, it is important to be aware of the potential downsides of recursion
when using it in Python.
12. List and explain numeric data types in python with example

In Python, there are four built-in numeric data types.

These are:

1)Integer (int): It represents a whole number without any fractional part. For
example, 10, 20, -30, etc.

2)Float: It represents real numbers and contains a decimal point. For example,
3.14, -2.5, 0.0, etc.

3)Complex: It represents a number with a real and imaginary part. It is written in


the form a + bj, where a is the real part and b is the imaginary part. For example,
2+3j, 4-2j, etc.

4)Boolean (bool): It represents a truth value, which can either be True or False.

Here are some examples of each data type in Python:

# integer examples

a = 10

b = -20

c=0

# float examples

x = 3.14

y = -2.5 z = 0.0

# complex examples

m = 2 + 3j

n = 4 - 2j

p = complex(5, -6)
# boolean examples

q = True r = False

s = 10 > 5
In the above examples, a, b, and c are integers, x, y, and z are floats, m, n, and p
are complex numbers, and q, r, and s are boolean values.
13. Write a program to demonstrate the use of while loop

# program to print numbers from 1 to 10 using while loop

i = 1 # initialize a counter variable

while i <= 10: # loop condition

print(i) # print the current value of

i i += 1 # increment i by 1

print("Done!") # print a message after the loop has completed

In the above program, we initialize a counter variable i to 1. We then use a while


loop with the condition i <= 10 to print the numbers from 1 to 10. Inside the loop,
we print the current value of i using the print() function, and then increment i by 1
using the += operator. This process continues until the loop condition becomes
False (i.e., i becomes greater than 10). After the loop has completed, we print a
message to indicate that the program is done. When you run this program, it
should output the following:

10
Done! Note that the while loop will continue to execute as long as the condition i
<= 10 is True. Once i becomes greater than 10, the loop will terminate and the
program will continue with the next statement after the loop
14. Explain python dictionary with example A dictionary in Python is a
collection of key-value pairs, where each key is associated with a value.
The keys in a dictionary must be unique and immutable, while the
values can be of any data type, including lists, tuples, strings, numbers,
and other dictionaries. Dictionaries are mutable, which means that
their contents can be changed after they are created.

Here's an example of a Python dictionary:

# create a dictionary of student grades

grades = {'Alice': 85, 'Bob': 70, 'Charlie': 92, 'David': 88}

# print the dictionary

print(grades)

In this example, we create a dictionary called grades that maps the


names of students to their grades. The keys in the dictionary are strings
('Alice', 'Bob', 'Charlie', and 'David'), while the values are integers
representing the grades. We then use the print() function to display the
entire dictionary:

Arduino

Copy code

{'Alice': 85, 'Bob': 70, 'Charlie': 92, 'David': 88}

To access the value associated with a particular key in the dictionary,


we can use the square bracket notation []:

Python

Copy code
# get Alice's grade from the dictionary

alice_grade = grades['Alice']

# print Alice's grade

print("Alice's grade is:", alice_grade)

In this example, we use the key 'Alice' to retrieve the value associated
with that key from the grades dictionary. We assign the value to a
variable called alice_grade and then print it out: Alice's grade is: 85

We can also add, remove, and modify items in a dictionary using


various methods. For example, we can add a new key-value pair to the
grades dictionary like this:

# add a new student to the dictionary

grades['Eve'] = 79

# print the updated dictionary

print(grades)

This will add a new key-value pair ('Eve': 79) to the grades dictionary
and then print out the entire dictionary:

{'Alice': 85, 'Bob': 70, 'Charlie': 92, 'David': 88, 'Eve': 79}

Overall, dictionaries are a powerful and versatile data structure in


Python that can be used to store and manipulate complex data in a
variety of ways.
15. Compare between list and tuple

Lists and tuples are both built-in data structures in Python, but they
have some key differences that make them useful in different contexts.
Here are some of the main differences between lists and tuples:

1)Mutability: One of the biggest differences between lists and tuples is


that lists are mutable, while tuples are immutable. This means that you
can add, remove, or modify elements in a list after it is created, but you
cannot do so with a tuple. If you try to modify a tuple, you will get a
TypeError.

2)Syntax: Lists are defined using square brackets ([]), while tuples are
defined using parentheses (()). For example, you might create a list of
numbers like this: numbers = [1, 2, 3], and a tuple of strings like this:
names = ('Alice', 'Bob', 'Charlie').

3)Length: Lists can be of any length, while tuples have a fixed length
once they are created. If you try to add or remove elements from a
tuple, you will get a TypeError.

4)Usage: Lists are typically used for collections of items that may need
to be modified, while tuples are used for collections of items that
should not be modified. For example, you might use a list to store the
scores of a basketball game, since those scores might change over time.
On the other hand, you might use a tuple to represent the coo
Q.16 Explain the use of string in python. Show string slicing operation with
example

In Python, a string is a sequence of characters enclosed within quotation marks, which


can be either single quotes (' ) or double quotes (" ). Strings are immutable objects,
which means that once they are created, their contents cannot be changed.

Strings in Python are used to represent textual data such as names, addresses, and
messages, among others. They can be manipulated and processed in various ways using
built-in string methods and operators.

Here is an example of creating and manipulating a string in Python:

# creating a string

message = "Hello, World!"

# printing the string

print(message)

# accessing individual characters in the string

print(message[0]) # prints 'H'

print(message[6]) # prints 'W'

# slicing the string to get a substring

print(message[0:5]) # prints 'Hello'

print(message[7:]) # prints 'World!'

In the above example, we create a string variable named message and assign it the value
"Hello, World!". We then print the entire string using the print() function.

Next, we use indexing to access individual characters within the string. We print the first
character (which is at index 0) using message[0], and the seventh character (which is at
index 6) using message[6] .
Finally, we use slicing to extract a substring from the original string. Slicing allows us to
specify a range of indices to extract a portion of the string. In the example, message[0:5]
extracts the substring from the first character to the fifth character (exclusive), which is
"Hello" . message[7:] extracts the substring from the eighth character to the end of the
string, which is "World!" .
Q.17 Show the use of if-else in python with example
In Python, the if-else statement is used to conditionally execute a block of code based on a
specified condition. The general syntax of the if-else statement in Python is as follows:

if condition:

# Execute code if condition is True

else:

# Execute code if condition is False

Here is an example of using the if-else statement in Python:

# Prompt the user to enter a number

num = int(input("Enter a number: "))

# check if the number is positive, negative, or zero

if num> 0:

print("The number is positive")

elifnum< 0:

print("The number is negative")

else:

print("The number is zero")

In the above example, we prompt the user to enter a number using the input() function,
and convert the input value to an integer using the int() function.

Next, we use an if-else statement to check the value of the number. If the number is
greater than zero, we print a message saying that the number is positive. If the number
is less than zero, we print a message saying that the number is negative. If the number is
equal to zero, we print a message saying that the number is zero.

Note that the elif clause stands for "else if", and allows us to test multiple conditions in
sequence. If the condition in the if clause is not met, the code in the elif clause is
executed. If none of the conditions is true, the code in the else clause is executed.
Q.18 Develop a python program to find factorial of given a number using
function
Here is an example Python program that calculates the factorial of a given number using a
function:

def factorial(num):

if num == 0:

return 1

else:

return num * factorial(num - 1)

# prompt the user to enter a number

num = int(input("Enter a number: "))

# calculate the factorial of the number

result = factorial(num)

# print the result

print("The factorial of", num, "is", result)

In this program, we define a function named factorial that takes a single argument num.
The function uses recursion to calculate the factorial of the number. If the input number
is 0, the function returns 1 (since 0! = 1). Otherwise, the function multiplies the input
number by the factorial of the number one less than it.

Next, we prompt the user to enter a number using the input() function, and convert the
input value to an integer using the int() function.

We then call the factorial() function with the user's input as the argument, and store
the result in a variable named result .

Finally, we print the result of the factorial calculation using the print() function.
Q.19 What is python? What are the benefits of using python?

Python is a popular high-level, interpreted programming language that was first


released in 1991 by Guido van Rossum. It is designed to be simple, easy to learn, and
highly expressive, with a clean syntax and dynamic semantics. Python is used for a wide
range of applications, including web development, scientific computing, data analysis,
artificial intelligence, machine learning, and more.

Here are some of the key benefits of using Python:

1. Easy to Learn and Use: Python has a simple and intuitive syntax that is easy to
read and write. This makes it a great language for beginners to learn, as well as
for experienced programmers who want to write code more quickly and
efficiently.
2. Large Standard Library: Python comes with a large standard library that provides
a wide range of tools and modules for many common programming tasks, such
as working with databases, processing text and files, and more. This makes it easy
to build complex applications without having to write a lot of custom code.
3. Cross-Platform: Python is a cross-platform language, which means that it can run
on many different operating systems, including Windows, Mac OS, Linux, and
more. This makes it easy to develop and deploy applications across multiple
platforms without having to rewrite the code.
4. Open Source: Python is an open-source language, which means that it is free to
use, distribute, and modify. This has led to a large and active community of
developers who contribute to the language and create a wide range of tools and
libraries.
5. High-Level Language: Python is a high-level language, which means that it
abstracts away many low-level details of the machine, such as memory
management and hardware access. This makes it easier to write code that is more
focused on solving the problem at hand, rather than on managing the details of
the system.
6. Versatile: Python can be used for a wide range of applications, from simple scripts
to complex web applications and scientific computing. Its flexibility and versatility
make it a great choice for many different types of projects and teams.
Q.20 What are lists and tuple? What is the key difference between two.

In Python, a list is a collection of values that can be of any data type, including other
lists. A tuple, on the other hand, is a collection of values that can be of any data type,
but once created, it cannot be modified (immutable).

Here are some key differences between lists and tuples in Python:

1. Mutable vs. Immutable: Lists are mutable, which means that you can add, remove,
or modify elements in a list after it has been created. Tuples, on the other hand,
are immutable, which means that once a tuple is created, you cannot add,
remove, or modify elements in it.
2. Syntax: Lists are created using square brackets [] , while tuples are created using
parentheses () .
3. Performance: Tuples are generally faster than lists when it comes to accessing
elements because they are stored in a contiguous block of memory. Lists, on the
other hand, may require multiple memory allocations if they grow too large,
which can affect performance.
4. Use Cases: Lists are generally used for collections of data that may need to be
modified over time, such as arrays or lists of user inputs. Tuples, on the other
hand, are often used to represent fixed collections of data, such as the
coordinates of a point or the RGB values of a color.

Here are some examples of creating and using lists and tuples in Python:

Creating a list:

my_list = [1, 2, 3, "four", 5.0]


Modifying a list:

my_list[0] = "one"

my_list.append(6)
Creating a tuple:

my_tuple = (1, 2, 3, "four", 5.0)


Accessing elements of a tuple:

print(my_tuple[0]) # prints 1
Trying to modify a tuple will result in a TypeError :

my_tuple[0] = "one" # raises TypeError


21] What is function? Explain python function with an example
In computer programming, a function is a named block of code that performs a
specific task. Functions are used to break down a larger problem into smaller,
more manageable parts, which makes the code more organized, easier to read,
and easier to maintain.
In Python, a function is defined using the "def" keyword, followed by the name of
the function, a set of parentheses, and a colon. The code that makes up the
function is indented below the function definition. Here's an example:
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
In this example, we define a function called greet that takes one argument,
name. The function simply prints a greeting to the console, using the name
argument in the message. We then call the function with the argument "Alice",
causing it to print "Hello, Alice!" to the console.
Functions can also return values, which can be useful for passing data between
different parts of a program. Here's an example:
defadd_numbers(x, y):
result = x + y
return result
sum = add_numbers(3, 5)
print(sum)
In this example, we define a function called add_numbers that takes two
arguments, x and y, and returns their sum. We then call the function with the
arguments 3 and 5, which returns the value 8. We store this value in a variable
called sum, and then print it to the console. The output of this program will be
"8".
22] What do you mean by conditional statement? Explain conditional statement
in python with an example
A conditional statement is a programming construct that allows the execution of
different code blocks based on whether a certain condition is true or false. In
Python, the most common conditional statement is the if statement.
The syntax for an if statement in Python is as follows:
if condition:
# code block to be executed if condition is true
Here, the condition is an expression that evaluates to either True or False. If the
condition is true, then the code block indented below the if statement will be
executed.
For example, let's say we want to write a program that checks if a number is
positive or negative. We can use an if statement to do this as follows:
num = -5
ifnum>= 0:
print("The number is positive")
else:
print("The number is negative")
In this example, the if statement checks whether the value of num is greater than
or equal to zero. If it is, then the program prints "The number is positive". If the
condition is false, then the program executes the code block after the else
statement and prints "The number is negative". Since num is -5 in this example,
the program will print "The number is negative"
23] In Python, there are two types of loops: for loop and while loop. Let's take a
look at each of them with an example:
1. for loop
The for loop in Python is used to iterate over a sequence (e.g., a list, tuple, string,
etc.) and execute a block of code for each item in the sequence. The syntax for
the for loop is as follows
# code block to be executed for
each item
Here, item is a variable that represents each item in the sequence, and sequence
is the sequence of items to be iterated over.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output-
apple
banana
cherry
In this example, the for loop iterates over the list fruits and prints each item in the
list.
2. while loop
The while loop in Python is used to execute a block of code repeatedly as long as
a certain condition is true. The syntax for the while loop is as follows
while condition:
# code block to be executed
repeatedly as long as condition is true
Here, condition is an expression that evaluates to either True or False. The code
block will be executed repeatedly as long as condition is true.
Example:
count = 0
while count < 5:
print(count)
count += 1
Output
0
1
2
3
4
In this example, the while loop executes the code block repeatedly as long as the
count variable is less than 5. The print statement inside the loop prints the
current value of count, and the count += 1 statement increments the value of
count by 1 in each iteration.
These are the two most common looping conditions in Python that can be used to
execute code repeatedly.
24] What are the common built-in data types in Python?
Python has several built-in data types that are used to represent various kinds of
data. The most commonly used built-in data types in Python are:
1]Numeric Types: These are used to represent numeric values. There are three
types of numeric types in Python:
int (integer)
float (floating-point number)
complex (complex number)
2]Boolean Type: This is used to represent Boolean values (True or False).
3]String Type: This is used to represent a sequence of characters.

4]List Type: This is used to represent a sequence of values that can be modified.

5]Tuple Type: This is used to represent a sequence of values that cannot be


modified.

6]Set Type: This is used to represent a collection of unique values.

7]Dictionary Type: This is used to represent a collection of key-value pairs.

Example
# Numeric types
x = 5 #int
y = 3.14 # float
z = 2 + 3j # complex

# Boolean type
is_true = True
is_false = False

# String type
name = "Alice"

# List type
fruits = ["apple", "banana", "cherry"]

# Tuple type
numbers = (1, 2, 3, 4)

# Set type
unique_numbers = {1, 2, 3, 4}

# Dictionary type
person = {"name": "Alice", "age": 25, "gender": "female"}
These are some of the common built-in data types in Python that are used to
represent different kinds of data.
25]Python an interpreted language. Explain
Yes, Python is an interpreted language.
An interpreted language is a programming language where the code is executed
directly, without the need for a separate compilation step. In other words, the
source code of an interpreted language is directly executed by an interpreter,
which translates and executes the code line-by-line.
In the case of Python, the Python interpreter reads and executes the source code
of a Python program directly. When a Python program is run, the interpreter first
checks the syntax of the program for any errors. If the syntax is correct, then the
interpreter executes the program line-by-line, translating and executing each line
as it goes.
This is in contrast to a compiled language like C or Java, where the source code is
first compiled into machine code before it can be executed. In a compiled
language, the compilation step is separate from the execution step, and the
resulting machine code can be executed directly by the computer.
The fact that Python is an interpreted language has some implications for its
performance and portability. Interpreted languages are generally slower than
compiled languages, since the interpreter has to translate and execute the code
on-the-fly. However, interpreted languages are also more portable, since the
same code can be run on any platform that has a compatible interpreter installed.

In summary, Python is an interpreted language, which means that its code is


executed directly by an interpreter, without the need for a separate compilation
step.
26]What is computing?
Computing refers to the use of computers and computing technology to process,
manage, and communicate information. Computing involves the use of
algorithms, software, and hardware to perform a wide range of tasks, from basic
data processing to complex data analysis and machine learning.
Computing technology has become an integral part of modern society, with
applications in virtually every industry and aspect of our lives, including business,
science, medicine, entertainment, communication, education, and more.
Computing enables us to automate routine tasks, process large amounts of data,
create and share digital content, communicate and collaborate with others in
real-time, and solve complex problems that would be difficult or impossible to
solve by hand.
The field of computing is constantly evolving, with new technologies and
innovations emerging at a rapid pace. Some of the key areas of computing
include:
Computer science: the study of algorithms, programming languages, and
computer architecture, among other topics.
Software engineering: the development and maintenance of software systems.
Data science: the extraction of insights and knowledge from large and complex
data sets.
Artificial intelligence: the development of intelligent systems that can perform
tasks that typically require human-level intelligence, such as natural language
processing, image recognition, and decision making.
Cybersecurity: the protection of computer systems and networks from
unauthorized access and attacks.
Overall, computing plays a crucial role in shaping the way we work, communicate,
and live our lives, and its importance is only expected to grow in the years to
come.
27] How do we declare variable in python and keyword used to check data
type? Explain
with an example
In Python, we can declare a variable simply by assigning a value to it using the
equal sign (=). Python is a dynamically typed language, which means that the data
type of a variable is determined at runtime based on the type of value assigned to
it.
To check the data type of a variable in Python, we can use the built-in type()
function. This function returns the data type of the given object as a string.
Here's an example of how to declare a variable and check its data type:
# Declare a variable and assign a value
x = 42

# Check the data type of the variable


print(type(x)) # Output: <class 'int'>
In this example, we declare a variable x and assign the value 42 to it. We then use
the type() function to check the data type of x, which in this case is an integer
(int).

Here's another example that shows how to declare variables of different data
types and check their types:
# Declare variables of different data types
name = "Alice"
age = 25
is_male = False
height = 1.75
# Check the data types of the variables
print(type(name)) # Output: <class 'str'>
print(type(age)) # Output: <class 'int'>
print(type(is_male)) # Output: <class 'bool'>
print(type(height)) # Output: <class 'float'>
In this example, we declare four variables of different data types (name, age,
is_male, and height) and assign values to them. We then use the type() function
to check the data types of each variable, which are a string (str), an integer (int), a
boolean (bool), and a float (float), respectively.
Overall, declaring variables and checking their data types is a fundamental aspect
of Python programming, and the type() function is a useful tool for working with
variables of different data types.

You might also like