+ 2
Python
How to work with dictionary and modules
9 Respuestas
+ 5
You can learn them in Python courses, such as Python Developer: https://www.sololearn.com/learn/courses/python-developer
Still here's the basics:
Dictionary:
Dictionary is a collection of key-value pairs, each key holding a value. Like here, where name holds "Alan" and age holds 20:
person = {
"name": "Alan",
"age": 20
}
Access values:
print(person) # Outputs the dictionary
print(person["name"]) # Outputs "Alan"
Add, update and remove values:
person["name"] = "John" # Value of 'name' is "John"
person["profession"] = "Programmer" # Added new key 'profession' with value "Programmar"
person.pop["age"] # Removes the key-value pair of "age"
Module:
Modules are files that have variables, classes, functions and more set-up in a way that you can reuse them in your code to make tasks easier and optimized.
Import a module with import:
import math
Using a math function:
print(math.sqrt(25)) #square root of 25
Learn more about these in Python course and other resources 👍
+ 3
Sololearn doesn't allow module creation
+ 1
Creating a module: Save your functions or variables in a .py file, and you can import them into other Python scripts.
Importing modules: You use the import keyword to access the functionality of the module.
Using functions from the module: You can call the functions or access variables as needed.
+ 1
Quick Tip: Working on a problem or small project will help you develop the knowledge. For instance, this is a good start:
https://www.w3resource.com/JUMP_LINK__&&__python__&&__JUMP_LINK-exercises/dictionary/
+ 1
Hi
+ 1
Tell me anyone , the importance of python
+ 1
Steps to Create a Module in Python
1. Create a Python File (Module)
A module is just a .py file with some Python code.
Example: Create a file called mymodule.py and add the following code:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
pi = 3.14159
2. Import the Module in Another Python File
Now, you can import this module in another Python script and use its functions and variables.
Example: Create another Python file (main.py) and import mymodule:
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
print(mymodule.add(5, 3)) # Output: 8
print(mymodule.pi) # Output: 3.14159
3. Import Specific Functions or Variables (Optional)
Instead of importing the whole module, you can import only specific functions or variables:
from mymodule import greet, pi
print(greet("Bob")) # Output: Hello, Bob!
print(pi) # Output: 3.14159
+ 1
4. Use an Alias for the Module (Optional)
You can rename the module while importing it using as:
import mymodule as mm
print(mm.greet("Charlie")) # Output: Hello, Charlie!