Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

python

Na

Uploaded by

Technical Gaurav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python

Na

Uploaded by

Technical Gaurav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

1]Type conversion In Python, type conversion refers to does not contain that item will raise an IndexError or tuple(range_example)

tuple(range_example) # Output: (0, 1, 2) Benefits of


the process of conver ng one data type to another. This can KeyError respec vely.  The del statement does not return Tuples Over Other Data Structures 1. Immutability: o Data
be done manually using built-in func ons or automa cally by any value. The del statement is a powerful tool for Integrity: Once created, the contents of a tuple cannot be
the interpreter in some cases. Type conversion is essen al managing memory and ensuring that unused or irrelevant changed, which ensures that data remains constant
when you need to perform opera ons that require operands data is removed from your program. If you need more throughout the program. o Hashability: Because tuples are
to be of the same type. Types of Type Conversion: 1. examples or have any specific ques ons, feel free to ask! immutable, they can be used as keys in dic onaries and
Implicit Type Conversion (Coercion): o This type of +5]describe process of crea n and storing string how it is elements in sets, which require hashable types. 2.
conversion is automa cally performed by the Python different and how you can use variable to store and use Performance: o Efficiency: Tuples are generally more
interpreter. o It usually happens when performing opera effec vely memory-efficient and faster than lists due to their
ons between different types, and Python converts them to immutability. o Fixed Size: The fixed size of tuples allows
a common type. o Example: python x = 10 y = 3.5 result = the Python interpreter to make opmiza ons that aren't
x + y # x is converted to float print(result) # Output: 13.5 possible with lists. 3. Readability and Intent: o Clear Intent:
2. Explicit Type Conversion (Cas ng): o This type of Using tuples can signal that the collec on of values should
conversion is manually done by the programmer using not be modified, providing a clear indica on of intent to
built-in func ons. o It is necessary when you need to other developers. o Structured Data: Tuples are o en used
convert types explicitly for certain opera ons. o Common to represent structured data, like records or coordinates
func ons include int(), float(), str(), list(), tuple(), set(), (e.g., (x, y)). 4. Return Mul ple Values from Func ons: o Func
dict(). o Example: python # Conver ng a string to an 6]Crea ng and Storing Strings in Python Strings in on Returns: Tuples are useful for returning mul ple values
integer num_str = "42" num_int = int(num_str) Python are sequences of characters used to represent from a func on in a single statement. python def
print(num_int) # Output: 42 # Conver ng a float to an text. They are created by enclosing characters within single get_coordinates(): return (10, 20) x, y = get_coordinates()
integer num_float = 3.14 num_int = int(num_float) quotes ('), double quotes ("), or triple quotes (''' or """) for Example Usages Packing and Unpacking  Packing:
print(num_int) # Output: 3 (decimal part is truncated) # mul-line strings. Crea ng Strings  Single Quotes: python Combining mul ple values into a tuple. python packed_tuple
Conver ng an integer to a string num = 100 num_str = single_quote_str = 'Hello, World!'  Double Quotes: python = 1, 2, 3  Unpacking: Extrac ng values from a tuple into
str(num) print(num_str) # Output: "100" Common Type double_quote_str = "Hello, World!"  Triple Quotes (used for variables. python a, b, c = packed_tuple print(a, b, c) #
Conversion Func ons:  int(): Converts to integer. python a mul-line strings): python mul _line_str = """Hello, World!""" Output: 1 2 3 Nes ng Tuples  Tuples can contain other
= int(5.6) # Output: 5  float(): Converts to float. python b Storing Strings in Variables Variables are used to store data tuples (or other complex data structures) as elements.
= float("3.14") # Output: 3.14  str(): Converts to string. that can be reused and manipulated throughout your python nested_tuple = (1, (2, 3), (4, (5, 6))) Tuples are a
python c = str(10) # Output: "10"  list(): Converts to list. program. When you assign a string to a variable, Python powerful tool in Python, providing clear, efficient, and
python d = list((1, 2, 3)) # Output: [1, 2, 3]  tuple(): stores the string in memory and gives you a reference to immutable collec ons of items. They are ideal for use cases
Converts to tuple. python e = tuple([1, 2, 3]) # Output: (1, that loca on via the variable name.  Assignment: python where the integrity and performance of the data are
2, 3)  set(): Converts to set. python f = set([1, 2, 2, 3]) # gree ng = 'Hello, World!' Differences and Use Cases  Single paramount. I\
Output: {1, 2, 3}  dict(): Converts to dic onary (requires a vs. Double Quotes: Func onally, single and double quotes
sequence of key-value pairs). python g = dict([('a', 1), ('b', are the same. The choice between them is o en a ma er of
2)]) # Output: {'a': 1, 'b': 2} By using these type style or convenience (e.g., using double quotes if the string
conversion func ons, you can ensure your data is in the contains single quotes). python single_quote_str = 'It\'s a
correct format for your opera ons, avoiding poten al errors beau ful day!' double_quote_str = "It's a beau ful day!" 
and making your code more robust. Triple Quotes: Used for mul-line strings and documenta on
strings (docstrings). They preserve the forma ng of the text. 8]What is a File? A file in the context of compu ng is
python mul _line_str = """This is a mul-line string.""" Effec essen ally a collec on of data or informa on that has a
2]condi onal statemnt in python Condi onal statements
ve Use of Variables Using variables to store strings makes unique name and is stored on a computer or storage
in Python allow you to control the flow of your program
your code more readable, maintainable, and efficient. Here device. Files serve as the primary method for data storage
based on certain condi ons. These statements enable you
are some ps for effec ve use: 1. Descrip ve Variable Names: and retrieval, allowing users and applica ons to read, write,
to execute different blocks of code depending on whether a
Use meaningful names to make your code self-explanatory. and manage data efficiently. They can contain a vast array
condi on is true or false. Key Types of Condi onal
python user_name = "Alice" 2. Concatena on: Combine of informa on, ranging from plain text to complex mul
Statements: 1. if Statement: o The simplest form of a condi
strings using the + operator or forma ed strings (f-strings) media data. Different Types of Files 1. Text Files  Descrip
onal statement. o Executes a block of code if the condi on
for be er readability. python f irst_name = "Alice" last_name on: Text files store data in plain text format, which means
is true. o Syntax: python if condi on: # code to execute if
= "Smith" full_name = first_name + " " + last_name # they contain readable characters without any special forma
condi on is true o Example: python age = 18 if age >= 18:
Using f-string full_name = f"{first_name} {last_name}" 3. ng.  Extensions: Common extensions include .txt and .log.
print("You are an adult.") 2. if-else Statement: o Provides an
String Methods: Python provides various string methods to  Usage: They are commonly used for simple documents,
alterna ve block of code to execute if the condi on is false.
manipulate and format strings effec vely. python text = configura on files, and logs.  Example: Examples include
o Syntax: python if condi on: # code to execute if condi on
"hello" capitalized_text = text.capitalize() # Output: 'Hello' readme files and source code files. 2. Binary Files  Descrip
is true else: # code to execute if condi on is false o
upper_text = text.upper() # Output: 'HELLO' 4. Avoiding on: Binary files contain data in a binary format, which
Example: python age = 16 if age >= 18: print("You are an
Memory Overhead: When dealing with large or repe ve means they store informa on in a series of bytes. This data
adult.") else: print("You are a minor.") 3. if-elif-else
strings, consider using join opera ons to minimize memory can include both text and non-text elements.  Extensions:
Statement: o Allows checking mul ple condi ons. o elif
usage. python words = ["hello", "world"] sentence = " Common extensions include .bin and .dat.  Usage: They
(short for "else if") can be used to add more condi ons
".join(words) are used for executable programs, compiled code, and
between if and else. o Syntax: python if condi on1: # code
other non-text data.  Example: Examples include
to execute if condi on1 is true elif condi on2: # code to
executable files, image files, and audio files.
execute if condi on2 is true else: # code to execute if none disscus method of add remove union methhod func
of the above condi ons are true o Example: python score = on explain how these method are use to menepulate
85 if score >= 90: print("Grade: A") elif score >= 80: set In Python, sets are collec ons of unique elements, and 11]write a program to prompt user to enter a text
print("Grade: B") elif score >= 70: print("Grade: C") else: they provide several methods to manipulate these filename and display no of vowel and constant in file
print("Grade: D or below") Nested Condi onal Statements:  elements efficiently. Let's discuss some of the key methods, python
You can nest condi onal statements inside one another to including add(), remove(), and union(), and how they can
create more complex condi ons.  Example: python age = be used to manipulate sets. 1. add() Method:  Purpose: def count_vowels_and_consonants(file_path):
22 gender = "female" if age >= 18: if gender == "male": Adds a single element to a set.  Usage: If the element is vowels = "aeiouAEIOU"
print("You are an adult male.") else: print("You are an adult already present, the set remains unchanged since sets do vowel_count = 0
female.") else: print("You are a minor." not allow duplicate elements.  Syntax: python consonant_count = 0
set.add(element)  Example: python my_set = {1, 2, 3}
my_set.add(4) print(my_set) # Output: {1, 2, 3, 4} try:
3]built in func on Python comes with a wide array of with open(file_path, 'r') as file:
built-in func ons that provide a range of useful func onali my_set.add(2) print(my_set) # Output: {1, 2, 3, 4} (2 is
text = file.read()
es. These func ons are always available and don't require already in the set) 2. remove() Method:  Purpose:
for char in text:
impor ng any modules. Here are some of the most Removes a specific element from a set.  Usage: If the if char.isalpha():
commonly used built-in func ons: Common Built-in Func element is not found, it raises a KeyError. Use discard() if char in vowels:
ons: 1. abs(): Returns the absolute value of a number. method to avoid this error.  Syntax: python vowel_count += 1
python print(abs(-5)) # Output: 5 2. all(): Returns True if all set.remove(element)  Example: python my_set = {1, 2, 3} else:
elements in an iterable are true. python print(all([True, my_set.remove(2) print(my_set) # Output: {1, 3} # consonant_count += 1
True, False])) # Output: False 3. any(): Returns True if any my_set.remove(4) # Raises KeyError because 4 is not in the return vowel_count, consonant_count
element in an iterable is true. python print(any([True, False, set 3. union() Method:  Purpose: Returns a new set except FileNotFoundError:
False])) # Output: True 4. chr(): Returns a string represen containing all unique elements from both sets.  Usage: It print(f"Error: The file '{file_path}' was not found.")
does not modify the original sets but returns a new set.  return None, None
ng a character whose Unicode code point is the integer
passed. python print(chr(97)) # Output: 'a' 5. dir(): Returns Syntax: python set1.union(set2) # OR set1 | set2 
Example: python set1 = {1, 2, 3} set2 = {3, 4, 5} def main():
a list of the names in the current local scope or the a file_path = input("Enter the text filename: ")
ributes of the given object. python print(dir()) # Output: result_set = set1.union(set2) print(result_set) # Output: {1,
vowels, consonants =
List of names in the current scope 6. divmod(): Returns a 2, 3, 4, 5} # OR using the | operator result_set = set1 |
count_vowels_and_consonants(file_path)
tuple containing the quo ent and remainder when dividing set2 print(result_set) # Output: {1, 2, 3, 4, 5} Other Useful
two numbers. python print(divmod(7, 3)) # Output: (2, 1) 7. Methods:  discard(): Removes an element if it is present; if vowels is not None and consonants is not None:
enumerate(): Adds a counter to an iterable and returns it as does nothing if the element is not present. python my_set print(f"Number of vowels in the file: {vowels}")
an enumerate object. python for i, value in enumerate(['a', = {1, 2, 3} my_set.discard(2) print(my_set) # Output: {1, print(f"Number of consonants in the file:
'b', 'c']): print(i, value) # Output: (0, 'a'), (1, 'b'), (2, 'c') 8. 3} my_set.discard(4) # No error if 4 is not in the set  {consonants}")
filter(): Constructs an iterator from elements of an iterable intersec on(): Returns a new set containing only the
for which a func on returns true. python def is_even(n): elements present in both sets. python set1 = {1, 2, 3} set2 if __name__ == "__main__":
return n % 2 == 0 print(list(filter(is_even, [1, 2, 3, 4, 5, 6]))) = {2, 3, 4} result_set = set1.intersec on(set2) 12]explain how to creater object in python Crea ng
# Output: [2, 4, 6] 9. float(): Converts a string or a number print(result_set) # Output: {2, 3}  difference(): Returns a objects in Python
to a floa ng-point number. python print(float('3.14')) # new set containing elements in the first set but not in the
Output: 3.14 10. int(): Converts a string or a number to an second set. python set1 = {1, 2, 3} set2 = {2, 3, 4} Crea ng objects in Python involves defining a class and
integer. python print(int('10')) # Output: 10 result_set = set1.difference(set2) print(result_set) # then instan a ng objects of that class. A
Output: {1} Summary These methods allow you to
efficiently manipulate sets by adding or removing
4]del statement in python The del statement in Python class is a blueprint for crea ng objects, providing ini al
elements, combining sets, and finding common or unique values for state (member variables or
is used to delete objects. It can be used to delete variables,
elements between sets. U lizing these methods helps you a ributes), and implementa ons of behavior (member func
items within a list, or even en re lists and dic onaries. This
manage and process collec ons of unique elements effec ons or methods).
can help manage memory and remove unnecessary data
vely in Python. Steps to Create an Object in Python
from your program. Usage of the del Statement: 1. Dele ng
1. Define a Class: The class defini on includes methods
a Variable: o Removes the variable from the namespace. o
9]explain crea ng tuple ,some way to ini alize tuple (func ons) and a ributes (variables)
Example: python x = 10 del x # Trying to access x now will
and benefit over other Crea ng and Ini alizing Tuples that define the behavior and state of the objects created
raise a NameError 2. Dele ng an Item from a List: o from the class.
Removes an item at a specific index from a list. o Example: in Python Tuples in Python are immutable sequences,
2. Instan ate an Object: Create an object of the class by
python my_list = [1, 2, 3, 4, 5] del my_list[2] # Removes typically used to store collec ons of heterogeneous data.
calling the class as if it were a
the item at index 2 (value 3) print(my_list) # Output: [1, 2, They are similar to lists, but with a key difference: once func on.
4, 5] 3. Dele ng a Slice from a List: o Removes a range of created, tuples cannot be modified. Crea ng and Ini alizing Example
items from a list. o Example: python my_list = [1, 2, 3, 4, 5] Tuples 1. Using Parentheses ()  Empty Tuple: python Let's go through an example to illustrate the process:
del my_list[1:3] # Removes items at index 1 and 2 empty_tuple = ()  Single Element Tuple: Note the trailing 1. Defining a Class:
print(my_list) # Output: [1, 4, 5] 4. Dele ng an En re List: o comma. python single_element_tuple = (1,)  Mul ple o Use the class keyword to define a class.
Completely removes the list from memory. o Example: Elements: python mul _element_tuple = (1, 2, 3) 2. Without o Define an __init__() method to ini alize the object's a
python my_list = [1, 2, 3] del my_list # Trying to access Parentheses  Tuples can be created without parentheses ributes.
my_list now will raise a NameError 5. Dele ng Items from a by separa ng the values with commas. python o Define other methods to describe the behavior of the
another_tuple = 1, 2, 3 3. Using the tuple() Constructor  objects.
Dic onary: o Removes a key-value pair from a dic onary. o
From a List: python list_example = [1, 2, 3] tuple_from_list python
Example: python my_dict = {'a': 1, 'b': 2, 'c': 3} del
= tuple(list_example)  From a String: python class Dog:
my_dict['b'] # Removes the key 'b' and its value # Ini aliza on method
print(my_dict) # Output: {'a': 1, 'c': 3} Important Notes:  string_example = "hello" tuple_from_string =
def __init__(self, name, age):
Using del on an object that does not exist will raise a tuple(string_example)  From a Range: python
self.name = name # A ribute
NameError.  Dele ng an item from a list or dic onary that range_example = range(3) tuple_from_range = self.age = age # A ribute
child = Child()
# Method to make the dog bark print(child.father_trait()) # Output: Height
def bark(self): print(child.mother_trait()) # Output: Eye color
print(f"{self.name} says Woof!") ```

# Method to display dog's info 3. **Multilevel Inheritance**: A class inherits from a class
def info(self): which is also inherited from another class.
print(f"Dog Name: {self.name}, Age: {self.age}") ```python
2. Instan a ng an Object: class Grandfather:
o Create an instance of the Dog class by calling it as if it def trait(self):
were a func on. return "Wisdom"
o The __init__() method is automa cally called to ini alize
the object's a ributes. class Father(Grandfather):
python def father_trait(self):
my_dog = Dog("Buddy", 3) # Crea ng an object of the Dog return "Strength"
class
class Son(Father):
# Calling methods on the object pass
my_dog.bark() # Output: Buddy says Woof!
my_dog.info() # Output: Dog Name: Buddy, Age: 3 son = Son()
Explana on print(son.trait()) # Output: Wisdom
 Class Defini on: print(son.father_trait()) # Output: Strength
o __init__ Method: This is a special method called a ```
constructor. It ini alizes the
object's a ributes. The self parameter is a reference to the 4. **Hierarchical Inheritance**: Multiple classes inherit from
current instance of the the same superclass.
class. ```python
o Other Methods: Methods like bark and info define the class Animal:
behaviors of the objects. def sound(self):
 Object Instan a on: return "Some sound"
o Crea ng an Object: my_dog = Dog("Buddy", 3) creates an
instance of the Dog class class Dog(Animal):
with name as "Buddy" and age as 3. def sound(self):
o Accessing Methods: You can call the methods of the class return "Bark"
on the object using the
dot nota on (e.g., my_dog.bark()). class Cat(Animal):
Benefits of Using Objects def sound(self):
 Modularity: Classes and objects promote modularity and return "Meow"
reusability of code.
 Encapsula on: Objects encapsulate data and behavior, dog = Dog()
which can help in organizing and cat = Cat()
managing code. print(dog.sound()) # Output: Bark
 Inheritance: Classes allow for inheritance, making it print(cat.sound()) # Output: Meow
easier to create subclasses that extend ```
the func onality of base classes.
5. **Hybrid Inheritance**: A combination of two or more
write a program that reads the content of the file types of inheritance. It can be achieved by mixing any of
and count the occurences of the each letter promt the above types.
the user to enter the file name ```python
class Grandparent:
def count_letters(file_name): def grandparent_trait(self):
# Initialize a dictionary to keep track of letter counts return "Wisdom"
letter_counts = {}
class Parent(Grandparent):
try: def parent_trait(self):
with open(file_name, 'r') as file: return "Kindness"
content = file.read().lower()
class Uncle(Grandparent):
# Loop through each character in the file content def uncle_trait(self):
for char in content: return "Humor"
if char.isalpha():
if char in letter_counts: class Child(Parent, Uncle):
letter_counts[char] += 1 pass
else:
letter_counts[char] = 1 child = Child()
print(child.grandparent_trait()) # Output: Wisdom
# Print the letter counts print(child.parent_trait()) # Output: Kindness
for letter, count in sorted(letter_counts.items()): print(child.uncle_trait()) # Output: Humor
print(f"{letter}: {count}")

except FileNotFoundError:
print(f"The file {file_name} was not found.")

if __name__ == "__main__":
# Prompt the user to enter the file name
file_name = input("Enter the file name: ")
count_letters(file_name)

Python program that will prompt the user for a file


name and then display the file size of that plain text
file:

```python
import os

def get_file_size(file_name):
try:
file_size = os.path.getsize(file_name)
print(f"The size of '{file_name}' is {file_size} bytes.")
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")

if __name__ == "__main__":
# Prompt the user to enter the file name
file_name = input("Enter the file name: ")
get_file_size(file_name)
```

, inheritance is a key concept that allows a class to inherit


attributes and methods from another class. There are
several types of inheritance:

1. **Single Inheritance**: A class inherits from one


superclass.
```python
class Animal:
def sound(self):
return "Some sound"

class Dog(Animal):
def sound(self):
return "Bark"

dog = Dog()
print(dog.sound()) # Output: Bark
```

2. **Multiple Inheritance**: A class inherits from more than


one superclass.
```python
class Father:
def father_trait(self):
return "Height"

class Mother:
def mother_trait(self):
return "Eye color"

class Child(Father, Mother):


pass

You might also like