Programming Concepts and Structures
Introduction to Programming Concepts
- Basic Data Types
- Common types include integers, strings, floats, etc.
- Example:
a = 10, b = 20.
- Operators:
+, -, *, /, are used for arithmetic operations.+: Addition -: Subtraction *: Multiplication /: Division
- Variables: Storage locations for data.
- Example:
name = input("Enter your name: ")
- Input Handling: Gathering user input.
- Example:
age = input("Enter your age: ").
Control Statements
- Conditional Statements (if-else):
- Used to perform different actions based on conditions.
- Example:
if age > 18:
print("Adult")
else:
print("Minor")
Loops
- For Loop: Iterates over a sequence.
- Syntax:
for i in range(start, end): - Example:
for i in range(1, 11):
print(i)
- While Loop: Continues until a condition is false.
- Example:
count = 0
while count < 5:
print(count)
count += 1
Functions
- Function Definition: A block of code that only runs when it is called.
- Example:
def greet():
print("Hello!")
- Parameters and Return Values: Function parameters can be used to pass data.
- Example:
def add(a, b):
return a + b
Lists and Collections
- Lists: Ordered collections of items.
- Example:
fruits = ["apple", "banana", "cherry"].
- Dictionaries: Key-value pairs.
- Example:
student = {"name": "John", "age": 20}.
Classes and Objects
- Object-Oriented Programming (OOP): Using objects to structure programs.
- Class Definition: A blueprint for objects.
- Example:
class Dog:
def bark(self):
print("Woof!")
- Inheritance: Mechanism where one class derives from another.
- Example:
class Animal:
def sound(self):
print("Animal sound")
class Dog(Animal):
def sound(self):
print("Bark")
Error Handling
- Try-Except Block: Handles exceptions to prevent program crashes.
- Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Conclusion
- Understand the foundational concepts of programming.
- Practice writing small programs to strengthen your understanding.