Learn Python variables with this beginner-friendly guide. Understand variable naming rules, assignments, and operations with examples and exercises. Perfect for students and professionals starting their Python journey.
pip.You can import a module or specific functions from it using the import keyword.
import math
print(math.sqrt(16)) # Output: 4.0
from math import sqrt
print(sqrt(16)) # Output: 4.0
as:
import numpy as np
print(np.array([1, 2, 3]))
Python comes with many useful built-in modules. Some commonly used ones include:
math: Provides mathematical functions like sqrt(), pow(), and constants like pi.datetime: Useful for handling date and time operations.random: For generating random numbers.os: For interacting with the operating system (e.g., file manipulation).Example with random:
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
To install third-party libraries, you can use pip. For example, to install the popular requests library:
pip install requests
Once installed, you can import it and use it in your code:
import requests
response = requests.get('https://www.example.com')
print(response.text)
You can organize your code into modules by saving your functions or classes in separate Python files. For example, if you have a file mymodule.py:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
You can import and use the module like this:
import mymodule
print(mymodule.greet("Alice"))
math modulemath module to calculate the area of a circle. The formula is Area = π * r², where r is the radius.math module.calculate_area(radius) that returns the area of the circle.random modulerandom module.randint() function to simulate the die rolls.mymodule.py.is_prime(n) that returns True if the number is prime and False otherwise.is_prime() function with a few numbers.