DEV Community

Cover image for Basic Python: 1. Introduction to python
Akash Singh
Akash Singh

Posted on

Basic Python: 1. Introduction to python

Python is a popular and versatile programming language that has gained immense popularity due to its simplicity, readability, and a wide range of applications. It's a great choice for beginners and experienced developers alike. In this blog post, we'll provide you with a gentle introduction to Python programming, along with some examples to get you started.

Table of Contents

  1. Why Python?
  2. Your First Python Program
  3. Comments
  4. Variables and Data Types
  5. Operators
  6. Conditional Statements
  7. Loops
  8. Input and Output
  9. Functions
  10. Exception Handling
  11. Modules and Packages
  12. File Handling

1. Why Python?

Python is known for its clear and concise syntax, which makes it easy to write and understand code. It emphasizes readability and reduces the cost of program maintenance. Here are a few reasons why Python is a fantastic programming language to learn:

  1. Easy to Learn: Python's syntax is straightforward and resembles the English language, making it an ideal language for beginners.

  2. Versatile: Python can be used for web development, data analysis, machine learning, artificial intelligence, automation, and more.

  3. Large Standard Library: Python comes with a vast collection of modules and libraries that simplify common programming tasks.

  4. Community and Support: Python has a strong and active community, which means you can easily find help, tutorials, and resources online.

2. Your First Python Program

Let's start by writing a simple "Hello, world!" program in Python. This classic example is often used to introduce programming languages to beginners.

print("Hello, world!")
Enter fullscreen mode Exit fullscreen mode

In just one line, we've printed out the famous greeting. The print() function is used to display text or values on the screen. In Python 3, it's important to use parentheses around the text you want to print, unlike Python 2.

3. Comments

Comments are essential for code documentation and understanding. In Python, you can write single-line comments using the # symbol.

# This is a single-line comment

"""
This is a multi-line comment.
It can span multiple lines.
"""
Enter fullscreen mode Exit fullscreen mode

4. Variables and Data Types

At the core of every programming language are variables, which act as containers for storing and manipulating data. In Python, you don't need to declare the type of a variable explicitly. It dynamically determines the type based on the assigned value.

# Example of variable declaration
name = "Akash"
age = 23
height = 5.8
is_student = True
Enter fullscreen mode Exit fullscreen mode

Python supports various data types, including:

  • int: Integer values (e.g., 42)
  • float: Floating-point or decimal values (e.g., 3.14)
  • str: Strings, sequences of characters (e.g., "Hello, World!")
  • bool: Boolean values, representing True or False
  • list: Ordered collection of items
  • tuple: Immutable, ordered collection of items
  • dict: Key-value pairs (dictionary)
  • set: Unordered collection of unique items

5. Operators

Operators are symbols that perform operations on variables and values. Python supports a wide range of operators:

  • Arithmetic Operators: +, -, *, /, %, // (floor division), ** (exponentiation)
  • Comparison Operators: ==, !=, <, >, <=, >=
  • Logical Operators: and, or, not
  • Assignment Operators: =, +=, -=, *=, /=, %=
  • Identity Operators: is, is not
  • Membership Operators: in, not in

6. Conditional Statements

Conditional statements allow your program to make decisions and take different paths based on certain conditions. The most common ones are if, elif (short for "else if"), and else.

age = 18
if age < 18:
    print("You are a minor.")
elif age == 18:
    print("You just turned 18!")
else:
    print("You are an adult.")
Enter fullscreen mode Exit fullscreen mode

7. Loops

Loops enable you to repeat a block of code multiple times. Python offers two main types of loops: for and while.

For Loop:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

While Loop:

count = 0
while count < 5:
    print("Count:", count)
    count += 1
Enter fullscreen mode Exit fullscreen mode

8. Input and Output

User interaction is crucial in many programs. Python facilitates input and output operations using the input() and print() functions, respectively.

name = input("Enter your name: ")
print("Hello,", name)
Enter fullscreen mode Exit fullscreen mode

9. Functions

Functions are blocks of reusable code that perform specific tasks. They allow you to break down your code into smaller, manageable pieces. You can define your own functions in Python using the def keyword.

def greet(name):
    print("Hello,", name)

greet("Akash")
Enter fullscreen mode Exit fullscreen mode

You can also return values from functions using the return statement.

def add(a, b):
    return a + b

result = add(3, 5)
print("Sum:", result)
Enter fullscreen mode Exit fullscreen mode

10. Exception Handling

In Python, you can handle errors gracefully using try-except blocks.

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print("Result:", result)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input. Please enter a valid number.")
Enter fullscreen mode Exit fullscreen mode

11. Modules and Packages

Python's extensive standard library is complemented by third-party modules and packages. You can import and use these to enhance your programs.

import math
print(math.sqrt(25))  # Output: 5.0

from datetime import datetime
current_time = datetime.now()
print(current_time)
Enter fullscreen mode Exit fullscreen mode

12. File Handling

Python provides convenient ways to work with files, allowing you to read and write data to and from files.

Reading from a File

file_path = "sample.txt"
with open(file_path, "r") as file:
    content = file.read()
    print(content)
Enter fullscreen mode Exit fullscreen mode

Writing to a File

file_path = "output.txt"
data_to_write = "This is some data to write to the file."
with open(file_path, "w") as file:
    file.write(data_to_write)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)