Python Programming Basics tutorial for beginners

Python Programming Basics - Tutorial For Beginner's

Introduction to Python Programming Basics

Python is a high-level, interpreted programming language known for its simplicity and readability. Developers widely use it 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 in Python

Python syntax is clean and easy to understand.
Python is case-sensitive language. Thus, there’s no need to insert terminator at end of line. 
Additionally, 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

Python Variables and Operators

Now that you are familiar with Python’s basic data types, let’s look at how to store and manipulate data using variables and operators.

Variables

Variables store data that you can  use and manipulate.
Python is non-typed language, due to which there is 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 execute code repetitively.

For loop:

You can use For loop 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. We can define functions using the def keyword.

In-built functions:

Essentially, In-built functions are pre-defined in python library, and you can  directly use them without declaring them.

Example:
				
					print("Hello world!")
				
			

User Defined functions:

Users define the functions on their own, and you can also declare these functions 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 in Python

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 in Python Programming

You can read from and write to files in Python using in-built functions.

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

Error Handling and Exceptions in Python Basics

You can handle errors in Python using try, except, and 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 in Python Programming

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 in Python

  • Constructor (__init__): Python automatically calls the constructor method to create an object. 
  • Destructor (__del__): Similarly, Python triggers the destructor when the 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
				
			

Basics of Inheritance in Python

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 in Python

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
				
			

Concept of Polymorphism in Python

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 in Python Programming

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 in Python

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 : Mastering Python Programming Basics

You’ve built 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.