List four string functions in python ?
â«.capitalize()
â«.upper()
â«.lower()
â«.join()
â«.islower()
â«.isupper()
Explain with example the use of single, double, triple quotes in python?
Quotation symbols are used to create string object in Python. Python recognizes single, double and triple quoted strings. String literals are written by enclosing a sequence of characters in single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""")
Write the equivalent python expression. âð(ððð ð)2+ð(ð ððð)2 ?
import math
r = 10
a = 1
ans = sqrt(r*cos(a)**2+r*sin(a)**2)
print(ans)
What are the key features of python?
1. Easy to Code
2. Easy to Read
3. Free and Open-Source
4. Robust Standard Library
5. Object-Oriented and Procedure-Oriented
Write python code to read a string and print it in reverse.
str = "Hello"
print(str[::-1])
Output:olleH
What are the built-in types available in python?
Binary Types: memoryview, bytearray, bytes.
Boolean Type: bool.
Set Types: frozenset, set.
Mapping Type: dict.
Sequence Types: range, tuple, list.
Numeric Types: complex, float, int.
Text Type: str.
Write a two difference between a list and a tuple?
list:
â«Lists are mutable
â«The implication of iterations is Time-consuming
â«Lists consume more memory
Tuple
â«Tuples are immutable
â«The implication of iterations is comparatively Faster
â«Tuple consumes less memory as compared to the list
Write one line code to print number from 6 to 25 in base 8, and base 16?
for x in range(6,26):
print(hex(x))
print(oct(x))
How to convert a list into other data types?
You can convert a list into string using str() function
str = " "
li = [1,"Hello","This is a list","will be converted to a string"]
for x in li:
str+=x
print(str)
List any five data types in python?
Python has five standard Data Types:
â«Numbers
â«String
â«List
â«Tuple
â«Dictionary
Find the output: a,b,c,d=25,0x25,0o25,0b1101; print(a,b,c,d).
Output: 25,37,21,13
Find the output: x=100; print("{:8b}{:8d}{:8x}{:8o}{:e}".format(x,x,x,x,x))
Output: 1100100,100,64,1441.000000e+02
What are keywords? Give Example?
Python keywords are special reserved words that have specific meanings and purposes and can't be used for anything but those specific purposes. These keywords are always availableâyou'll never have to import them into your code.
Example: for , if , while , break etc..
What is return statement?
The Python return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. A return statement consists of the return keyword followed by an optional return value.
State about logical operator available in python with example?
Logical operators in Python are used for conditional statements are true or false.
Logical operators in Python are AND, OR and NOT. For logical operators following condition are applied.
For AND operator â It returns TRUE if both the operands (right side and left side) are true
For OR operator- It returns TRUE if either of the operand (right side or left side) is true
For NOT operator- returns TRUE if operand is false
Example: Here in example we get true or false based on the value of a and b
a = True
b = False
print(a and b)# will return False since one of them is false
print(a or b)# will return True since one of them is True
print(not a)# will return False since the value is True
print(not a)# will return True since the value is False
Illustrate interpreter and interactive mode in python? Interpreter:
A python interpreter is a computer program that converts each high-level program statement into machine code.
An interpreter translates the command that you write out into code that the computer can understand.
Python is the most famous example of a high-level language.
However, while high-level languages are relatively easy to understand by humans, the same cannot be said for machines.
Machines only understand machine code or machine language, a language represented by strings of bits â 1s and 0s.
When using a Python interpreter, the programmer types in the command, the interpreter reads the command, evaluates it, prints the results, and then goes back to read the command. Interactive mode:
Interactive mode is very convenient for writing very short lines of code.
In the interactive mode as we enter a command and press enter, the very next step we get the output. The output of the code in the interactive mode is influenced by the last command we give.
This mode is very suitable for beginners in programming as it helps them evaluate their code line by line and understand the execution of code well.
The interactive mode doesn't save the statements. Once we make a program it is for that time itself, we cannot use it in the future. In order to use it in the future, we need to retype all the statements.
Define module in python. Give an example to use it?
A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use.
It also makes the code logically organized.
Create a simple Python module
Letâs create a simple calc.py in which we define two functions, one add and another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Now we can save this py file with name calc.py and we can import and use the these function in other programs as well!.
Show the usage of five format specifiers in python?
":<" Left aligns the result (within the available space)
":>" Right aligns the result (within the available space)
":^" Center aligns the result (within the available space)
":=" Places the sign to the left most position
":+" Use a plus sign to indicate if the result is positive or negative
":-" Use a minus sign for negative values only
Define local, global and lexical scope in python. Give example? Global Variables:
These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function.
Let's see how to create a global variable.
# This function uses global variable
def f():
print("Inside Function", s)
# Global scope
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)
Output:
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks Local Variables:
Local variables are those which are initialized inside a function and belong only to that particular function.
It cannot be accessed anywhere outside the function. Let's see how to create a local variable.
Example: Creating local variables
def f():
# local variable
s = "I love Geeksforgeeks"
print(s)
# Driver code
f()
Output:
I love Geeksforgeeks Lexical scope
Lexical scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope.
This means that the child's functions are lexically bound to the execution context of their parents.
Lexical scope is sometimes also referred to as static scope.
What is the role of following characters in python (i) | (ii) ^ (iii) & (iv) // (v) % (iv) ~
(i) "|" - It is a Bitwise Or Operator
(ii) "^" - It is a Bitwise Xor Operator
(iii) "&" - It is a Bitwise And operator
(iv) "//" - It is Floor Division Operator,which returns the whole value as the result after division!
(v) "%" - It is a Modulus Operator, which returns the remainder value as the result after division!
(vi)"~" - It is the Bitwise Not operator
Write a python program to reverse each word of a given string?
# Python code to Reverse each word
def reverseWordSentence(Sentence):
# Splitting the Sentence into list of words.
words = Sentence.split(" ")
newWords = [word[::-1] for word in words]
# Joining the new list of words
newSentence = " ".join(newWords)
return newSentence
# Driver's Code
Sentence = "Python is good to learn"
print(reverseWordSentence(Sentence))
Output:
"nothyP si doog ot nrael"
Define mutable and immutable with example? Mutable:
Mutable is when something is changeable or has the ability to change.
In Python, "mutable" is the ability of objects to change their values. These are often the objects that store a collection of data. Immutable:
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable.
Once created, the value of these objects is permanent.
List of Mutable and Immutable objects
â«Lists
â«Sets
â«Dictionaries
Write a python program to check a given year is leap year or not?
# Python program to check if year is a leap year or not
year = int(input("Enter a year:"))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
How function is defined in python. Write a function to check a number is prime?
In Python, a function is defined using the def keyword, followed by the name of the function, and a set of parentheses that may include parameters.
The code inside the function must be indented. Here is an example function to check if a number is prime:
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
This function takes an integer number as an input and returns True if the number is prime, and False otherwise.
Write python program to find sum of digits of a number?
# Function to get sum of digits
def getSum(n):
sum = 0
for digit in str(n):
sum += int(digit)
return sum
n = 569
print(getSum(n))
Output: 20
Write python code to convert a given number to binary, octal, hexadecimal equivalent?
def convert_base(number):
binary = bin(number).replace("0b", "")
octal = oct(number).replace("0o", "")
hexadecimal = hex(number).replace("0x", "").upper()
return binary, octal, hexadecimal
The function makes use of the built-in functions bin(), oct(), and hex() to convert the decimal number to binary, octal, and hexadecimal, respectively. The replace() method is used to remove the prefixes "0b", "0o", and "0x" from the output.
The hexadecimal representation is converted to uppercase using the upper() method. The function returns a tuple of the three converted values.
Demonstrate the various expression in python with examples?
Expressions are a combination of values, variables, and operators that evaluate to a single value in Python. Here are some examples of different types of expressions in Python:
â«Arithmetic Expressions: These are expressions that perform arithmetic operations such as addition, subtraction, multiplication, division, etc.
â«Comparison Expressions: These are expressions that compare values and return a Boolean value (True or False).
â«Logical Expressions: These are expressions that perform logical operations such as and, or, and not.
â«Membership Expressions: These are expressions that test membership in a sequence such as lists, tuples, strings, etc.
â«Identity Expressions: These are expressions that compare the memory location of two objects.
Give the characteristics of membership operator with suitable example?
Membership operators are used to test if a sequence is presented in an object:
"in"- Returns True if a sequence with the specified value is present in the object
y = [1,3,5,6,7]
x = 5
x in y
output:True
not in Returns True if a sequence with the specified value is not present in the object
x not in y
Output : False #since 5 is in y
Explain in detail about the various operators in python. List their hierarchy?
In Python, operators are symbols that perform specific operations on values. There are several types of operators in Python â«Arithmathic Operators:
These are operators that perform basic arithmetic operations such as addition, subtraction, multiplication, division, etc.
+ : addition
- : subtraction
* : multiplication
/ : division (floating-point division)
// : floor division (rounds down to nearest integer)
% : modulus (returns the remainder of division)
** : exponentiation (raises a number to a power) â«Comparision Operators
These are operators that compare two values and return a Boolean value (True or False).
== : equal to
!= : not equal to
> : greater than
< : less than
>= : greater than or equal to
<= : less than or equal to â«Assignment Operators:
These are operators that assign a value to a variable.
= : simple assignment
+= : add and assign
-= : subtract and assign
*= : multiply and assign
/= : divide and assign
%= : modulus and assign
**= : exponentiate and assign â«Logical Operators:
These are operators that perform logical operations such as and, or
and : logical and
or : logical or
not : logical not â«Membership Operators:
These are operators that test membership in a sequence such as lists, tuples, strings, etc.
in : checks if an element is in a sequence
not in : checks if an element is not in a sequence â«Identity Operators:
These are operators that compare the memory location of two objects.
is : checks if two variables refer to the same object
is not : checks if two variables refer to different objects
Illustrate a program to display different data types using variables and literal consonants?
# Integer variable
x = 10
print("Integer variable x:", x)
# Floating-point variable
y = 10.5
print("Floating-point variable y:", y)
# String variable
name = "John Doe"
print("String variable name:", name)
# Boolean variable
is_male = True
print("Boolean variable is_male:", is_male)
# List literal
colors = ["red", "green", "blue"]
print("List literal colors:", colors)
# Tuple literal
coordinates = (10, 20)
print("Tuple literal coordinates:", coordinates)
# Set literal
unique_numbers = {1, 2, 3, 4, 5}
print("Set literal unique_numbers:", unique_numbers)
# Dictionary literal
person = {
"name": "Jane Doe",
"age": 30,
"gender": "Female"
}
print("Dictionary literal person:", person) Output
Integer variable x: 10
Floating-point variable y: 10.5
String variable name: John Doe
Boolean variable is_male: True
List literal colors: ['red', 'green', 'blue']
Tuple literal coordinates: (10, 20)
Set literal unique_numbers: {1, 2, 3, 4, 5}
Dictionary literal person: {'name': 'Jane Doe', 'age': 30, 'gender': 'Female'}