def square(n):
return n * n
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
print(list(squared_numbers))
[1, 4, 9, 16]
---
#Python #FunctionalProgramming #Keywords
#21.
filter()Constructs an iterator from elements of an iterable for which a function returns true.
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
[2, 4, 6]
#22.
lambdaCreates a small anonymous function.
multiply = lambda a, b: a * b
print(multiply(5, 6))
30
#23.
defKeyword used to define a function.
def greet(name):
return f"Hello, {name}!"
print(greet("World"))
Hello, World!
#24.
returnKeyword used to exit a function and return a value.
def add(a, b):
return a + b
result = add(7, 8)
print(result)
15
#25.
isinstance()Checks if an object is an instance of a specified class.
number = 10
print(isinstance(number, int))
print(isinstance(number, str))
True
False
---
#Python #ControlFlow #Keywords
#26.
if, elif, elseUsed for conditional execution.
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C")
Grade B
#27.
forUsed to iterate over a sequence (like a list, tuple, or string).
colors = ["red", "green", "blue"]
for color in colors:
print(color)
red
green
blue
#28.
whileCreates a loop that executes as long as a condition is true.
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
Count is 0
Count is 1
Count is 2
#29.
breakExits the current loop.
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
#30.
continueSkips the rest of the code inside the current loop iteration and proceeds to the next one.
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
---
#Python #StringMethods #TextManipulation
#31.
.upper()Converts a string into upper case.
message = "hello python"
print(message.upper())
HELLO PYTHON
#32.
.lower()Converts a string into lower case.
message = "HELLO PYTHON"
print(message.lower())
hello python
#33.
.strip()Removes any leading and trailing whitespace.
text = " some space "
print(text.strip())
some space
#34.
.split()Splits the string at the specified separator and returns a list.
sentence = "Python is fun"
words = sentence.split(' ')
print(words)
['Python', 'is', 'fun']
#35.
.join()Joins the elements of an iterable to the end of the string.
words = ['Python', 'is', 'awesome']
sentence = " ".join(words)
print(sentence)
Python is awesome
---
#Python #MoreStringMethods #Text
#36.
.replace()Returns a string where a specified value is replaced with another value.
text = "I like cats."
new_text = text.replace("cats", "dogs")
print(new_text)
I like dogs.
try:
result = 10 / 0
except ZeroDivisionError:
result = "You can't divide by zero!"
print(result)
You can't divide by zero!
#52.
open()Opens a file and returns a file object.
# This code creates a file named "myfile.txt"
# No direct output, but a file is created.
file = open("myfile.txt", "w")
file.close()
print("File created and closed.")
File created and closed.
#53.
.write()Writes the specified string to the file.
file = open("myfile.txt", "w")
file.write("Hello, File!")
file.close()
# No direct output, but content is written to myfile.txt
print("Content written to file.")Content written to file.
#54.
.read()Reads the content of the file.
# Assuming "myfile.txt" contains "Hello, File!"
file = open("myfile.txt", "r")
content = file.read()
print(content)
file.close()
Hello, File!
#55.
withA context manager, often used with
open() to automatically handle file closing.with open("myfile.txt", "w") as f:
f.write("This is safer!")
# The file is automatically closed here.
print("File written and closed safely.")File written and closed safely.
---
#Python #Keywords #Advanced
#56.
importUsed to import modules.
import math
print(math.sqrt(16))
4.0
#57.
from ... importImports specific parts of a module.
from datetime import date
today = date.today()
print(today)
2023-10-27
(Note: Output date will be the current date)
#58.
inMembership operator. Checks if a value is present in a sequence.
my_list = [1, 2, 3, 4, 5]
print(3 in my_list)
print(10 in my_list)
True
False
#59.
delDeletes an object (variable, list item, dictionary entry, etc.).
my_list = [10, 20, 30]
del my_list[1] # delete item at index 1
print(my_list)
[10, 30]
#60.
passA null statement. It's used when a statement is required syntactically but you do not want any command or code to execute.
def my_empty_function():
pass # To be implemented later
my_empty_function() # This does nothing and produces no error
print("Function executed without error.")
Function executed without error.
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤1