HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat 2 Numbers
      • Python Example Code to Concat N Strings
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
    • Modules and Libraries
      • Python Code for Automation using BDD
      • Python Code to Load .SO File (and Invoke a Function)
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Basic Syntax

Let’s start with the basics of Python syntax.

Python uses indentation to define blocks of code. Instead of using braces like `{}` in other languages, Python relies on spaces or tabs. For example, if you have an `if` statement, the code that should run if the condition is true is indented:

if True:
print("This is inside the if block")
print("This is outside the if block")

Here, the second `print` statement is not indented, so it runs regardless of the `if` condition.

To add comments in your code, you use the `#` symbol. Anything after `#` on that line is a comment and is ignored by Python:

# This is a comment
print("Hello, World!") # This prints text to the screen

For multi-line comments, Python does not have a special syntax. Instead, you use triple quotes:

"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Hello again!")

Variables in Python are used to store data. You assign a value to a variable using `=`:

name = "Alice" # This is a string variable
age = 30 # This is an integer variable

Python handles different types of data, like strings, integers, and floats. Strings are text, integers are whole numbers, and floats are numbers with decimal points:

name = "Alice" # String
age = 30 # Integer
height = 5.6 # Float

You can perform operations with these data types. For example, you can add numbers:

x = 10
y = 5
sum = x + y
print(sum) # This will print 15

You can also combine strings:

greeting = "Hello"
name = "Alice"
message = greeting + " " + name
print(message) # This will print "Hello Alice"

Python also has functions, which are blocks of code designed to do something specific. You define a function using the `def` keyword:

def say_hello():
print("Hello!")

To use the function, you simply call it by its name followed by parentheses:

say_hello() # This will print "Hello!"

That’s a quick overview of basic Python syntax. As you practice and write more code, these concepts will become more familiar.

Comments

  • Single-line comment: # This is a comment
  • Multi-line comment:
    """
    This is a
    multi-line comment
    """

Variables

  • Define a variable: x = 5
  • Variable names can include letters, numbers, and underscores. They must start with a letter or underscore.

Data Types

  • Integer: x = 10
  • Float: y = 3.14
  • String: name = "Alice"
  • Boolean: flag = True

Basic Operations

  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Integer Division: a // b
  • Modulus: a % b
  • Exponentiation: a ** b

Strings

  • Concatenation: "Hello" + " World"
  • Repetition: "Hello" * 3
  • Accessing characters: name[0] (first character)
  • Slicing: name[1:4] (substring)

Lists

  • Create a list: my_list = [1, 2, 3]
  • Access elements: my_list[0]
  • Slice list: my_list[1:3]
  • Append item: my_list.append(4)

Tuples

  • Create a tuple: my_tuple = (1, 2, 3)
  • Access elements: my_tuple[0]

Dictionaries

  • Create a dictionary: my_dict = {'key1': 'value1', 'key2': 'value2'}
  • Access value: my_dict['key1']
  • Add item: my_dict['key3'] = 'value3'

Control Flow

  • If statement:
    if condition:
        # code
    elif another_condition:
        # code
    else:
        # code
  • For loop:
    for item in iterable:
        # code
  • While loop:
    while condition:
        # code

Functions

  • Define a function:
    
    def function_name(parameters):
        # code
        return value
                
  • Call a function: function_name(arguments)

Indentation

  • Python uses indentation to define code blocks. Consistent spacing is crucial.

Exception Handling

  • Try/Except:
    
    try:
        # code
    except ExceptionType as e:
        # code
                

Imports

  • Import a module: import module_name
  • Import specific items: from module_name import item_name

Classes and Objects

  • Define a class:
    
    class MyClass:
        def __init__(self, value):
            self.value = value
        def method(self):
            # code
                
  • Create an object: obj = MyClass(value)

Lambda Functions

  • Create a lambda function: lambda x: x * 2

List Comprehensions

  • Syntax: [expression for item in iterable if condition]
  • Example: squares = [x**2 for x in range(10)]
Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Examples
Up Next
Python Example Code to Concat 2 Numbers
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2026 Happiom. All Rights Reserved.