Jul 18, 2024
python.exe
to PATH during installation.print('Hello, World!') # This is a comment
a = 1 # int
b = 2.0 # float
c = 'Python' # string
d = True # boolean
e = None # NoneType
+
, -
, *
, /
==
, !=
, >
, <
, >=
, <=
and
, or
, not
=
, +=
, -=
, *=
, /=
print(type(variable))
print(float('5.6')) # Type casting
name = 'Python' # or "Python" or '''Python'''
print(name[0:3]) # 'Pyt'
print(name[::-1]) # 'nohtyP'
len()
, endswith()
, startswith()
, capitalize()
, find()
, replace()
friends = ['apple', 'mango', 1, True]
friends.append('grape') # modifying list
values = (1, 2, 'Python')
.append()
, .sort()
, reverse()
, pop()
.count()
, .index()
data = {'name': 'Harry', 'marks': 95}
data['age'] = 21 # Adding new key-value pair
unique_items = {1, 2, 2, 3} # Duplicates not allowed
unique_items.add(4)
if age > 18:
print("Eligible")
else:
print("Not eligible")
while condition:
# code block
for item in sequence:
# code block
def greet(name):
print(f'Hello, {name}')
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
square = lambda x: x * x
try:
# Try to execute this block
except Exception as e:
print(e)
finally:
# This code runs no matter what
with open('example.txt', 'w') as file:
file.write('Hello, World!')
with open('example.txt', 'r') as file:
content = file.read()
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print('Woof!')
rex = Dog('Rex', 5)
rex.bark()
class Animal:
# Base class
class Dog(Animal):
# Derived class
touchvenvproject
pip install virtualenv
virtualenv myprojectenv
source myprojectenv/bin/activate
Lambda Functions: Inline anonymous functions
add = lambda x, y: x + y
print(add(2, 3)) # 5
Map, Filter, Reduce: Built-in functions for applying to lists.
map(function, list)
filter(function, list)
reduce(function, list)
List Comprehensions:
[x for x in range(5)] # [0, 1, 2, 3, 4]
Decorators:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper