list.sort()
- Type: A method of the list object.
- Behavior: Sorts the list in place.
- Return Value: Returns
None
. - Example:
my_list.sort()
list.sort()
None
.my_list.sort()
# decorator example in Python | |
# decorator function | |
def decorator(func): | |
def wrapper(): | |
print("Runs before") # do something before | |
func() # call the original function | |
print("Runs after") # do something after | |
return wrapper |
try: | |
hour_24 = int(input("Enter hour in 24h format (0–23): ")) | |
if 0 <= hour_24 <= 23: | |
hour_12 = hour_24 % 12 or 12 | |
print(f"The hour in 12h format is: {hour_12}") | |
else: | |
print("Error: Please enter a valid hour between 0 and 23.") | |
except ValueError: |
class Dog: | |
# the __init__ method is a special method called the constructor | |
# it initializes the attributes of a new instance | |
# 'self' refers to the new Dog object being created | |
def __init__(self, name, breed): | |
self.name = name # 'self.name' assigns the 'name' argument to the 'name' attribute of *this* dog | |
self.breed = breed # 'self.breed' assigns the 'breed' argument to the 'breed' attribute of *this* dog | |
self.is_hungry = True # every new dog starts hungry. This is an instance attribute | |
# this is an instance method, 'self' refers to the specific dog instance |
# read text file | |
with open("log.txt", "r") as f: | |
content = f.read() | |
# write (overwrite) text | |
with open("log.txt", "w") as f: | |
f.write("New log start\n") | |
# append to file | |
with open("log.txt", "a") as f: |
class Demo: | |
def __init__(self): | |
self.public_var = "Public" | |
self._protected_var = "Protected" | |
self.__private_var = "Private" | |
def show_vars(self): | |
print(self.public_var) | |
print(self._protected_var) | |
print(self.__private_var) |
name = "Marius" | |
text = f"MyNameIs{name}" # MyNameIsMarius | |
print(text[0:6]) # 'MyName' - from start (0) up to 6 (exclusive) | |
print(text[:6]) # 'MyName' - same as above, starts by default to 0 | |
print(text[6:]) # 'IsMarius' - from index 6 to end | |
print(text[::2]) # 'MNmIMru' - starts with index 0 then every 2nd character | |
print(text[::-1]) # 'suiraMsIemaNyM' - reversed string | |
print(text[-7:-1]) # 'sMarius' - slice from index -7 to -1 | |
print(text[-1:-8:-1]) # 'suiraMs' - slice backward from end (negative step), stops at index -8 (exclusive) |
import this | |
# run the .py file | |
# and have a great coding day! |
To view all installed packages, you can utilize either of the following commands in the Terminal:
pip list
or
pip freeze
To convert a .py file to .exe you can use PyInstaller
pip install pyinstaller