General Flashcards
Boolean Operators
and - Returns True if both operands are True, else False
or- Returns True if both operands are True, else False
not - Returns value opposite to the Truth value of the expression
Note: Never use relational
(==, !=) operators to compare boolean operations. Use is or is not operators for it.
For i in range(5)
for i in range(5): print(i)
Output:
0 1 2 3 4
for index, num in enumerate(nums):
enumerate(nums): - built in function. takes iterable and produces tuple(index, item) for each element
names = [“Nonna”, “Alan”]
for i, name in enumerate(names):
print(i, name)
Output:
0 Nonna
1 Alan
for item in list
names = [“Nonna”, “Alan”, “Amir”]
for name in names:
print(name);
Output: Nonna Alan Amir
for i in range(len(names))
names = [“Nonna”, “Alan”, “Amir”]
for i in range(len(names)):
print(i)
Output: 0 1 2
for char in string
for i in “Nonna”:
print(i)
Nonna
Functions
def my_function(param1, param2):
# Function body
result = param1 + param2
return result
result = my_function(5, 3)
Lambda Functions
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Function with no return statement
def my_function(x, y):
result = x + y
print(result)
output = my_function(3, 4)
print(output) # Output will be None
If you omit the return statement entirely, the function will still return None by default when it reaches the end of its code block
Break from for loop
for i in range(1, 10):
if i == 5:
break
print(i)
Continue to the next step
for i in range(10):
if i % 2 == 0:
continue
print(i)
Skipping specific items in an iteration based on a condition.
Avoiding the execution of certain parts of the loop’s body for specific cases.
Swaping elements without extra var
nums = [1,2,3,4,5]
i =0, j = 5
nums[i], nums[j] = nums[j], nums[i]
output: [5,2,3,4,1]
With statment
with open('hello.txt', 'w') as f: f.write('hello, world!')
Opening files using the with statement is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement.
Internally it looks like this:
~~~
f = open(‘hello.txt’, ‘w’)
try:
f.write(‘hello, world’)
finally:
f.close()
~~~
using a with statement allows you to abstract away most
of the resource handling logic. Instead of having to write an explicit
try…finally statement each time, using the with statement takes
care of that for us.
Context manager
It’s a simple “protocol” (or interface) that
your object needs to follow in order to support the with statement.
Basically, all you need to do is add __enter__ and __exit__ methods
to an object if you want it to function as a context manager. Python will call these two methods at the appropriate times in the resource
management cycle.
~~~
class ManagedFile:
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name, ‘w’)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
~~~
```
with ManagedFile(‘hello.txt’) as f:
… f.write(‘hello, world!’)
… f.write(‘bye now’)
~~~
name mangling
print(my_object.__private_var) # This will raise an AttributeError
it is a mechanism used to prevent naming conflicts in subclasses.
Python does not have true private attributes but name mangling is a way to avoid accidental overwriting of a parent class’s attributes by a subclass.
class MyClass: def \_\_init\_\_(self): self.\_\_private_var = 10 def get_private_var(self): return self.\_\_private_var my_object = MyClass() print(my_object.get_private_var()) # Outputs: 10 Trying to access the private variable directly will result in an AttributeError The private variable is actually stored as _MyClass\_\_private_var print(my_object._MyClass\_\_private_var) # Outputs: 10