Peterson J. Mastering Dart and Python Programming. a Comprehensive Guide...2024
Peterson J. Mastering Dart and Python Programming. a Comprehensive Guide...2024
Dart has come a long way since its initial release, with
significant updates and improvements. Dart 2, released in
August 2018, introduced a more concise and readable
syntax, making the language even more accessible to
developers.
## Conclusion
1. Download the Dart SDK TAR file for macOS or Linux from
the Dart website.
```dart --version```
While you can write Dart code using a basic text editor,
using an Integrated Development Environment (IDE) can
significantly enhance your development experience. IDEs
provide features such as code completion, debugging tools,
and project management capabilities.
Choose the text editor that aligns with your preferences and
workflow. While these editors may not offer the same level
of integration and features as full-fledged IDEs, they can still
be powerful tools for Dart programming.
Once you have installed the Dart SDK and chosen your
preferred development environment (IDE or text editor),
there are a few additional configurations you can make to
streamline your Dart development experience:
If you plan to use version control for your Dart projects (and
you should), consider setting up a version control system
like Git. Learn the basics of Git,
## Conclusion
Setting up your Dart development environment is a
foundational step in your journey to becoming a proficient
Dart programmer. In this chapter, we've covered the
installation of the Dart SDK, the selection of an Integrated
Development Environment (IDE) or text editor, and
additional configurations to enhance your development
experience.
```dart
// Syntax: data_type variable_name = initial_value;
int age = 25; // An integer variable named "age" with an
initial value of 25.
String name = "John"; // A string variable named "name"
with an initial value of "John".
```
```dart
int age = 30; // An integer variable storing the value 30.
```
#### **2. double**
```dart
double pi = 3.14159; // A double variable storing the value
of Pi.
```
```dart
String greeting = "Hello, Dart!"; // A string variable storing a
greeting.
```
```dart
bool isDartFun = true; // A boolean variable indicating that
Dart is fun.
```
```dart
List<int> numbers = [1, 2, 3, 4, 5]; // A list of integers.
List<String> fruits = ["apple", "banana", "cherry"]; // A list
of strings.
```
```dart
Map<String, int> ages = {"Alice": 25, "Bob": 30, "Carol":
35}; // A map with string keys and integer values.
```
### Variable Naming Rules
## Variable Scope
```dart
void main() {
int x = 10; // x is a local variable accessible within the
main function.
print(x); // Outputs: 10
}
```
```dart
int globalVar = 5; // globalVar is a global variable.
void main() {
print(globalVar); // Outputs: 5
updateGlobalVar(); // Calls a function that modifies
globalVar.
print(globalVar); // Outputs: 10
}
void updateGlobalVar() {
globalVar = 10; // Modifies the global variable.
}
```
## Constants
```dart
final int finalVar = 100; // A final variable with a runtime-
determined value.
```
```dart
const double pi = 3.14159; // A compile-time constant
variable.
```
```dart
var age = 25; // Dart infers that age is of type int.
var name = "John"; // Dart infers that name is of type String.
```
## Conclusion
```dart
if (condition) {
// Code to be executed if the condition is true.
}
```
```dart
int age = 18;
```dart
if (condition) {
// Code to be executed if the condition is true.
} else {
// Code to be executed if the condition is false.
}
```
```dart
int age = 15;
Now, when the `age` variable is 15, the condition in the `if`
statement is `false`, and the code inside the `else` block is
executed, resulting in "You are not yet an adult." being
printed.
```dart
if (condition1) {
// Code to be executed if condition1 is true.
} else if (condition2) {
// Code to be executed if condition2 is true.
} else {
// Code to be executed if none of the conditions is true.
}
```
```dart
int score = 75;
if (score >= 90) {
print("A");
} else if (score >= 80) {
print("B");
} else if (score >= 70) {
print("C");
} else {
print("F");
}
```
```dart
condition ? expression_if_true : expression_if_false
```
Here's an example:
```dart
int x = 10;
int y = 20;
```dart
for (initialization; condition; update) {
// Code to be executed in each iteration.
}
```
```dart
for (int i = 1; i <= 5; i++) {
print(i);
}
```
```dart
while (condition) {
// Code to be executed as long as the condition is true.
}
```
```dart
int count = 5;
```dart
do {
// Code to be executed at least once.
} while (condition);
```
Let's use a `do-while` loop to prompt the user for input until
a valid value is provided:
```dart
String userInput;
bool isValid = false;
do {
print("Please enter a valid input: ");
userInput = getUserInput(); // Assume this function gets
user input.
isValid = validateInput(userInput); // Assume this function
validates the input.
} while (!isValid);
```
```dart
```dart
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i is 3.
}
print(i);
}
```
## Conclusion
## Understanding Functions
```dart
returnType functionName(parameters) {
// Function body with instructions.
// Optionally, return a value of the specified returnType.
}
```
```dart
// Function that adds two numbers and returns the result.
int add(int a, int b) {
return a + b;
}
void main() {
// Calling the add function and storing the result in a
variable.
int sum = add(5, 3);
print("The sum is: $sum"); // Outputs: The sum is: 8
}
```
In this example:
```dart
// Function that greets a person.
String greet(String name, int age) {
return "Hello, $name! You are $age years old.";
}
void main() {
String message = greet("Alice", 25);
print(message); // Outputs: Hello, Alice! You are 25 years
old.
}
```
```dart
// Function that returns an integer.
int multiply(int a, int b) {
return a * b;
}
void main() {
int product = multiply(4, 3);
print("Product: $product"); // Outputs: Product: 12
String uppercaseText = capitalize("dart");
print("Uppercase: $uppercaseText"); // Outputs: Uppercase:
DART
In these examples:
```dart
void main() {
int x = 10; // This variable is in the scope of the main
function.
void innerFunction() {
int y = 5; // This variable is in the scope of the
innerFunction.
print(x); // Accessing the variable x from the outer scope.
}
innerFunction();
print(y); // Error: The variable y is not in scope here.
}
```
```dart
void printNumbers(int a, int b) {
int x = a + b; // Variable x is declared within the function.
print(a); // Accessing parameter a.
print(b); // Accessing parameter b.
print(x); // Accessing variable x.
}
void main() {
int a = 3;
int b = 7;
printNumbers(a, b); // Call the function with arguments a
and b.
print(a); // Accessing variable a from the main
function.
print(b); // Accessing variable b from the main
function.
print(x); // Error: Variable x is not in scope here.
}
```
In this example, `a` and `b` are function parameters, and
`x` is a variable declared within the `printNumbers`
function. The parameters `a` and `b` are accessible only
within the `printNumbers` function, while the variables
declared within that function are not accessible in the
`main` function.
## Methods in Dart
class:
```dart
returnType methodName(parameters) {
// Method body with instructions.
// Optionally, return a value of the specified returnType.
}
```
### Creating and Using Methods
```dart
class Dog {
String name;
// Method to bark.
void bark() {
print("$name says Woof!");
}
}
void main() {
// Create a Dog object and call its bark method.
Dog myDog = Dog("Buddy");
myDog.bark(); // Outputs: Buddy says Woof!
}
```
In this example:
```dart
class MathUtils {
// Instance method to add two numbers.
int add(int a, int b) {
return a + b;
}
void main() {
MathUtils math = MathUtils();
In this example:
```dart
class Circle {
double radius;
Circle(this.radius);
void main() {
Circle myCircle = Circle(5.0);
double area = myCircle.calculateArea();
print("The area of the circle is $area square units.");
}
```
In this example:
```dart
class StringBuilder {
String _value = "";
@override
String toString() {
return _value;
}
}
void main() {
StringBuilder builder = StringBuilder()
.add("Hello, ")
.add("Dart ")
.add("Programmers!");
print(builder); // Outputs: Hello, Dart Programmers!
}
```
## Conclusion
```dart
class ClassName {
// Class properties (attributes).
dataType propertyName;
// Constructor(s).
ClassName(parameters) {
// Constructor code.
}
// Methods.
returnType methodName(parameters) {
// Method code.
}
}
```
```dart
// Define a simple class.
class Dog {
String name;
Dog(this.name);
void bark() {
print("$name says Woof!");
}
}
void main() {
// Create a Dog object.
Dog myDog = Dog("Buddy");
### Constructors
```dart
class Rectangle {
double width;
double height;
// Default constructor.
Rectangle() {
width = 1.0;
height = 1.0;
}
// Parameterized constructor.
Rectangle.withDimensions(double w, double h) {
width = w;
height = h;
}
}
void main() {
// Create objects using different constructors.
Rectangle defaultRectangle = Rectangle();
Rectangle customRectangle =
Rectangle.withDimensions(3.0, 4.0);
print("Default Rectangle:
${defaultRectangle.width}x${defaultRectangle.height}");
print("Custom Rectangle:
${customRectangle.width}x${customRectangle.height}");
}
```
```dart
class Counter {
int value = 0;
void main() {
// Create a Counter object.
Counter counter = Counter();
counter.reset();
print("Counter value after reset: ${counter.value}"); //
Outputs: Counter value after reset: 0
}
```
```dart
class Person {
String name;
int age;
Person(this.name, this.age);
}
void main() {
// Create a Person object.
Person person = Person("Alice", 30);
## Inheritance
```dart
// Superclass (base class).
class Animal {
String name;
Animal(this.name);
void speak() {
print("$name makes a sound");
}
}
void main() {
// Create objects of the superclass and subclass.
Animal animal = Animal("Generic Animal");
Dog dog = Dog("Buddy");
on both objects.
animal.speak(); // Outputs: Generic Animal makes a sound
dog.speak(); // Outputs: Buddy barks
}
```
```dart
class Vehicle {
String brand;
Vehicle(this.brand);
void drive() {
print("$brand is moving");
}
}
void honk() {
print("Honk honk!");
}
}
void main() {
// Create objects of the superclass and subclass.
Vehicle vehicle = Vehicle("Generic Vehicle");
Car car = Car("Toyota", 4);
```dart
class Shape {
double area() {
return 0.0; // Default implementation for all shapes.
}
}
Circle(this.radius);
@override
double area() {
return 3.14 * radius * radius;
}
}
Square(this.side);
@override
double area() {
return side * side;
}
}
void main() {
// Create objects of different shapes.
Circle circle = Circle(5.0);
Square square = Square(4.0);
Dart provides two operators, `is` and `as`, for working with
classes and type checking:
```dart
class Animal {}
void main() {
Animal animal = Dog();
if (animal is Dog) {
print("It's a Dog!");
} else {
print("It's not a Dog.");
}
}
```
```dart
class Animal {}
if (dog != null) {
dog.bark(); // Outputs: Woof!
}
}
```
## Lists
```dart
// Using list literals.
var fruits = ['apple', 'banana', 'cherry'];
```dart
var fruits = ['apple', 'banana', 'cherry'];
```dart
var fruits = ['apple', 'banana', 'cherry'];
- **Adding Elements**:
- `add(element)`: Appends an element to the end of the
list.
- `insert(index, element)`: Inserts an element at the
specified index.
- `addAll(iterable)`: Appends all elements of the iterable to
the end of the list.
- **Removing Elements**:
- `remove(element)`: Removes the first occurrence of the
element from the list.
- `removeAt(index)`: Removes the element at the specified
index.
- `removeLast()`: Removes and returns the last element of
the list.
- `removeWhere(predicate)`: Removes elements that
satisfy the given predicate.
- `clear()`: Removes all elements from the list.
```dart
var numbers = [1, 2, 3];
// Adding elements.
numbers.add(4); // [1, 2, 3, 4]
numbers.insert(1, 5); // [1, 5, 2, 3, 4]
numbers.addAll([6, 7]); // [1, 5, 2, 3, 4, 6, 7]
// Removing elements.
numbers.remove(3); // [1, 5, 2, 4, 6, 7]
numbers.removeAt(1); // [1, 2, 4, 6, 7]
numbers.removeLast(); // [1, 2, 4, 6]
numbers.removeWhere((n) => n % 2 == 0); // Remove
even numbers.
numbers.clear(); // []
```
```dart
var fruits = ['apple', 'banana', 'cherry'];
## Sets
```dart
// Using set literals.
var fruits = {'apple', 'banana', 'cherry'};
```dart
var fruits = {'apple', 'banana', 'cherry'};
// Adding elements.
fruits.add('orange');
fruits.addAll({'grape', 'kiwi'});
// Removing elements.
fruits.remove('banana');
fruits.removeAll({'cherry', 'kiwi'});
```
```dart
var set1 = {1, 2, 3};
var set2 = {3, 4,
5};
// Union of sets.
var union = set1.union(set2); // {1, 2, 3, 4, 5}
// Intersection of sets.
var intersection = set1.intersection(set2); // {3}
// Difference of sets.
var difference = set1.difference(set2); // {1, 2}
// Subset checking.
var isSubset = set1.isSubsetOf(set2); // false
```
## Maps
```dart
// Using map literals.
var fruits = {
'apple': 2.0,
'banana': 1.5,
'cherry': 3.0,
};
You can access the values in a map using their keys. Dart
maps use square brackets `[]` to access values associated
with keys.
```dart
var fruits = {
'apple': 2.0,
'banana': 1.5,
'cherry': 3.0,
};
```dart
var fruits = {
'apple': 2.0,
'banana': 1.5,
'cherry': 3.0,
};
// Removing an entry.
fruits.remove('cherry');
```
```dart
var fruits = {
'apple': 2.0,
'banana': 1.5,
'cherry': 3.0,
};
## Conclusion
## Handling Exceptions
### The `try`, `catch`, and `finally` Blocks
```dart
try {
// Code that may raise an exception.
} catch (exception) {
// Code to handle the exception.
} finally {
// Code that runs regardless of whether an exception was
thrown.
}
```
```dart
void main() {
try {
var result = 10 ~/ 0; // Attempting to divide by zero.
print("Result: $result");
} on IntegerDivisionByZeroException {
print("Cannot divide by zero.");
} catch (e) {
print("Error: $e");
} finally {
print("Execution completed.");
}
}
```
void main() {
try {
validateAge(-5); // Calling a function that throws an
exception.
} catch (e) {
print("Error: $e");
}
}
```
```dart
class CustomException implements Exception {
final String message;
CustomException(this.message);
@override
String toString() => message;
}
void main() {
try {
throw CustomException("This is a custom exception.");
} catch (e) {
print("Caught custom exception: $e");
}
}
```
In this example, we define a custom exception class
`CustomException` that extends `Exception`. We provide a
constructor that accepts a message, and we override the
`toString` method to return the message when the
exception is printed. Custom exceptions allow you to create
meaningful and informative error messages tailored to your
application's needs.
## Exception Propagation
```dart
void innerFunction() {
throw Exception("An error occurred in innerFunction.");
}
void outerFunction() {
try {
innerFunction();
} catch (e) {
print("Caught exception in outerFunction: $e");
}
}
void main() {
outerFunction();
}
```
## Assertions
```dart
void divide(int a, int b) {
assert(b != 0, "Division by zero is not allowed.");
print("Result: ${a / b}");
}
void main() {
divide(10, 0); // Throws AssertionError in debug mode.
}
```
```dart
void divide(int a, int b) {
assert(() {
if (b == 0) {
throw AssertionError("Division by zero is not allowed.");
}
return true;
}(), "Assertion failed");
print("Result: ${a / b}");
}
void main() {
divide(10, 0); // Throws AssertionError in debug mode.
}
```
## Conclusion
## Futures in Dart
### What Are Futures?
```dart
Future<int> fetchUserData() {
return Future<int>(() {
// Simulate fetching user data.
return 42; // Return a value once the task is completed.
});
}
```
```dart
Future<int> fetchUserData() async {
// Simulate fetching user data.
await Future.delayed(Duration(seconds: 2)); // Simulate a
2-second delay.
return 42; // Return a value once the task is completed.
}
```
In this example, the `fetchUserData` function is declared as
asynchronous using the `async` keyword. It uses `await` to
pause execution until the `Future` created by
`Future.delayed` completes after a 2-second delay.
To work with the result of a `Future`, you can use the `then`
method to specify a callback function that will be invoked
when the `Future` completes successfully. You can also use
the `catchError` method to handle errors.
```dart
void main() {
fetchUserData()
.then((value) {
print("User data: $value");
})
.catchError((error) {
print("Error: $error");
});
}
```
```dart
Future<void> fetchUserData() async {
final future1 = fetchUserDataFromServer();
final future2 = fetchUserDataFromCache();
```dart
Future<void> fetchData() async {
// Asynchronous operations with await.
final result = await fetchUserData();
print("Fetched data: $result");
}
```
```dart
Future<void> fetchData() async {
final result = await fetchUserData();
print("Fetched data: $result");
}
```
```dart
void main() {
fetchUserData()
.then((value) {
print("User data: $value");
})
.catchError((error) {
print("Error: $error");
});
}
```
You can also use `async` and `await` to handle errors more
concisely within an asynchronous function.
```dart
Future<void> fetchData() async {
try
{
final result = await fetchUserData();
print("Fetched data: $result");
} catch (error) {
print("Error: $error");
}
}
```
In this example, the `try` block contains the code that may
throw an exception. If an exception occurs, it is caught by
the `catch` block, allowing you to handle it gracefully.
## Conclusion
## Libraries in Dart
```dart
// my_library.dart
library my_library;
void greet() {
print("Hello from my library!");
}
class Person {
String name;
Person(this.name);
}
```
In this example, we create a Dart library named
`my_library` in a file named `my_library.dart`. The library
contains a `greet` function and a `Person` class.
```dart
import 'my_library.dart';
void main() {
greet(); // Calling the greet function from my_library.
```dart
// utils.dart
library my_project.utils;
```dart
import 'utils.dart';
void main() {
final result = add(5, 3); // Using the add function from the
utils library.
print("Result: $result");
}
```
## Packages in Dart
```
my_package/
lib/
my_library.dart
pubspec.yaml
```
```yaml
name: my_package
description: A sample Dart package
version: 1.0.0
```
```yaml
dependencies:
http: ^3.0.0
```
## Conclusion
## Understanding Flutter
```dart
class MyButton extends StatelessWidget {
final String text;
MyButton(this.text);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
// Handle button press.
},
child: Text(text),
);
}
}
```
```dart
class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text('Count: $count'),
ElevatedButton(
onPressed: increment,
child: Text('Increment'),
),
],
);
}
}
```
For example, here's how you can create a simple layout with
a row of two buttons using the `Row` widget:
```dart
Row(
children: <Widget>[
ElevatedButton(
onPressed: () {
// Handle button 1 press.
},
child: Text('Button 1'),
),
ElevatedButton(
onPressed: () {
// Handle button 2 press.
},
child: Text('Button 2'),
),
],
)
```
```dart
final ThemeData myTheme = ThemeData(
primaryColor: Colors.blue,
accentColor: Colors.green,
fontFamily: 'Roboto',
textTheme: TextTheme(
headline1: TextStyle(fontSize: 24, fontWeight:
FontWeight.bold),
bodyText1: TextStyle(fontSize: 16),
),
);
```
```dart
GestureDetector(
onTap: () {
// Handle tap gesture.
},
child: Container(
width: 200,
height: 100,
color: Colors.blue,
child: Center(
child: Text('Tap me'),
),
),
)
```
```dart
class AnimatedExample extends StatefulWidget {
@override
_AnimatedExampleState createState() =>
_AnimatedExampleState();
}
class _AnimatedExampleState extends
State<AnimatedExample> {
double _width = 100.0;
void _animateWidth() {
setState(() {
_width = _width == 100.0 ? 200.0 : 100.0;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
AnimatedContainer(
duration: Duration(seconds: 1),
width: _width,
height: 100,
color: Colors.blue,
),
ElevatedButton(
onPressed: _animateWidth,
child: Text('Animate Width'),
),
],
);
}
}
```
## Responsive Design
```dart
Row(
children: <Widget>[
Expanded(
flex: 1,
child: Container(color: Colors.red),
),
Expanded(
flex: 2,
child: Container(color: Colors.green),
),
],
)
```
## Conclusion
```yaml
dependencies:
http: ^0.13.3
```
```dart
import 'package:http/http.dart' as http;
if (response.statusCode == 200) {
// Request was successful, parse the response.
final data = json.decode(response.body);
print('Fetched books: $data');
} else {
// Request failed with an error code.
print('Request failed with status code:
${response.statusCode}');
}
}
```
```dart
import 'package:http/http.dart' as http;
if (response.statusCode == 201) {
// Book was created successfully.
final data = json.decode(response.body);
print('Created book: $data');
} else {
// Request failed with an error code.
print('Request failed with status code:
${response.statusCode}');
}
}
```
In this example, we use `http.post` to send a POST request
with a JSON body containing the book's title and author. We
check the response status code to determine if the book
was created successfully.
Similarly, you can use the `put` and `delete` functions from
the `http` package to send PUT and DELETE requests,
respectively. These functions work in a manner similar to
`post` and `get`.
```dart
import 'package:http/http.dart' as http;
if (response.statusCode == 200) {
// Request was successful, parse the response.
final data = json.decode(response.body);
print('Fetched private data: $data');
} else {
// Request failed with an error code.
print('Request failed with status code:
${response.statusCode}');
}
}
```
You can use Dart's `http` package to inspect the status code
and handle errors accordingly, as shown in the previous
examples.
class MyApiClient {
final String baseUrl;
final String apiKey;
MyApiClient(this.baseUrl, this.apiKey);
## Conclusion
```dart
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() =>
_CounterWidgetState();
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text('Counter: $_counter'),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
);
}
}
```
```dart
class CounterModel extends ValueNotifier<int> {
CounterModel(int value) : super(value);
void increment() {
value++;
notifyListeners();
}
}
CounterWidget(this.counterModel);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text('Counter: ${counterModel.value}'),
ElevatedButton(
onPressed: counterModel.increment,
child: Text('Increment'),
),
],
);
}
}
```
```dart
class CounterProvider extends InheritedWidget {
final int counter;
final Function() increment;
CounterProvider({
required this.counter,
required this.increment,
required Widget child,
}) : super(child: child);
@override
bool updateShouldNotify(CounterProvider oldWidget) {
return counter != oldWidget.counter;
}
}
```dart
class CounterModel extends ChangeNotifier {
int _counter = 0;
void increment() {
_counter++;
notifyListeners();
}
}
return Column(
children: <Widget>[
Text('Counter: ${counterCubit.state}'),
ElevatedButton(
onPressed: counterCubit.increment,
child: Text('Increment'),
),
],
);
}
}
```
In this example, the `CounterCubit` is a component that
manages the counter state. It extends `Cubit<int>` and
emits new states when the counter changes. The
`context.read` method is used to access the `CounterCubit`
instance.
```dart
// Define actions
enum CounterActions { increment }
// Reducer function
int counterReducer(int state, dynamic action) {
if (action == CounterActions.increment) {
return state + 1;
}
return state;
}
// Create a store
final store = Store<int>(
counterReducer,
initialState: 0,
);
```dart
class CounterController extends GetxController {
var counter = 0.obs;
void increment() {
counter++;
}
}
class CounterWidget extends StatelessWidget {
final CounterController controller =
Get.put(CounterController());
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Obx(() {
return Text('Counter: ${controller.counter}');
}),
ElevatedButton(
onPressed: controller.increment,
child: Text('Increment'),
),
],
);
}
}
```
## Conclusion
```dart
import 'package:test/test.dart';
```
2. Write a test case using the `test` function, and use
assertions to verify the expected behavior.
```dart
void main() {
test('Test addition', () {
expect(1 + 1, equals(2));
});
}
```
3. Run the tests using the Dart test runner. You can run tests
in the terminal by executing the following command:
```bash
dart test test_file.dart
```
The test runner will execute the test cases and report the
results.
```dart
void main() {
group('Math operations', () {
test('Test addition', () {
expect(1 + 1, equals(2));
});
test('Test subtraction', () {
expect(3 - 1, equals(2));
});
});
group('String operations', () {
test('Test string length', () {
expect('Dart'.length, equals(4));
});
```dart
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
void main() {
test('Test database interaction', () {
final database = MockDatabase();
when(database.query('SELECT * FROM
users')).thenReturn([
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
]);
```dart
import 'package:flutter_test/flutter_test.dart';
```
```dart
void main() {
testWidgets('Widget test example', (WidgetTester tester)
async {
// Your test code goes here.
});
}
```
```dart
void main() {
testWidgets('Widget test example', (WidgetTester tester)
async {
// Build a widget tree and pump it.
await tester.pumpWidget(MyApp());
4. Run the integration tests using the Flutter test runner. You
can run tests in the terminal using the following command:
```bash
flutter test test_file.dart
```
The test runner will launch the app in a headless mode,
execute the test cases, and report the results.
[Dart DevTools](https://pub.dev/packages/devtools) is a
suite of web-based tools that provide insights into your Dart
and Flutter applications during development. It offers
features such as:
```yaml
dev_dependencies:
devtools: ^latest_version
```
```bash
dart pub get
```
```dart
import 'package:devtools/devtools.dart';
void main() {
runApp(MyApp());
// Enable Dart DevTools by calling enableDevTools().
enableDevTools();
}
```
### Logging
```dart
void main() {
print('Starting the application.');
print('Application finished.');
}
```
## Conclusion
### 2. Optimization
### 4. Security
### 5. Performance
### 6. Documentation
### 7. Licensing
Verify that you have the necessary licenses for third-party
libraries and assets used in your project. Ensure compliance
with open-source licenses.
### 8. Versioning
Popular CI/CD services for Dart and Flutter include Travis CI,
CircleCI, Jenkins, and GitHub Actions.
## Post-Deployment Activities
feedback.
THANK YOU
PYTHON MASTERY FOR
INTERMEDIATE
PROGRAMMERS
```python
# Python Installation
Visit https://www.python.org/downloads/ to download and
install the latest version of Python.
When you run the above code, you should see the output:
`Hello, World!` This simple program demonstrates how
straightforward it is to write and execute Python code.
```python
# Numeric Data Types
age = 30 # Integer
temperature = 25.5 # Floating-point number
complex_num = 2 + 3j # Complex number
```
```python
# Strings
```python
# Lists
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana',
'orange']
mixed_list = [10, 'John', True,
3.14]
```
```python
# Tuples
```python
# Dictionaries
student = {
'name': 'Alice',
'age': 25,
'major': 'Computer Science'
}
```
```python
# If-elif-else Statements
num = 10
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
```
```python
# For Loop
count = 0
while count < 5:
print(count)
count += 1
```
## 1.4 Functions
Functions are blocks of code that perform a specific task and
can be reused throughout the program. They help in
organizing code and making it more modular.
```python
# Function Definition
def greet(name):
return f"Hello, {name}!"
# Function Call
print(greet("Alice"))
```
```python
# List Comprehensions
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
```
```python
# Class Definition
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
# Object Creation
dog1 = Dog("Buddy", 3)
print(dog1.name) # Output: Buddy
print(dog1.bark()) # Output: Woof!
```
```python
# File Handling
file_path = "example.txt"
# Writing to a File
with open(file_path, "w") as file:
file.write("Hello, File!")
## 1.8 Conclusion
In this chapter, we introduced Python and covered essential
concepts like variables, data types, control flow, functions,
list comprehensions, object-oriented programming, and file
handling. With this foundation, you are now ready to dive
deeper into the world of intermediate Python programming.
The subsequent chapters will explore more advanced topics
and techniques, empowering you to become a proficient
Python developer.
## 2.1 Lists
Lists are one of the most versatile and commonly used data
structures in Python. A list is an ordered collection of
elements, and it can hold values of different data types.
```python
# Creating Lists
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
mixed_list = [10, 'John', True, 3.14]
```
### 2.1.2 Accessing List Elements
You can access individual elements in a list using index
notation. Python uses zero-based indexing, so the first
element has an index of 0, the second element has an index
of 1, and so on.
```python
# Accessing List Elements
fruits = ['apple', 'banana', 'orange']
```python
# List Slicing
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```python
# Modifying Lists
fruits = ['apple', 'banana', 'orange']
```python
# List Methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
## 2.2 Tuples
Tuples are similar to lists, but they are immutable, meaning
their elements cannot be changed after creation.
```python
# Creating Tuples
coordinates = (10, 20)
colors = ('red', 'green', 'blue')
```
```python
# Accessing Tuple Elements
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
print(coordinates[1]) # Output: 20
```
```python
# Tuple Unpacking
coordinates = (10, 20)
x, y = coordinates
print(x) # Output: 10
print(y) # Output: 20
```
```python
# Using Tuples for Multiple Return Values
def get_student_info():
name = 'Alice'
age = 25
major = 'Computer Science'
return name, age, major
```python
# Creating Sets
numbers_set = {1, 2, 3, 4, 5}
fruits_set = {'apple', 'banana', 'orange'}
```
```python
# Modifying Sets
fruits_set = {'apple', 'banana', 'orange'}
# Removing an element
fruits_set.remove('apple')
print(fruits_set) # Output: {'banana', 'orange', 'mango'}
```
```python
# Set Operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
## 2.4 Dictionaries
Dictionaries are collections of key-value pairs. They provide
a way to store data with custom identifiers (keys) for
easy retrieval.
```python
# Creating Dictionaries
student = {
'name': 'Alice',
'age': 25,
'major': 'Computer Science'
}
```
```python
# Accessing Dictionary Elements
student = {
'name': 'Alice',
'age': 25,
'major': 'Computer Science'
}
```python
# Modifying Dictionaries
student = {
'name': 'Alice',
'age': 25,
'major': 'Computer Science'
}
## 2.5 Conclusion
In this chapter, we explored essential Python data
structures: lists, tuples, sets, and dictionaries. Each data
structure serves a specific purpose and has unique
characteristics. Understanding these data structures and
their respective operations is fundamental for efficient
programming in Python.
```python
# Function Definition
def greet(name):
return f"Hello, {name}!"
```
```python
# Function with Positional Arguments
def power(base, exponent):
return base ** exponent
result = power(2, 3)
print(result) # Output: 8
```
```python
# Function with Keyword Arguments
def describe_person(name, age, city):
return f"{name} is {age} years old and lives in {city}."
```python
# Function with Default Arguments
def greet_person(name, greeting="Hello"):
return f"{greeting}, {name}!"
```python
# Function with Return Statement
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # Output: 8
```
```python
# Function with Multiple Return Values
def get_min_max(numbers):
return min(numbers), max(numbers)
numbers = [4, 2, 7, 1, 9]
min_val, max_val = get_min_max(numbers)
print(min_val) # Output: 1
print(max_val) # Output: 9
```
```python
# Lambda Function
multiply = lambda x, y: x * y
result = multiply(3, 4)
print(result) # Output: 12
```
```python
# Lambda with map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
```python
# Nested Functions
def outer_function():
print("This is the outer function.")
def inner_function():
print("This is the inner function.")
inner_function()
outer_function()
# Output:
# This is the outer function.
# This is the inner function.
```
## 3.4 Recursion
Recursion is the process of a function calling itself. It is a
powerful technique used to solve complex problems.
```python
# Recursion Example: Factorial
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) # Output: 120
```
## 3.5 Conclusion
Functions and lambdas are vital tools in Python for
structuring and organizing code. Functions allow us to
encapsulate code into reusable blocks, improving code
maintainability and readability. Lambdas, on the other hand,
provide a concise way to define small anonymous functions
for one-time use or as arguments to higher-order functions.
```python
# Class Definition
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return "Woof!"
```python
# Accessing Object Attributes and Methods
print(dog1.name) # Output: Buddy
print(dog1.age) # Output: 3
print(dog1.bark()) # Output: Woof!
```
## 4.2 Inheritance
### 4.2.1 Creating Subclasses
Inheritance allows a class (subclass) to inherit attributes and
methods from another class (superclass). It facilitates code
reuse and promotes a hierarchical organization of classes.
```python
# Creating Subclasses
class Labrador(Dog):
def fetch(self):
return "Fetching is fun!"
labrador1 = Labrador("Rocky", 5)
print(labrador1.name) # Output: Rocky
print(labrador1.fetch()) # Output: Fetching is fun!
```
```python
# Overriding Methods
class Poodle(Dog):
def bark(self):
return "Yap!"
poodle1 = Poodle("Charlie", 2)
print(poodle1.bark()) # Output: Yap!
```
```python
# Calling Superclass Methods
class GermanShepherd(Dog):
def bark(self):
return super().bark() + " Growl!"
german_shepherd1 = GermanShepherd("Max", 4)
print(german_shepherd1.bark()) # Output: Woof! Growl!
```
## 4.3 Encapsulation
def get_age(self):
return self.__age
## 4.4 Polymorphism
```python
# Polymorphism Example
class Bird:
def fly(self):
return "Bird flying high!"
class Fish:
def swim(self):
return "Fish swimming in water!"
def move(animal):
if isinstance(animal, Bird):
return animal.fly()
elif isinstance(animal, Fish):
return animal.swim()
else:
return "Unknown animal!"
bird = Bird()
fish = Fish()
```python
# Using ABCs in Python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
square = Square(5)
print(square.area()) # Output: 25
```
## 4.6 Conclusion
In this chapter, we explored advanced object-oriented
programming concepts in Python. We learned how to create
classes and objects, use inheritance to derive new classes,
and practice encapsulation to hide the internal details of a
class. Additionally, we discussed polymorphism, which
enables different classes to share a common interface.
```python
# math_operations.py (module)
def add(a, b):
return a + b
```python
# main.py
import math_operations
result = math_operations.add(3, 5)
print(result) # Output: 8
result = math_operations.subtract(10, 4)
print(result) # Output: 6
```
```python
# main.py
from math_operations import add, subtract
result = add(2, 3)
print(result) # Output: 5
result = subtract(10, 7)
print(result) # Output: 3
```
```python
# main.py
from math_operations import add as addition
result = addition(4, 6)
print(result) # Output: 10
```
```python
# math_operations.py (module)
def add(a, b):
return a + b
if __name__ == "__main__":
result = add(3, 5)
print(result) # Output: 8
```
```python
# math_operations.py (module)
def add(a, b):
return a + b
if __name__ == "__main__":
result = add(3, 5)
print(result) # Output: 8
```
```python
# main.py
import math_operations
result = math_operations.add(10, 4)
print(result) # Output: 14
```
```
my_package/
__init__.py
module1.py
module2.py
```
```python
# main.py
import my_package.module1
import my_package.module2
result = my_package.module1.add(3, 5)
print(result) # Output: 8
result = my_package.module2.subtract(10, 4)
print(result) # Output: 6
```
```python
# main.py
from my_package import module1 as m1
from my_package import module2 as m2
result = m1.add(2, 3)
print(result) # Output: 5
result = m2.subtract(10, 7)
print(result) # Output: 3
```
```python
# main.py
from my_package import *
result = module1.add(4, 6)
print(result) # Output: 10
result = module2.subtract(8, 5)
print(result) # Output: 3
```
```python
# my_package/__init__.py
print("Initializing my_package...")
```
```bash
# Installing a Package using pip
pip install package_name
```
```python
# Using a Third-Party Package
import requests
response = requests.get("https://www.example.com")
print(response.status_code) # Output: 200
```
```plaintext
# requirements.txt
requests==2.26.0
numpy==1.21.1
```
```bash
# Installing Packages from requirements.txt
pip install -r requirements.txt
```
## 5.6 Conclusion
In this chapter, we explored Python modules and packages,
crucial concepts for organizing and reusing code in our
projects. We learned how to create and import modules, as
well as how to structure modules into packages using the
`__init__.py` file. Additionally, we examined the `__name__`
variable and its role in controlling code execution when a
module is run directly or imported.
```python
# Opening a File in Read Mode
file = open("example.txt", "r")
```
```python
# Using the with Statement
with open("example.txt", "r") as file:
data = file.read()
# Perform operations with the file
# File automatically closed outside the 'with' block
```
```python
# Reading the Entire File
with open("example.txt", "r") as file:
data = file.read()
print(data)
```
```python
# Reading Lines from a File using readline()
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line)
line = file.readline()
```
```python
# Reading Lines from a File using a Loop
with open("example.txt", "r") as file:
for line in file:
print(line)
```
### 6.2.3 Reading Data as a List of Lines
We can use the `readlines()` method to read all lines of a
file into a list, where each line is an element of the list.
```python
# Reading Data as a List of Lines
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line)
```
```python
# Writing Data to a File
with open("output.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a new line.")
```
### 6.3.2 Appending Data to a File
To append data to an existing file, we use the `write()`
method in append mode.
```python
# Appending Data to a File
with open("output.txt", "a") as file:
file.write("This is an appended line.")
```
```python
# Reading Input from the User
name = input("Enter your name: ")
print(f"Hello, {name}!")
```
```python
# Redirecting Input and Output Streams
with open("input.txt", "r") as f_in, open("output.txt", "w") as
f_out:
data = f_in.read()
f_out.write(data)
```
```python
# Using the seek() Method
with open("example.txt", "r") as file:
file.seek(5) # Move the file pointer to the 6th byte
data = file.read()
print(data)
```
```python
# Using the tell() Method
with open("example.txt", "r") as file:
data1 = file.read(5) # Read the first 5 bytes
position = file.tell() # Get the current position of the file
pointer
data2 = file.read() # Read from the current position till
the end
print(data1) # Output: "This "
print(position) # Output: 5
print(data2) # Output: "is the rest of the file."
```
```python
# Reading Binary Files
with open("image.jpg", "rb") as file:
data = file.read()
# Process binary data
```
```python
# Writing Binary Files
with open("output.bin", "wb") as file:
data = b'\x00\x01\x02\x03\x04'
file.write(data)
```
## 6.8 Conclusion
In this chapter, we explored file handling and input/output
operations in Python. We learned how to open and close
files, read and write data to files, and work with input and
output streams. Additionally, we looked at file seek and tell
operations and how to handle file handling errors.
```python
# Creating a Thread
import threading
def print_numbers():
for i in range(1, 6):
print(i)
thread = threading.Thread(target=print_numbers)
```
```python
# Starting a Thread
import threading
def print_numbers():
for i in range(1, 6):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
```
def print_numbers():
for i in range(1, 6):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
```python
# Using Lock for Thread Synchronization
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
lock.acquire()
counter += 1
lock.release()
def decrement():
global counter
for _ in range(100000):
lock.acquire()
counter -= 1
lock.release()
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=decrement)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Counter value:", counter)
```
```python
# Creating a Process
import multiprocessing
def print_numbers():
for i in range(1, 6):
print(i)
process = multiprocessing.Process(target=print_numbers)
```
```python
# Starting a Process
import multiprocessing
def print_numbers():
for i in range(1, 6):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
```
```python
# Waiting for a Process to Finish
import multiprocessing
def print_numbers():
for i in range(1, 6):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()
## 7.6 Conclusion
```python
# Importing required libraries
import requests
from bs4 import BeautifulSoup
```python
# Importing required libraries
from selenium import webdriver
Apart from web scraping, Selenium can also be used for web
automation, enabling us to interact with web pages, fill
forms, click buttons, and perform various actions
programmatically.
```python
# Importing required libraries
from selenium import webdriver
username_input.send_keys("your_username")
password_input.send_keys("your_password")
submit_button.click()
## 8.7 Conclusion
```python
import numpy as np
print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std_dev)
```
```python
import pandas as pd
```python
import matplotlib.pyplot as plt
```python
import seaborn as sns
```python
import pandas as pd
import seaborn as sns
- **Choose the Right Plot Type:** Select a plot type that best
represents the data and the message you want to convey.
- **Label Axes and Add Titles:** Clearly label the axes and
add informative titles to the visualizations.
- **Use Color Wisely:** Use colors to highlight important
information, but avoid using too many colors that may
confuse the audience.
- **Avoid Chartjunk:** Eliminate unnecessary elements in
the plot that do not contribute to the message.
- **Provide Context:** Provide context and explanations to
help the audience understand the visualizations.
- **Ensure Accessibility:** Make sure the visualizations are
accessible to all, including those with visual impairments.
## 9.6 Conclusion
```python
import sqlite3
```python
# Creating a table
cursor.execute('''CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL)''')
We can insert data into the table using SQL's `INSERT INTO`
command.
```python
# Inserting data into the table
cursor.execute("INSERT INTO students (name, age) VALUES
(?, ?)", ("John", 25))
cursor.execute("INSERT INTO students (name, age) VALUES
(?, ?)", ("Alice", 22))
```python
# Querying data from the table
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
```python
import mysql.connector
```python
# Creating a table
cursor.execute('''CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL)''')
```python
# Inserting data into the table
cursor.execute("INSERT INTO employees (name, age)
VALUES (%s, %s)", ("John", 25))
cursor.execute("INSERT INTO employees (name, age)
VALUES (%s, %s)", ("Alice", 22))
```python
# Querying data from the table
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()
```bash
pip install sqlalchemy
```
```python
from sqlalchemy import create_engine
```python
from sqlalchemy import Column, Integer, String,
create_engine
from sqlalchemy.ext.declarative import declarative_base
```python
from sqlalchemy.orm import Session
session.add_all([employee1, employee2
])
session.commit()
```
```python
# Querying data from the table
employees = session.query(Employee).all()
## 10.5 Conclusion
```python
import numpy as np
from sklearn.linear_model import LinearRegression
# Sample data
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([2, 4, 5, 4, 5])
print("Predictions:", predictions)
```
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```python
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
```python
import numpy as np
import tensorflow as tf
from tensorflow
## 11.5 Conclusion
```bash
pip install django
```
```bash
django-admin startproject project_name
```
```bash
python manage.py startapp app_name
```
```python
# app_name/models.py
class BlogPost(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
```
```python
# app_name/views.py
def blog_posts(request):
posts = BlogPost.objects.all()
return render(request, 'blog/posts.html', {'posts': posts})
```
```html
<!-- app_name/templates/blog/posts.html -->
<!DOCTYPE html>
<html>
<head>
<title>Blog Posts</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% endfor %}
</ul>
</body>
</html>
```
```python
# app_name/urls.py
urlpatterns = [
path('posts/', views.blog_posts, name='blog_posts'),
]
```
```bash
python manage.py runserver
```
```bash
python manage.py makemigrations
python manage.py migrate
```
## 12.9 User Authentication
```python
# app_name/views.py
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form':
form})
```
```html
<!-- app_name/templates/registration/register.html -->
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>User Registration</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
</body>
</html>
```
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request,
data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('blog_posts')
else:
form = AuthenticationForm()
return render(request, 'registration/login.html', {'form':
form})
def user_logout(request):
logout(request)
return redirect('login')
```
```html
<!-- app_name/templates/registration/login.html -->
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
</head>
<body>
<h1>User Login</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</body>
</html>
```
## 12.10 Conclusion
```python
# server.py
import socket
while True:
# Wait for a connection
connection, client_address = server_socket.accept()
try:
print(f"Connection from {client_address}")
finally:
# Clean up the connection
connection.close()
```
```python
# client.py
import socket
try:
# Send data to the server
message = "Hello from the client!"
client_socket.sendall(message.encode())
# Receive the response from the server
data = client_socket.recv(1024)
print(f"Received: {data.decode()}")
finally:
# Clean up the connection
client_socket.close()
```
```python
# udp_server.py
import socket
while True:
# Receive data from the client
data, client_address = server_socket.recvfrom(1024)
```python
# udp_client.py
import socket
# Create a UDP socket
client_socket = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
try:
# Send data to the server
message = "Hello from the UDP client!"
client_socket.sendto(message.encode(), server_address)
finally:
# Clean up the connection
client_socket.close()
```
import socket
import threading
finally:
# Clean up the connection
connection.close()
while True:
# Wait for a connection
connection, client_address = server_socket.accept()
## 13.8 Conclusion
```python
# network_scanner.py
import socket
if __name__ == "__main__":
target_host = "example.com"
ports_to_scan = [80, 443, 22, 8080]
open_ports = scan_ports(target_host, ports_to_scan)
print(f"Open ports on {target_host}: {open_ports}")
```
import requests
from bs4 import BeautifulSoup
def scrape_security_news():
url = "https://example-security-news.com"
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
headlines = soup.find_all("h2", class_="news-title")
news = [headline.text for headline in headlines]
return news
return []
if __name__ == "__main__":
security_news = scrape_security_news()
for i, headline in enumerate(security_news, start=1):
print(f"{i}. {headline}")
```
```python
# certificate_expiry_checker.py
import ssl
import socket
from datetime import datetime
def get_certificate_expiry(domain):
try:
context = ssl.create_default_context()
with socket.create_connection((domain, 443)) as sock:
with context.wrap_socket(sock,
server_hostname=domain) as ssl_sock:
cert = ssl_sock.getpeercert()
expiry_date = datetime.strptime(cert['notAfter'],
'%b %d %H:%M:%S %Y %Z')
return expiry_date
except (ssl.SSLError, socket.gaierror,
ConnectionRefusedError, OSError):
return None
if __name__ == "__main__":
domains = ["example.com", "example.org",
"example.net"]
for domain in domains:
expiry_date = get_certificate_expiry(domain)
if expiry_date:
days_remaining = (expiry_date -
datetime.now()).days
print(f"Certificate for {domain} expires in
{days_remaining} days.")
else:
print(f"Could not retrieve certificate information for
{domain}.")
```
```python
# ssh_brute_force.py
import paramiko
ssh_client.close()
if __name__ == "__main__":
target_host = "example.com"
target_username = "admin"
password_list = ["password1", "password2",
"password3"]
ssh_brute_force(target_host, target_username,
password_list)
```
```python
# sql_injection_checker.py
import requests
def is_sql_injection_vulnerable(url):
payloads = ["' OR '1'='1", "' OR '1'='1' --", "' OR '1'='1'
#"]
for payload in payloads:
response = requests.get(f"{url}?id={payload}")
if "error" not in response.text.lower():
return True
return False
if __name__ == "__main__":
target_url = "https://example.com/products"
if is_sql_injection_vulnerable(target_url):
print("The web application is vulnerable to SQL
injection.")
else:
print("The web application is not vulnerable to SQL
injection.")
```
## 14.7 Conclusion
```python
# Inefficient Approach
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
# Efficient Approach
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
```
```python
# Inefficient Approach
total = 0
def calculate_sum(numbers):
global total
for num in numbers:
total += num
# Efficient Approach
def calculate_sum(numbers):
total = 0
for num in numbers:
total += num
return total
```
```python
# Inefficient Approach
squares = []
for num in range(1, 11):
squares.append(num**2)
# Efficient Approach
squares = [num**2 for num in range(1, 11)]
```
## 15.4 Use `join()` for String Concatenation
```python
# Inefficient Approach
names = ['Alice', 'Bob', 'Charlie']
greeting = ""
for name in names:
greeting += f"Hello, {name}! "
# Efficient Approach
names = ['Alice', 'Bob', 'Charlie']
greeting = " ".join(f"Hello, {name}!" for name in names)
```
For comparing with `None`, prefer using `is` and `is not`
instead of `==` and `!=`, as it is faster and more explicit.
# Efficient Approach
x = None
if x is None:
print("x is None")
```
```python
# Inefficient Approach
x=5
y = 10
operation = "x + y"
result = eval(operation)
# Efficient Approach
x=5
y = 10
result = x + y
```
```python
# Inefficient Approach
file = open("data.txt", "r")
data = file.read()
file.close()
# Efficient Approach
with open("data.txt", "r") as file:
data = file.read()
```
```python
# Inefficient Approach
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num * 2
# Efficient Approach
numbers = [1, 2, 3, 4, 5]
total = 0
multiplier = 2
for num in numbers:
total += num * multiplier
```
## 15.9 Use `timeit` for Performance Measurement
```python
# timeit_example.py
import timeit
def sum_with_loop(numbers):
total = 0
for num in numbers:
total += num
return total
def sum_with_builtin(numbers):
return sum(numbers)
```python
# Inefficient Approach with List
def get_numbers_list(n):
numbers = []
for i in range(n):
numbers.append(i)
return numbers
# Efficient Approach with Generator
def get_numbers_generator(n):
for i in range(n):
yield i
```
```python
# profile_example.py
import cProfile
import pstats
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def main():
result = factorial(10)
print(result)
if __name__ == "__main__":
# Profile the code
profiler = cProfile.Profile()
profiler.enable()
main()
profiler.disable()
.Stats(profiler)
stats.print_stats()
```
# Efficient Approach
names = set(["Alice", "Bob", "Charlie"])
if "Alice" in names:
print("Alice is present in the set.")
```
```python
# fibonacci.pyx
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
```
## 15.14 Conclusion