Scripts, Modules, Math Module, and Escape Sequences in Python

1. Scripts

In Python, a script is a file containing Python code that is intended to be executed. Scripts are typically used to automate tasks or to execute a series of operations. Here is an example of a simple Python script:

# my_script.py

 

# A simple Python script to print "Hello, World!"
print("Hello, World!")

To run this script, you would execute it from the command line:

python my_script.py

2. Modules

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. Modules are used to organize and reuse code. Here’s an example of a module:

# my_module.py

def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b

You can import and use this module in another script or module:

# another_script.py

import my_module

print(my_module.greet("Alice"))
print(my_module.add(5, 3))

3. Math Module

The math module provides access to mathematical functions. Here are some examples of how to use it:

import math

# Calculate the square root
print(math.sqrt(16))  # Output: 4.0

# Calculate the cosine of 0
print(math.cos(0))  # Output: 1.0

# Calculate the factorial of 5
print(math.factorial(5))  # Output: 120

The math module includes many other functions such as sin, log, exp, and constants like pi and e.

4. Escape Sequences

Escape sequences are used in strings to represent characters that are difficult to type directly, such as newlines, tabs, or quotes. Here are some common escape sequences:

  • \n: Newline
  • \t: Tab
  • \\: Backslash
  • \': Single quote
  • \": Double quote

Summary

  • Scripts: Files containing Python code to be executed.
  • Modules: Reusable files containing Python code, importable by other scripts or modules.
  • Math Module: Provides mathematical functions and constants.
  • Escape Sequences: Special characters in strings represented by a backslash followed by a character.
Buscar
Categorías
Read More
Technology
Scenarios of Computer Misuse and Their Effects on Society
Computer misuse can have widespread and serious impacts on society. It encompasses a wide range...
By ALAGAI AUGUSTEN 2024-07-13 07:42:14 0 3K
Business
How to Start Selling on Amazon FBA: A Step-by-Step Guide
Are you looking to tap into the booming world of e-commerce? Selling on Amazon using Fulfillment...
By Mpatswe Francis 2024-09-18 20:21:05 0 2K
Technology
Introduction to Linux: Hardware Components
Linux is a versatile and powerful operating system that can run on a wide variety of hardware....
By Tebtalks Access 2024-07-13 07:13:37 0 3K
Technology
S5 KABS ICT RESOURCE 2023
S5 KABS ICT RESOURCE 2023
By ICT TUTORIALS 2024-11-16 02:25:05 0 2K
Technology
Learning Microsoft Excel can be beneficial for a variety of reasons
Data Organization: Excel allows users to store, organize, and manage large sets of data...
By Microsoft Excel Tips 2024-10-15 22:10:08 0 4K