Python Unit 5-9
Python Unit 5-9
Python Unit 5-9
In [ ]: # This is a comment.
# Import statements.
import module1
import module2
# Define variables.
variable1 = 10
variable2 = 20
# Main code.
if variable1 > variable2:
print("Variable 1 is greater than variable 2.")
else:
print("Variable 1 is not greater than variable 2.")
# Functions.
def my_function(arg1, arg2):
return arg1 + arg2
This program starts with a comment, which is ignored by the Python interpreter.
The next line imports the module1 and module2 modules. These modules can be used to perform common
tasks, such as reading and writing files, or connecting to a database.
The next section of the program defines two variables, variable1 and variable2. These variables are used to
store data in memory for later use.
The main code of the program is contained in the if statement. This statement checks if variable1 is greater
than variable2. If it is, the program prints the message "Variable 1 is greater than variable 2." Otherwise, the
program prints the message "Variable 1 is not greater than variable 2."
The last section of the program defines a function called my_function(). This function takes two arguments,
arg1 and arg2, and returns the sum of the two arguments.
The main code of the program calls the my_function() function with the variable1 and variable2 variables as
arguments. The result of the function call is stored in the result variable.
The last line of the program prints the value of the result variable.
Syntax: Python has a simple and easy-to-read syntax. It uses indentation to define code blocks, which
makes code more readable and easier to maintain.
Data types: Python has a variety of data types, including integers, floats, strings, and booleans. It also has
more complex data types, such as lists, dictionaries, and sets.
Operators: Python has a variety of operators for performing operations on data, such as arithmetic, logical,
and comparison operators.
Control flow statements: Python has a variety of control flow statements for controlling the flow of execution
of a program, such as if statements, for loops, and while loops.
Functions: Python allows you to define functions, which are reusable blocks of code. Functions can take
arguments and return values.
Classes and objects: Python is an object-oriented programming language, which means that you can define
classes and objects. Classes are blueprints for creating objects, and objects are instances of classes.
Python is a general-purpose, high-level programming language. Its design philosophy emphasizes code
readability with its notable use of significant whitespace. Its language constructs and object-oriented
approach aim to help programmers write clear, logical code for small and large-scale projects.
Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including
structured (particularly, procedural), object-oriented, and functional programming. It is often described as a
"batteries included" language due to its comprehensive standard library.
Python interpreters are available for many operating systems, allowing Python code to run on a wide variety
of platforms. Python is also used in education and research.
It is a general-purpose language, meaning it can be used to create a variety of different programs and
isn't specialized for any specific problems.
It is a versatile language, used in a wide variety of fields, including web development, data science,
machine learning, and artificial intelligence.
It is a free and open-source language, meaning it is freely available to use and distribute.
It has a large and active community of developers, which means there are many resources available to
help users learn and use the language.
It is constantly being updated and improved, with new features being added all the time.
Python interpreter is written in C programming language as we all know that C is considered as mother of
all programming languages, Python interpreter called “CPython”.
Initially in source code analysis, Python get source and check for some Indentation rule and check for
errors. if there are any errors Python stops its execution and make to modify to prevent errors. This process
is called Lexical analysis in python which states that dividing the source code into list of individual tokens.
In Byte code generation, once the python interpreter receives the tokens, it generates AST (Abstract
Structure tree) which coverts to byte code and then byte code can be saved in (.py) extension.
At last, by using Python Virtual Machine, interpreter loads the machine language and PVM converts in into
0s and 1 s which prints the results.
Unit 6
1) Provide examples demonstrating basic arithmetic operations using Python.
Arithmetic operators are used with numeric values to perform common mathematical operations:
Addition x + y
Subtraction x - y
Multiplication x * y
/ Division x / y
% Modulus x % y
Exponentiation x y
// Floor division x // y
In [ ]: # Addition
a = 5
b = 2
sum = a + b
print(sum) # Output: 7
This code defines two variables, a and b, and assigns them the values 5 and 2, respectively. It then
calculates the sum of a and b and stores the result in the variable sum. Finally, it prints the value of sum to
the console. The output of this code is 7.
In [ ]: # Subtraction
a = 5
b = 2
difference = a - b
print(difference) # Output: 3
This code is similar to the previous example, but instead of calculating the sum of a and b, it calculates the
difference. The output of this code is 3.
In [ ]: # Multiplication
a = 5
b = 2
product = a * b
print(product) # Output: 10
10
This code calculates the product of a and b and stores the result in the variable product. The output of this
code is 10.
In [ ]: # Division
a = 5
b = 2
quotient = a / b
print(quotient) # Output: 2.5
2.5
This code calculates the quotient of a and b and stores the result in the variable quotient. The output of this
code is 2.5
In [ ]: # Floor division
a = 5
b = 2
floor_quotient = a // b
print(floor_quotient) # Output: 2
This code calculates the floor quotient of a and b and stores the result in the variable floor_quotient. The
floor quotient is the largest integer that is less than or equal to the quotient of a and b. The output of this
code is 2.
In [ ]: # Modulus
a = 5
b = 2
remainder = a % b
print(remainder) # Output: 1
This code calculates the remainder of a divided by b and stores the result in the variable remainder. The
remainder is the part of a that is not divisible by b. The output of this code is 1.
In [ ]: # Exponentiation
a = 5
b = 2
power = a ** b
print(power) # Output: 25
25
This code calculates the power of a raised to the power of b and stores the result in the variable power. The
power of a raised to the power of b is the product of a multiplied by itself b times. The output of this code is
25.
Python uses a set of rules called "operator precedence" to determine the order in which operators are
evaluated in an expression. This means that some operators are evaluated before others, based on their
level of precedence.
1. Parentheses
2. Exponentiation
3. Multiplication and Division
4. Addition and Subtraction
Within a level of precedence, operators are evaluated from left to right. For example, in the expression 2 + 3
4, multiplication is evaluated before addition, so the expression would be evaluated as 2 + (3 4), resulting in
14. Parentheses can be used to override the default order of precedence. For example, in the expression (2
+ 3) 4, the addition inside the parentheses is evaluated first, so the expression would be evaluated as (5) 4,
resulting in 20.
Here are some more examples of how operator precedence works in Python:
32
10
20
Indentation is a crucial aspect of Python's syntax. It is used to define blocks of code and is essential for the
proper execution of Python programs.
Here are some of the key significances of indentation in Python's code structure:
Defining code blocks: Indentation is used to group related lines of code together and define code
blocks. This makes the code more readable and organized, as it visually represents the structure and
hierarchy of the program.
Improved readability: Proper indentation enhances the readability of Python code, making it easier for
programmers to understand and maintain the code. It allows programmers to quickly identify the
beginning and end of code blocks, as well as the nesting of code within blocks.
Preventing errors: Python uses indentation to determine the flow of control within a program. Incorrect
indentation can lead to syntax errors, preventing the program from executing correctly.
Consistency and readability: Consistent indentation throughout a Python program improves its
readability and maintainability. It also makes it easier for other programmers to collaborate on and
understand the code.
Block structure: Indentation defines the block structure of Python code, which includes loops,
conditional statements, and function definitions. This helps in organizing the code logically and making
it more readable and maintainable.
In [ ]: def my_function(x):
if x > 0:
return x + 1
else:
return x - 1
print(my_function(5))
In this example, the code block for the my_function() function is indented by four spaces. This indicates that
all the lines of code within this block belong to the function definition. Similarly, the if and else statements
are indented by four spaces to indicate that they are part of the my_function() block.
4) How does the Python shell facilitate code execution and experimentation?
The Python shell is an interactive environment where users can execute Python code line by line, view
results immediately, and experiment with Python features. This makes it an ideal tool for learning Python,
debugging code, and experimenting with new ideas.
Here are some of the ways in which the Python shell facilitates code execution and experimentation:
Interactive execution: The Python shell allows users to execute Python code line by line. This means
that users can see the results of their code immediately, which can be helpful for debugging and
learning.
Immediate feedback: The Python shell provides immediate feedback to users. This means that users
can see the results of their code as soon as they execute it. This can be helpful for debugging and
learning.
Experimentation: The Python shell is a great environment for experimentation. Users can try out new
ideas and see how they work without having to write a full program. This can be helpful for learning
Python and developing new algorithms.
Here is an example of how the Python shell can be used for experimentation:
In [ ]: >>> 1 + 1
2
>>> 2 * 2
4
>>> "hello" + "world"
"helloworld"
'helloworld'
Out[ ]:
In this example, the user is experimenting with different Python expressions. The user is able to see the
results of each expression immediately, which helps the user to learn how Python works.
Atoms:
Atoms are the basic building blocks of Python syntax. They represent the most elementary components of
expressions or statements. In Python, there are several types of atoms:
Literals: Literal values such as numbers (integers, floats), strings, and Boolean values (True and False).
Identifiers: Identifiers are also considered atoms, representing the names given to variables, functions,
classes, modules, or any other user-defined object. They serve as references to objects stored in
memory.
Special literals: Python has two special literals: None and Ellipsis (...). These are used to represent the
absence of a value or to indicate incomplete slices, respectively.
List, tuple, and dictionary displays: These are used to create lists, tuples, and dictionaries, respectively,
with specified values.
Identifiers:
Identifiers are names used to identify variables, functions, classes, modules, or any other object in Python.
Rules for naming identifiers in Python are as follows:
The remainder of the identifier can contain letters, digits (0-9), or underscores.
Keywords:
Keywords are reserved words in Python that have special meanings and purposes. They are part of the
Python language syntax and cannot be used as identifiers. Keywords are used to define the structure and
flow of Python code, such as loops, conditional statements, class definitions, and more. Some examples of
keywords in Python include if, else, for, while, def, class, return, import, True, False, None, etc.
6) Provide examples of valid identifiers and discuss the rules for naming identifiers.
Some examples of invalid Python identifiers are: 1variable - cannot start with a number, my-variable -
cannot contain hyphens, my variable - cannot contain spaces, class - is a Python keyword, and true - is a
Python keyword.
Identifiers cannot contain special symbols, such as !, @, #, $, %, ^, &, *, (, ), -, +, =, |, \, /, ., ;, :, ', ", <, >,
?, `.
Examples:
42 # integer literal
0 # integer literal
String Literals: These represent sequences of characters enclosed in either single (' ') or double (" ")
quotes.
Examples:
Boolean Literals: These represent the two truth values, True and False.
Examples:
Examples:
Container Literals: These represent collections of data, such as lists, tuples, dictionaries, and sets.
Examples:
8) Discuss the concept of strings in Python, highlighting their characteristics and operations.
In Python, a string is a sequence of characters enclosed within quotes. It can be any sequence of letters,
numbers, spaces, and special characters (like punctuation marks) contained within single quotes (' ') or
double quotes (" ").
Strings are one of the most fundamental data types in Python, and they are used in a wide variety of
applications. For example, strings can be used to represent text, filenames, URLs, and email addresses.
Strings are immutable, which means that they cannot be changed once they are created.
Strings can be indexed, which means that you can access individual characters in a string using their
index number.
Strings can be sliced, which means that you can extract a substring from a string.
Strings can be concatenated, which means that you can combine two or more strings together.
Strings can be compared to each other using the standard comparison operators (<, >, ==, !=, <=, and
>=).
Here are some of the operations that can be performed on strings in Python:
Concatenation: The + operator can be used to concatenate two or more strings together. For example,
the following code will concatenate the strings "Hello" and "World" to create the string "Hello World":
'HelloWorld'
Out[1]:
Indexing: The operator can be used to access individual characters in a string. For example, the
following code will print the character at index 0 of the string "Hello World":
'H'
Out[2]:
Slicing: The operator can also be used to slice a substring from a string. For example, the following
code will extract the substring "World" from the string "Hello World":
'World'
Out[3]:
Comparison: The standard comparison operators (<, >, ==, !=, <=, and >=) can be used to compare
two strings to each other. For example, the following code will return True because the strings "Hello"
and "World" are equal:
False
Out[4]:
9) List various categories of operators in Python. Provide examples illustrating the usage and
functionality of two operator category.
Python divides the operators in the following groups:
Arithmetic Operators : Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
Comparison Operators : Comparison operators compare two values/variables and return a boolean
result: True or False.
Logical Operators : Logical operators are used to check whether an expression is True or False. They
are used in decision-making.
Bitwise Operators : Bitwise operators act on operands as if they were strings of binary digits. They
operate bit by bit, hence the name.
Identity Operators : 'is' and 'is not' are used to check if two values are located at the same memory
location.
Membership Operators : 'in' and 'not in' are the membership operators. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In [5]: a = 10
b = 5
# Add a and b
sum = a + b
# Subtract b from a
difference = a - b
# Multiply a and b
product = a * b
# Divide a by b
quotient = a / b
15 5 50 2.0 0
In [6]: x = 5
# Add 5 to x
x += 5
# Subtract 5 from x
x -= 5
# Multiply x by 5
x *= 5
# Divide x by 5
x /= 5
print(x)
10.0
Unit 7
1) Explain different methods for accepting user input in Python.
input(): function: The input() function is the most common way to accept user input in Python. It takes a
prompt as an argument and returns the user's input as a string.
For example:
This code will prompt the user to enter their name and store the input in the variable name.
eval(): function: The eval() function can be used to accept user input and evaluate it as Python code.
This can be useful for accepting complex input, such as mathematical expressions.
For example:
This code will prompt the user to enter a mathematical expression and evaluate it. The result will then be
printed to the console.
fileinput: module: The fileinput module can be used to accept user input from a file. This can be useful
for processing large amounts of data.
For example:
In [ ]: import fileinput
This code will read each line from the file specified by the user and print it to the console.
Using the print() function: The print() function is the most basic way to display output in Python. It takes
any number of arguments and prints them to the console, separated by spaces.
For example:
Hello, world!
Formatting strings with placeholders: You can use placeholders to format strings in Python.
Placeholders are represented by curly braces ({}). When you print a string with placeholders, the values
of the placeholders will be inserted into the string.
For example:
Hello, Alice!
Concatenating strings for output: You can concatenate strings in Python using the + operator.
For example:
Alice Bob
Formatting integers: You can use the format() method to format integers in Python. The format()
method takes a number and a format string as arguments. The format string specifies how the number
should be formatted.
For example:
12,345
Formatting floating-point numbers: You can use the format() method to format floating-point numbers in
Python. The format() method takes a number and a format string as arguments. The format string
specifies how the number should be formatted.
For example:
3.14
Here is a table that summarizes the key differences between while loops and for loops in Python:
Definition :
A while loop is a control flow statement that repeatedly executes a block of code until a given condition is
met.
A for loop is a control flow statement that repeatedly executes a block of code for a specified number of
times.
Syntax :
Usage :
Use a while loop when you need to repeatedly execute a block of code until a given condition is met, but
you don't know in advance how many times the loop will need to iterate.
Use a for loop when you need to repeatedly execute a block of code for a specified number of times.
Here are some examples of how to use while loops and for loops in Python:
0
1
2
3
4
0
1
2
3
4
In both of these examples, the code will print the numbers from 0 to 4.
However, the while loop uses a condition to determine how many times the loop will iterate, while the for
loop uses a range to specify the number of iterations.
1
2
3
4
5
This code will print each item in the list to the console. The while loop uses a condition to determine how
many times the loop will iterate, which is based on the length of the list.
1
2
3
4
5
This code will also print each item in the list to the console. However, the for loop uses a for-in loop to
iterate through the list, which is a more concise and readable way to write the code.
The if...else conditional statement in Python is a powerful tool that allows you to control the flow of your
program based on a certain condition.
In [ ]: if <condition>:
<statement(s)>
else:
<statement(s)>
The can be any expression that evaluates to True or False. If the evaluates to True, the <statement(s)>
block is executed. If the evaluates to False, the <statement(s)> block is skipped and the <statement(s)>
block in the else clause is executed, if it exists.
You can also use the elif statement to add additional conditions to your if...else statement. The syntax for
the elif statement is as follows:
In [ ]: if <condition>:
<statement(s)>
elif <condition>:
<statement(s)>
elif <condition>:
<statement(s)>
...
else:
<statement(s)>
The elif statements are evaluated in order, and the first condition that evaluates to True is executed. If none
of the conditions evaluate to True, the <statement(s)> block in the else clause is executed, if it exists.
5) Highlight the differences among break, continue, and pass statements in Python.
Break Statement : The break statement in Python is used to terminate the loop or statement in which it
is present. After that, the control will pass to the statements that are present after the break statement,
if available. If the break statement is present in the nested loop, then it terminates only those loops
which contain the break statement.
statement(s)
if condition:
break
statement(s)
loop end
0
1
2
3
4
Continue Statement : Continue is also a loop control statement just like the break statement. continue
statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute
the next iteration of the loop. As the name suggests the continue statement forces the loop to continue
or execute the next iteration. When the continue statement is executed in the loop, the code inside the
loop following the continue statement will be skipped and the next iteration of the loop will begin.
Syntax :
# statement(s)
if condition:
continue
# statement(s)
1
3
5
7
9
Pass Statement : As the name suggests pass statement simply does nothing. The pass statement in
Python is used when a statement is required syntactically but you do not want any command or code to
execute. It is like a null operation, as nothing will happen if it is executed. Pass statements can also be
used for writing empty loops. Pass is also used for empty control statements, functions, and classes.
Syntax :
Unit 8
1) Explain the characteristics and provide scenarios where different data structures of python would
be most appropriate for usage.
Here are the characteristics and scenarios where different data structures of Python would be most
appropriate for usage:
Lists: Lists are mutable, ordered sequences of elements. They can be used to store any type of data, and
can be of any length. Lists are a good choice for storing data that needs to be accessed and modified
frequently, such as a list of items in a shopping cart.
Tuples: Tuples are immutable, ordered sequences of elements. They are similar to lists, but cannot be
changed once they are created. Tuples are a good choice for storing data that needs to be accessed
frequently, but does not need to be modified, such as the coordinates of a point on a map.
Sets: Sets are unordered collections of unique elements. They can be used to store any type of data, and
can be of any length. Sets are a good choice for storing data that needs to be unique, such as a list of
unique words in a document.
Dictionaries: Dictionaries are unordered collections of key-value pairs. Keys can be any type of data, and
values can be any type of data. Dictionaries are a good choice for storing data that needs to be accessed
by key, such as a lookup table.
Strings: Strings are immutable sequences of characters. They can be used to store any type of text data.
Strings are a good choice for storing text data that needs to be accessed and modified frequently, such as
the text in a document.
Here are some specific scenarios where each data structure would be most appropriate for usage:
Lists:
Tuples:
Sets:
Dictionaries:
Strings:
The datetime module in Python provides classes for manipulating dates and times. It includes the following
classes:
The datetime module also includes a number of functions for working with dates and times, such as:
now(): This function returns the current date and time as a datetime object.
strftime(): This function formats a datetime object as a string.
strptime(): This function parses a string into a datetime object.
timezone(): This function returns the current timezone as a tzinfo object.
2024-03-27 13:05:53.190204
2023-08-04
12:00:00
2023-08-04 12:00:00
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-28-e9c69c3b204b> in <cell line: 28>()
26
27 # Calculate the difference between two dates
---> 28 date1 = datetime.date(2023, 8, 4)
29 date2 = datetime.date(2023, 8, 5)
30 difference = date2 - date1
In Python, a module is a file containing Python definitions and statements. It is a way to organize your
Python code into logical units. Modules can contain functions, classes, and variables.
Code organization: Modules help you organize your code into logical units. This makes your code easier to
understand and maintain.
Code reuse: Modules allow you to reuse code. You can import a module into your program and use the
functions, classes, and variables defined in the module. This saves you from having to write the same code
over and over again.
Namespace: Modules create a namespace for your code. This means that you can define functions,
classes, and variables with the same name in different modules without having to worry about them
conflicting with each other.
Module imported.
You can import this module into your program and use the functions defined in the module as follows:
In [ ]: import my_module
# Call the add() function.
result = my_module.add(1, 2)
Output :
Module imported.
-1
1. Use the keyword def to declare the function and follow this up with the function name.
2. Add parameters to the function: they should be within the parentheses of the function.
greet("Alice")
Hello, Alice!
This function takes one parameter, name, and prints a greeting to the user. The function body is indented,
which indicates that it is part of the function.
Code reuse: Functions can be reused throughout your code, which can save you time and effort.
Modularity: Functions can help you to organize your code into smaller, more manageable pieces. This can
make your code easier to read and maintain.
Readability: Functions can make your code more readable by grouping related code together.
Maintainability: Functions can make your code easier to maintain by making it easier to find and fix bugs.
The exit() function takes an optional argument, which is an integer value that is used as the exit status of
the program. The exit status is a value that is returned to the operating system when the program
terminates. A zero exit status indicates that the program terminated normally, while a non-zero exit status
indicates that the program terminated abnormally.
If the exit() function is called without an argument, it will terminate the program with an exit status of zero.
def main():
print("This is the main function.")
if __name__ == "__main__":
main()
SystemExit: 0
/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py:3561: UserWarni
ng: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
When this program is executed, it will print the message "This is the main function." and then terminate with
an exit status of zero.
The exit() function can be used to terminate a Python program for a variety of reasons. For example, it can
be used to terminate a program when it has finished executing its task, or it can be used to terminate a
program when it encounters an error.
The exit() function is a powerful tool that can be used to control the execution of Python programs.
However, it should be used with caution, as it can terminate a program at any point.
Here are the concepts of default arguments in Python functions with examples:
In Python, default arguments are function arguments that are used if no arguments are passed to the
function call. They are represented as argument_name = value in the function definition. Here's an example
of a function that uses default arguments:
In this example, the msg parameter has a default value of "Good morning!". If no msg argument is provided
during the function call, the default value is used.
Unit 9
1) Define objects and classes in Python and discuss their relationship.
In Python, a class is a blueprint for creating objects. Objects are the instances of a particular class. Every
other element in Python will be an object of some class, such as the string, dictionary, number(20,30), etc.
will be an object of some corresponding built-in class(int, str) in Python.
def function(self):
print("This is a message inside the class.")
blah
This is a message inside the class.
In this example, we create a class called MyClass. This class has a variable called variable and a function
called function(). We then create an object from the class called my_object. We can then access the
variable in the object using the dot operator (.). We can also call the function in the object using the dot
operator.
The relationship between classes and objects is that a class is a blueprint for creating objects. An object is
an instance of a particular class. Every object has a set of attributes and methods that are defined by the
class.
Object : Has a set of attributes and methods that are defined by the class
bike1 = Bike()
bike1.name = "Canyon"
bike1.gear = 2
bike2 = Bike()
bike2.name = "Giant"
bike2.gear = 3
print(bike1.name)
print(bike2.name)
Canyon
Giant
In this example, the Bike class is a blueprint for creating bike objects. The
Bike class has two attributes, name and gear. The bike1 and bike2 objects are instances of the Bike class.
We can access the attributes of an object using the dot operator. For example, to access the name attribute
of the bike1 object, we would write bike1.name.
We can also create methods in classes. Methods are functions that are defined within a class. Methods can
be used to perform actions on objects.
def pedal(self):
print("Pedaling...")
bike1 = Bike()
bike1.pedal()
Pedaling...
The pedal() method takes no arguments and prints the message "Pedaling..." to the console.
We can call the pedal() method on the bike1 object to make it pedal:
In [41]: bike1.pedal()
Pedaling...
def speak(self):
print(f"The {self.name} says hello!")
class Dog(Animal):
pass
In this example, the Dog class inherits the speak() method from the Animal class. This means that we can
call the speak() method on a Dog object, even though it is not explicitly defined in the Dog class.
Inheritance allows us to create new classes that are based on existing classes. This can save us a lot of
time and effort, as we don't have to rewrite all of the code from the parent class. We can simply inherit the
code that we need and then add our own specific code to the child class.
Code reusability: Inheritance allows us to reuse code that has already been written. This can save us a lot
of time and effort, as we don't have to rewrite the same code over and over again.
Code organization: Inheritance allows us to organize our code in a logical way. We can create a hierarchy of
classes, where each class inherits from a more general class. This makes our code easier to understand
and maintain.
Polymorphism: Inheritance allows us to write polymorphic code. Polymorphism means that we can write
code that can work with different types of objects. For example, we can write a function that takes an Animal
object as an argument. This function can then be used with any object that inherits from the Animal class,
such as a Dog object or a Cat object.
Here are some examples demonstrating single and multiple inheritance in Python:
Single inheritance:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
Woof!
Meow!
In this example, the Dog and Cat classes inherit from the Animal class. This means that they have access
to all of the attributes and methods of the Animal class. Additionally, the Dog and Cat classes can override
the methods of the Animal class to provide their own specific implementations.
Multiple inheritance:
def speak(self):
pass
class Flyer:
def fly(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
def fly(self):
print("I'm flying!")
Tweet!
I'm flying!
In this example, the Bird class inherits from both the Animal and Flyer classes. This means that it has
access to all of the attributes and methods of both of those classes. Additionally, the Bird class can override
the methods of the Animal and Flyer classes to provide its own specific implementations.
Regular expressions (regex) are a powerful tool for searching, editing, and manipulating text in Python.
They are used to define patterns of text that can be matched against a string. Regex can be used for a
variety of tasks, including:
Form validation: Regex can be used to validate input fields in forms, such as email addresses, phone
numbers, and credit card numbers.
Data mining: Regex can be used to extract data from text files or web pages. For example, you could use
regex to extract all of the email addresses from a text file.
Text processing: Regex can be used to clean up text, remove unwanted characters, and format text. For
example, you could use regex to remove all of the punctuation from a string.
Natural language processing: Regex can be used to analyze text and identify patterns in language. For
example, you could use regex to identify all of the nouns in a sentence.
Regex is a powerful tool that can be used for a variety of tasks in Python. If you are working with text, it is
worth learning how to use regex.
In [ ]: import re
Event-driven programming is a programming paradigm where the flow of the program is determined by
events. Events can be user inputs, such as mouse clicks or keyboard presses, or system events, such as
file downloads or network connections. When an event occurs, the program responds by executing a
callback function.
Event-driven programming is a popular paradigm for Python because it is well-suited to building responsive
and interactive applications. For example, a GUI application might use event-driven programming to
respond to user clicks and key presses. A web server might use event-driven programming to respond to
HTTP requests.
Here is a simple example of event-driven programming in Python:
In [ ]: import tkinter as tk
def on_click(event):
print("Button clicked!")
root = tk.Tk()
button = tk.Button(root, text="Click me!", command=on_click)
button.pack()
root.mainloop()
In this example, we create a button and bind the on_click() function to the button's command event. When
the user clicks the button, the on_click() function is executed.
Event-driven programming is a powerful paradigm that can be used to build a wide variety of applications. It
is a popular choice for Python because it is well-suited to building responsive and interactive applications.
Interactivity: Event-driven programming makes it easy to build interactive applications, such as GUI
applications and web servers.
Scalability: Event-driven programming can be used to build scalable applications that can handle a large
number of concurrent events.
GUI programming in Python is the process of creating graphical user interfaces (GUIs) for applications
using the Python programming language. GUIs are the visual elements and interactive parts of a software
application that allow users to interact with it. They typically include windows, buttons, menus, and text
boxes.
Python offers a number of different libraries and frameworks for GUI programming, each with its own
strengths and weaknesses. Some of the most popular options include:
Tkinter
Qt for Python
Kivy
wxPython
Once you have chosen a GUI library, you can start creating your GUI by adding widgets to a window.
Widgets are the basic building blocks of GUIs, and they represent different types of visual elements, such
as buttons, labels, and text boxes. You can arrange widgets on the window using a layout manager, which
controls the size and position of the widgets.
Once you have added the widgets to your GUI, you need to write code to handle events. Events are actions
that occur when the user interacts with the GUI, such as clicking a button or typing in a text box. You can
use event handlers to respond to events and perform actions, such as updating the GUI or performing a
calculation.
GUI programming in Python can be a rewarding experience, and it allows you to create powerful and user-
friendly applications. By following the basics outlined above, you can get started with GUI programming in
Python and create your own GUIs.