Python Programming Basics tutorial for beginners

Python Programming Basics

Introduction 

Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in various fields such as web development, data science, automation, and more. In this guide you will explore Python Programming Basics for beginners.

Basic Syntax and Data Types

Python syntax is clean and easy to understand.
Python is case-sensitive language. There’s no need to insert terminator at end of line. 
Some basic data types include:

  • Integers: Whole numbers, e.g., x = 5
  • Floats: Decimal numbers, e.g., y = 3.14
  • Strings: Text data, e.g., name = "Alice"
  • Booleans: True or False values, e.g., is_valid = True

Variables and Operators

Variables

Variables store data that can be used and manipulated.
Python is non-typed language, i,e., no need to predefine data types of variable.

				
					a = "hello world"
b = 10
c = 10.5
				
			
Operators

Operators perform operations on variables:

  • Arithmetic Operators: +, -, *, /
  • Comparison Operators: ==, !=, >, <
  • Logical Operators: and, or, not

Control Flow Statements

Control flow statements determine the execution flow of a program.

Conditional Statements :
				
					if condition:
    # code block
elif another_condition:
    # another code block
else:
    # code block
				
			
Loops :

Loops are used to execute code repetitively.

For loop:
For loop is used when you know number of iterations.

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

while loop:
While loop is used to repeat a specific block of statements until a condition is met

				
					while condition:
     # code block
				
			

Functions in Python

Functions are reusable blocks of code. They are defined using the def keyword.

In-built functions:

Functions that are pre-defined in python library.  These functions are directly used without declaring.
Example:

				
					print("Hello world!")
				
			
User Defined functions:

Functions are reusable blocks of code. They are defined using the def keyword.

Declaring a function :

				
					def function_name(parameters):
        # code block
        return value
				
			

Calling  a function :

				
					function_name(attributes)
				
			

Working with Lists, Tuples, set and Dictionaries

Lists , set , tuple and dictionaries are built-in data structures in Python.

  • Lists: Ordered mutable collections, e.g., my_list = [1, 2, 3]
  • Dictionaries: Key-value pairs, e.g., my_dict = {“key1”: “value1”}
  • Tuple : Ordered immutable collections, e.g., my_tuple = (1,2,3)
  • Set: Unordered collections, e.g., my_set = {1,2,3,4}

File Handling

Python allows you to read from and write to files.

				
					with open('filename.txt', 'r') as file:
    content = file.read()
				
			

Error Handling and Exceptions

Python provides a way to handle errors using try, except, finally blocks.

				
					try:
    # code block
except Exception as e:
    # handle exception
finally:
    # code block (always executed)
				
			

Object-Oriented Programming in Python

Python supports Object-Oriented Programming (OOP), which allows you to create classes and objects, making your code more modular, reusable, and easier to maintain.

Creating Classes and Objects

A class is a blueprint for creating objects (instances). Each object can have attributes (variables) and methods (functions) defined in the class.

				
					class MyClass:
    def __init__(self, name):
        self.name = name  # Attribute

    def greet(self):
        print(f"Hello, {self.name}")  # Method

# Creating an object
obj = MyClass("Alice")
obj.greet()  # Output: Hello, Alice
				
			
Constructor and Destructor
  • Constructor (__init__): The constructor is a special method that is automatically called when an object is created. It initializes the object’s attributes.
  • Destructor (__del__): The destructor is a special method that is called when an object is deleted or goes out of scope.
				
					class MyClass:
    def __init__(self, name):
        self.name = name
        print(f"{self.name} created")

    def __del__(self):
        print(f"{self.name} destroyed")

obj = MyClass("Alice")
del obj  # Output: Alice destroyed
				
			
Inheritance

Inheritance allows a new class to inherit attributes and methods from an existing class. The new class is called the derived or child class, and the existing class is the base or parent class.

				
					class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def bark(self):
        print("Dog barks")

dog = Dog()
dog.speak()  # Output: Animal speaks
dog.bark()   # Output: Dog barks
				
			
Encapsulation

Encapsulation is the bundling of data and methods that operate on that data within a single unit or class. It also involves restricting access to some of the object’s components, which is achieved through private or protected attributes.

				
					class MyClass:
    def __init__(self, name):
        self.__name = name  # Private attribute

    def get_name(self):
        return self.__name

obj = MyClass("Alice")
print(obj.get_name())  # Output: Alice
				
			
Polymorphism

Polymorphism allows different classes to be treated as instances of the same class through inheritance. It enables methods to be used interchangeably between objects of different classes.

				
					class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

class Cat(Animal):
    def speak(self):
        print("Cat meows")

def make_animal_speak(animal):
    animal.speak()

dog = Dog()
cat = Cat()

make_animal_speak(dog)  # Output: Dog barks
make_animal_speak(cat)  # Output: Cat meows
				
			

Modules and Packages

Modules are Python files containing definitions and statements. Packages are directories containing multiple modules.

  • Importing Modules: import module_name
  • Using Packages: from package_name import module_name

Working with External Libraries

Python has a vast ecosystem of external libraries that extend its functionality.

  • Installing Libraries: pip install library_name
  • Using Libraries: import library_name

Example :

				
					import numpy as np 
import pandas as pd
				
			

Conclusion

This tutorial has provided a solid foundation in Python Basic Programming, covering everything from basic syntax to more advanced concepts like functions and object-oriented programming. With these skills, you’re well-equipped to explore Python further and apply it to various fields such as web development, data analysis, and automation. Keep practicing and experimenting to deepen your understanding and enhance your programming abilities.