Definition: Data types specify the type of data that a variable can hold. Python is dynamically-typed, which means you don't need to declare a variable’s type explicitly.
Explanation: Python provides several built-in data types, including numeric types, sequences, mappings, and more.
Basic Data Types:
int
: Integerfloat
: Floating-point numbercomplex
: Complex numberstr
: Stringbool
: BooleanExample:
num = 10
price = 19.99
letter = 'A'
is_python_fun = True
print("Integer:", num)
print("Float:", price)
print("String:", letter)
print("Boolean:", is_python_fun)
Definition: Variables are containers for storing data values. In Python, you can assign values to variables without explicitly declaring their type.
Explanation: Variables in Python are dynamically typed, meaning their type is determined at runtime based on the value assigned.
Example:
local_variable = 10
global_variable = 5
def example_function():
local_variable = 20
print("Local Variable:", local_variable)
print("Global Variable:", global_variable)
example_function()
print("Global Variable outside function:", global_variable)
Definition: Loops are used to execute a block of code repeatedly based on a condition.
Explanation: Python supports several types of loops: for
loop and while
loop.
for i in range(5):
print("Iteration:", i)
i = 0
while i < 5:
print("Iteration:", i)
i += 1
Definition: Conditions control the flow of the program based on certain criteria.
Explanation: Python supports conditional statements like if
, elif
, and else
to make decisions in the code.
number = 10
if number > 0:
print("Number is positive.")
else:
print("Number is non-positive.")
result = "Positive" if number > 0 else "Non-positive"
print(result)
Definition: Operators perform operations on variables and values.
Explanation: Python supports several types of operators: arithmetic, relational, logical, and assignment operators.
a = 10
b = 5
print("Sum:", a + b) # Output: 15
print("Difference:", a - b) # Output: 5
print("Product:", a * b) # Output: 50
print("Division:", a / b) # Output: 2.0
print("Is a greater than b?", a > b) # Output: True
print("Is a greater than 5 and b less than 10?", a > 5 and b < 10) # Output: True
Definition: OOP is a programming paradigm based on the concept of "objects", which can contain data and code.
Explanation: Python supports OOP and allows you to create classes and objects to model real-world entities.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking!")
dog1 = Dog("Buddy", 3)
dog1.bark()
Definition: Functions are blocks of code that perform a specific task and can be reused.
Explanation: In Python, functions are defined using the def
keyword.
Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))