You are on page 1of 8

1.Explain feature of python?

Ans:- Free and Open Source, Easy to code, Object-Oriented Language, GUI Programming Support,
High-Level Language, Large Community Support, Python is a Portable language, Python is an
Integrated language.

2. python identifiers?

Ans:- Python Identifier is the name we give to identify a variable, function, class, module or other
object. That means whenever we want to give an entity a name, that's called identifier.

3.How to declare variable?

Ans:- type variableName = value;

4.Reseved Keywords?

Ans:- and, else, while ,as, except, with, assert, finally, yield, break, for.

5.Importance of indentation?

Ans:- In computer programming languages, indentation is used to format program source code to
improve readability. Indentation is generally only of use to programmers; compilers and
interpreters rarely care how much whitespace is present in between programming statements.

6.Explain single line and multi line comment?

Ans:- Single-line comments start with two forward slashes ( # ). Any text between # and the end of
the line is ignored by the compiler./ Multiline comments are used for large text descriptions of
code or to comment out chunks of code while debugging applications.

7.Describe built in data type in python?

Ans:- Numeric data types: int, float, complex./String data types: str./Sequence types: list, tuple,
range./Binary types: bytes, bytearray, memoryview./Mapping data type: dict./Boolean type: bool.

8.What is list?

Ans:- A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements.

9.Explain Any 5 method of list with examples?

Ans:-Append(), Clear(), Count(), Copy(), index().

String:-lower(), split(), index(), join(), upper.

Tuple:-Count(), Index().

Dictionary:-update(), values(), pop(), Keys(), copy().

Set:-Pythonsetpop(), pythonsetclear(), pythonsetcopy(), pythonsetadd(),pythonsetupadte().

14. ?

Ans:- Arithmetic operators take precedence over logical operators. Python will always evaluate the
arithmetic operators first (** is highest, then multiplication/division, then addition/subtraction).
15.Describe bitwise operator?

Ans:- Python bitwise operators are used to perform bitwise calculations on integers. The integers
are converted into binary format and then operations are performed bit by bit, hence the name
bitwise operators.

16.Describe Logical Operator?

Ans:- Logical Operators in Python are used to perform logical operations on the values of variables.
The value is either true or false. We can figure out the conditions by the result of the truth values.
There are mainly three types of logical operators in python: logical AND, logical OR and logical
NOT.

17.Explain how to convert the type of one data into another?

Ans:- In Python, you can simply use the bin() function to convert from a decimal value to its
corresponding binary value. And similarly, the int() function to convert a binary to its decimal
value. The int() function takes as second argument the base of the number to be converted, which
is 2 in the case of binary numbers.

22. explain syntax of if-else with example in python?

Ans:- In case else is not specified, and all the statements are false , none of the blocks would be
executed. Here's an example: if 51<5: print("False, statement skipped") elif 0<5: print("true, block
executed") elif 0<3: print("true, but block will not execute") else: print("If all fails.")

23.Explain Condition statement with example?

Ans:- If the condition is True, the code block indented below the if statement will be executed. If
the condition is False, the code block will be skipped. Here's an example of how to use an if
statement to check if a number is positive: num = 5 if num > 0: print("The number is positive.")

24.Explain Nested if-else with example?

Ans:- Python nested “if else”. consider the following scenario: If num is greater than 0 , check if
num is even by checking if the remainder when num is divided by 2 is 0 . If the remainder is 0 ,
execute the code block that prints the message “The number is positive and even.Ex:- num = 5 if
num > 0: print("The number is positive.")else: if num < 0: print("The number is negative.")
else: print("The number is zero.").

25.explain how while loop is executing with example?

Ans:- A while loop is a control flow statement that allows you to repeatedly execute a block of
code as long as a specific condition is true. It is commonly used when you don't know the exact
number of iterations in advance and need to keep executing the code until the condition becomes
false.ex:- i = 1 while i <= 5: print("KnowledgeHut by upGrad") i = i + 1.

26.Explain importance of break and continue statement in loops with example?

Ans:- We can use the break statement with the for loop to terminate the loop when a certain
condition is met. For example, for i in range(5):if i == 3: break print(i).

We can use the continue statement with the for loop to skip the current iteration of the loop. Then
the control of the program jumps to the next iteration. For example, for i in range(5): if i == 3:
continue print(i).
27.Explain the syntax of for loop and apply it for string with example?

Ans:- The first word of the statement starts with the keyword “for” which signifies the beginning of
the for loop.Then we have the iterator variable which iterates over the sequence and can be used
within the loop to perform various functionsThe next is the “in” keyword in Python which tells the
iterator variable to loop for elements within the sequenceAnd finally, we have the sequence
variable which can either be a list, a tuple, or any other kind of iterator.The statements part of the
loop is where you can play around with the iterator variable and perform various function

word="anaconda" for letter in word: print (letter).

28.Explain any 4 math function?

Ans:- log10(x) Returns the base-10 logarithm of x, pow(x, y) Returns x raised to the power y, sqrt(x)
Returns the square root of x, acos(x) Returns the arc cosine of x.

29.Explain Any 4 random function?

Ans:- getrandbits() Return an integer with a specified number of bits, randrange() Returns a
random number within the range, randint() Returns a random integer within the range, choice()
Returns a random item from a list, tuple, or string

33.Explain slicing method of string with example?

Ans:- Strings are immutable data types in Python. We cannot update the string's value. Slicing
strings create a substring from the original string. Slicing means extracting a part from something,
and slicing a string means extracting some part from a string. The slice() method returns an object
containing the range of string slicing. The parameter includes a set of range of values defined as
(start, stop, step). Let's look at the syntax of the slice method().Ex:- string = 'Coding Ninjas'
print(string[slice(6)])

34. explain spliting method of string with example in python?

Ans:- When you need to split a string into substrings, you can use the split() method. The split()
method acts on a string and returns a list of substrings. The syntax is:
<string>.split(sep,maxsplit)Ex:- my_string = "Apples,Oranges,Pears,Bananas,Berries"
my_string.split(",")

35. explain linear search with example?

Ans:- Linear search is a method of finding elements within a list. It is also called a sequential
search. It is the simplest searching algorithm because it searches the desired element in a
sequential manner. It compares each and every element with the value that we are searching for. If
both are matched, the element is found, and the algorithm returns the key's index position.Ex:-
list1 = [1 ,3, 5, 4, 7, 9] key = 7 n = len(list1) res = linear_Search(list1, n, key) if(res == -1):
print("Element not found") else: print("Element found at index: ", res).

36.Explain binary search with example?

Ans:- A binary search is an algorithm to find a particular element in the list. Suppose we have a list
of thousand elements, and we need to get an index position of a particular element. We can find
the element's index position very fast using the binary search algorithm.There are many searching
algorithms but the binary search is most popular among them.The elements in the list must be
sorted to apply the binary search algorithm. If elements are not sorted then sort them first.
Programs:-

1.Prime No. program?

Ans:- num = 11 break

if num > 1: else:

for i in range(2, int(num/2)+1): print(num, "is a prime number")

if (num % i) == 0: else:

print(num, "is not a prime number") print(num, "is not a prime number")

2.Factorial Program?

Ans:- def factorial(n): num = 5

return 1 if (n==1 or n==0) else n * print("Factorial of",num,"is",factorial(num))


factorial(n - 1)

3.Armstrong no. Program?

def power(x, y): while (x != 0): r = temp % 10

if y == 0: n=n+1 sum1 = sum1 +


power(r, n)
return 1 x = x // 10
temp = temp // 10
if y % 2 == 0: return n
return (sum1 == x)
return power(x, y // 2) def isArmstrong(x):
* power(x, y // 2) x = 153
n = order(x)
return x * power(x, y // print(isArmstrong(x))
temp = x
2) * power(x, y // 2)
x = 1253
sum1 = 0
def order(x):
print(isArmstrong(x))
while (temp != 0):
n=0

4.Reverse String Program?

Ans:-

def reverse(s): s = "Geeksforgeeks"

str = "" print("The original string is : ", end="")

for i in s: print(s)

str = i + str print("The reversed string(using loops) is : ",


end="")
return str
print(reverse(s))
5.ascii value of given character program?

Ans:- c = 'g'

print("The ASCII value of '" + c + "' is", ord(c))

6. split multi line string into list with every element as word or sentence in python?

Ans:- def convert(lst): lst = 'Geeksforgeeks is a portal for geeks'

return ([i for i in lst.split()]) print( convert(lst))

7. find a symbol replace a particular symbol?

Ans:- string = "grrks FOR grrks"

new_string = string.replace("r", "e" )

print(string)

print(new_string)

8. identify if the character is digit is alphabet digit or alphanumeric in given string?

Ans:- ch = input("Please Enter Any Character : ")

if((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):

print("The Given Character ", ch, "is an Alphabet")

elif(ch >= '0' and ch <= '9'):

print("The Given Character ", ch, "is a Digit")

else:

print("The Given Character ", ch, "is a Special Character")


Differences

1. List and String

List String
List is a collection of elements, each element
String is a sequence of characters (text).
can be of any data type (int, float, str, etc.).
Lists are mutable, which means you can modify Strings are immutable, meaning you cannot
their elements change their individual characters after
creation.
Lists do not support repetition Strings support repetition

Lists have methods like append(), insert(), Strings have methods like strip(), split(),
remove(), and more for element manipulation. replace(), and more for string manipulation.
You can convert a list to a string using functions You can convert a string to a list using the split()
like join(). method.
Strings are defined using single or double
Lists are defined using square brackets
quotes
Elements or slices can be deleted from a list
Characters or slices cannot be deleted from a
using the del statement or the remove()
string.
method.
Strings are more memory-efficient because
Lists generally consume more memory due to
they store characters as-is without additional
the overhead of storing references to objects.
references.
Strings are used to work with text data,
Lists are typically used to store collections of
manipulate textual information, and represent
items, such as numbers, objects, or other lists.
sequences of characters.
mixed_list = [1, "two", 3.0, "four", True] String1 = "Hello, Python!"

Dictionary Set
Elements are unique; duplicates are automatically
Keys must be unique; values can be duplicated.
removed.
Sets do not support indexing or key-value access.
Dictionaries are accessed by their keys. You can use a You can use sets to check for the presence of
key to look up the associated value elements but cannot directly access elements by
their position.
Dictionaries are defined using curly braces and colon Sets are defined using curly braces without colons to
to separate keys and values denote elements
Set methods involve operations on individual Dictionary methods involve operations on key-value
elements, such as adding, removing, and checking pairs, including adding, modifying, removing, and
for existence. looking up values by keys.
Managing collections of unique elements, set
Key-value storage, mappings, data retrieval.
operations.
my_dict = {'name': 'John', 'age': 30} my_set = {1, 2, 3, 4}
List Tuple

Defined using square brackets []. Defined using parentheses ().


Lists are mutable; elements can be added, modified, Tuples are immutable; elements cannot be changed
or removed after creation. or added after creation.
You can add, modify, or remove elements using Elements cannot be added or removed after
methods like append(), insert(), and remove(). creation.
Commonly used for dynamic collections and data Often used for situations where data should not
where elements might change. change after creation
Tuples consume less memory due to their
Lists consume more memory due to their mutability.
immutability.
Can be used to storing a list of user preferences that Can be used to represent a point in 2D space, where
can change. x and y coordinates don't change.
my_list = [1, 2, 3] my_tuple = (1, 2, 3)

Tuple String
Defined using parentheses (). Defined using single or double quotes '' or "".
Tuples store ordered collections of elements Strings store ordered collections of characters.
Strings store sequences of characters (usually
Tuples can store elements of different data types.
Unicode characters).
Strings can be iterated through character by
Tuples can be iterated through using for loops.
character.
Searching for an element in a tuple can be slower, as Searching for a substring in a string can be more
it involves linear searching. efficient, thanks to built-in string search algorithms.
Tuples have fewer built-in methods compared to Strings have a wide range of built-in methods for
strings. string manipulation, formatting, and more.
Tuples are often used to represent fixed data Strings are used for representing and manipulating
structures like coordinates, records etc. text and formatting messages.
my_tuple = (1, 2, 3) my_string = "Hello, World!"
List Array
List is a built-in data structure in Python defined Arrays are not a built-in data type in Python.
Arrays are often used with external libraries, such as
Lists are part of Python's standard library.
NumPy.
Arrays can store elements of the same data type
Lists can store elements of various data types.
(homogeneous arrays).
Lists can grow or shrink dynamically as elements are Arrays have a fixed size when created; resizing typically
added or removed. requires creating a new array.
Lists may be slower for numerical operations due to their Arrays are optimized for numerical operations and
dynamic nature provide better performance
Lists may consume more memory due to dynamic sizing Arrays can be more memory-efficient due to
and storage of diverse data types. homogeneity
Lists are versatile and suitable for general-purpose data Arrays are used for numerical and scientific computing,
where performance and mathematical operations are
storage and manipulation.
crucial.
import numpy as np
my_list = [1, 2, 3, 4, 5]
my_array = np.array([1, 2, 3, 4, 5])
Array
String
A built-in data type in Python defined using single or
Created using external libraries like NumPy.
double quotes '' or "".
Typically stores elements of the same data type
Stores sequences of characters, often representing text.
(homogeneous).
Strings are immutable; their length doesn't change after Arrays have a fixed size when created, resizing typically
creation. requires creating a new array.
Efficient for string operations, including searching, slicing, Arrays are optimized for numerical operations and
and formatting. provide better performance.
Arrays can be more memory-efficient due to
Efficient in memory consumption for text data.
homogeneity.
Arrays are used for numerical and scientific computing,
Used for representing and manipulating text data,
where performance and mathematical operations are
parsing, formatting, and more.
crucial.
import numpy as np
my_string = "Hello, World!"
my_array = np.array([1, 2, 3, 4, 5])

2. Array and string

You might also like