Python Fundamentals with Examples

Python Fundamentals with Examples

Introduction

Python is one of the most popular programming languages due to its simplicity, readability, and versatility. It is widely used in web development, data science, artificial intelligence, automation, and more. This blog covers the fundamental concepts of Python, including conditions, loops, functions, object-oriented programming, and exception handling. Each topic is explained with examples to help beginners grasp the core principles of Python programming effectively.

1. Python Conditions

Python conditions use if statements to execute code based on true/false conditions created by comparisons and Boolean expressions. Conditional statements help make decisions in the program by checking conditions.

Example:

x = 10
y = 20
if x < y:
    print("x is less than y")
        

2. Comparison Operations

Comparison operations require using comparison operators: equal to ==, greater than >, less than <. These operators help compare values and return a Boolean result (True or False).

Example:

if x == 10:
    print("x is equal to 10")
if y > 10:
    print("y is greater than 10")
        

3. Inequalities Using !

An exclamation mark ! is used to define inequalities of a variable. The != operator checks if two values are not equal.

Example:

if x != y:
    print("x is not equal to y")
        

4. Comparing Different Data Types

You can compare integers, strings, and floats. Python allows comparisons between different types as long as they are comparable.

Example:

if "hello" == "hello":
    print("Strings are equal")
if 3.14 > 2:
    print("Pi is greater than 2")
        

5. Python Branching

Python branching directs program flow using if, else, and elif to execute different blocks of code based on conditions.

Example:

num = 5
if num > 0:
    print("Positive")
elif num == 0:
    print("Zero")
else:
    print("Negative")
        

6. Boolean Logic Operators

Boolean logic operators (and, or, not) are used to execute various operations on Boolean values.

Example:

x = True
y = False
if x and not y:
    print("x is True and y is False")
        

7. Python Loops

Loops automate repetitive tasks and iterate over data structures, reducing redundant code.

Example:

for i in range(3):
    print(i)
        

8. range() Function

The range() function generates a sequence of numbers with a specified start, stop, and step value, mainly used in loops.

Example:

for i in range(1, 6, 2):
    print(i)
        

9. for Loop Iteration

A for loop iterates over sequences like lists, tuples, or strings and executes a block of code for each item.

Example:

for char in "Python":
    print(char)
        

10. while Loop

A while loop executes a block of code as long as a specified condition remains true.

Example:

n = 3
while n > 0:
    print(n)
    n -= 1
        

11. Python Functions

Functions are reusable code blocks that perform specific tasks, improving modularity and reusability.

Example:

def greet(name):
    return "Hello " + name
print(greet("Alice"))
        

12. Built-in Functions

Python provides built-in functions like len() to find the length of a sequence and sum() to calculate the total sum.

Example:

numbers = [1, 2, 3]
print(len(numbers))
print(sum(numbers))
        

13. Sorting

The sorted() function creates a new sorted list, while sort() modifies the original list in place.

Example:

nums = [3, 1, 2]
print(sorted(nums))
nums.sort()
print(nums)
        

14. Creating Custom Functions

You can create custom functions in Python to perform specific operations.

Example:

def square(n):
    return n * n
print(square(4))
        

15. Documenting Functions

Functions should be documented using triple quotes to improve clarity and maintainability.

Example:

def add(a, b):
    """Returns the sum of two numbers."""
    return a + b
print(help(add))
        

16. Exception Handling

Exception handling prevents program crashes by managing errors using try-except.

Example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
        

17. Objects and Classes

Objects are instances of classes that encapsulate data and behavior, forming the basis of object-oriented programming.

Example:

class Car:
    def __init__(self, brand):
        self.brand = brand
    def show(self):
        print("Car brand:", self.brand)
car1 = Car("Toyota")
car1.show()
        

Conclusion

Python is a powerful and versatile programming language widely used for various applications, from web development to data science and automation. Mastering Python fundamentals is crucial for beginners to build a strong foundation in programming. By learning and practicing these concepts, developers can write clean, efficient, and scalable code, setting the stage for more advanced programming techniques and applications.

This is a fantastic way to get started with Python! Rohit Ramteke

要查看或添加评论,请登录

Rohit Ramteke的更多文章

社区洞察