Dive into Python (Part 1)

·

8 min read

Dive into Python  (Part 1)

Imagine a situation where you could talk to computers to perform any basic or complex tasks in an instant! This can be achieved by communicating with the system using a "Programming language."

A programming language is a set of rules and syntax that enables humans to communicate with computers. they are mainly divided into two levels of language i.e: low level language and high level language . High-level languages are closer to human-readable language, while low-level languages are closer to the machine's instructions

Today we will be looking into one such high level language called Python, which was named after the British comedy group Monty Python by Guido van Rossum.

Things to learn :

  1. Application of Python

  2. Basic Syntax and Data Types

  3. Control Flow

  4. Functions and Modules

  5. Error Handling

  6. Working with libraries

  7. Best Practices

Application of Python

The real-world applications of Python are endless, making it one of the most versatile and widely-used programming languages today. Here are some examples:

  • Web Development: Building dynamic websites with frameworks like Django and Flask.

  • Data Science and Analysis: Using libraries like Pandas and NumPy for data manipulation and analysis.

  • Machine Learning and AI: Creating intelligent systems with libraries like TensorFlow and scikit-learn.

  • Automation: Writing scripts to automate repetitive tasks, saving time and effort.

  • Game Development: Developing games and animations using libraries like Pygame.

  • Scientific Computing: Conducting complex computations and simulations with libraries like SciPy.

  • Finance: Analysing financial data and building trading algorithms.

these are only few of what this language can do , you can explore more about other applications of it here.

💡
Install Python: Visit the official Python website and follow the instructions to download the latest version of Python suitable for your operating system (Windows, macOS, Linux).

Basic Syntax and Data Types

Variable : A container that is used to store values in it . the values can be of any data type .
Data type : Its about what kind of data can be stored and manipulated. It defines the format, operations that can be performed on the data, and how it is stored in memory

Different types present :

  • Int - whole values can be positive or negative without having decimal point.
    ex : 10 , -99 , 78976

  • Float - numbers with decimal points , can be negative or positive.
    ex : 0.01 , 89.67

  • String - sequence of characters(letters) closed with "" or '
    ex : "hello world" , 'hello world'

  • Boolean - binary value indicating True or False.
    ex : on=True

  • List - ordered collection of items , which can be of different data types closed with []
    ex : nums =[10,90,5.5 , -9] (Here nums is variable)

  • Tuple - similar to list but the cannot be changes after creation (immutable).
    ex : age =( 10 , 20 , 20 )

  • Dictionary - collection of key - value pair , that has unique key values.
    ex : info = {'name': 'John', 'age': 30, 'city': 'New York'}

  • Set - unordered collection of unique items , closed with {}
    ex : temp ={55,67,78}

Comments in Python are used to help the developer understand more about the code; however, they do not add any functionality or interrupt the code while executing.

Single line comment

 # This is a single-line comment in PythonMultiple-Line

Multiple line comment

""" It can span across multiple lines and is typically 
used to provide detailed descriptions of code sections. """

Operations

While writing code in Python, we don't explicitly mention data types like in other languages such as Java or C because Python is dynamically typed i.e automatically determines the data type based on the value assigned.

Int or float

#Addition 
a = 10 
b = 20 
add = a + b 
print(add) #show the results ( used to print values )

#Subtract 
sub = a - b 
print(sub)

#Multiplication 
mul = a*b 
print(mul)

#division 
div = a/b #float value as output 
int_div = a//b #int value as output 
print(div)
print(int_div)

#power 
power = a ** b # a is base and b is power 
print(power)

Strings

# String declaration
my_string = "Hello, Python! Welcome to string operations."

# 1. Length of the string
print("Length of the string:", len(my_string))

# 2. Accessing characters in a string (indexing)
print("First character:", my_string[0])
print("Last character:", my_string[-1])
print("Substring from index 7 to 13:", my_string[7:14])

# 3. String concatenation
another_string = " Enjoy learning!"
concatenated_string = my_string + another_string
print("Concatenated string:", concatenated_string)

# 4. String repetition
repeated_string = my_string * 3
print("Repeated string:", repeated_string)

# 5. Checking substring presence
search_string = "Python"
if search_string in my_string:
    print("found in the string.")
else:
    print(" not found in the string.")

# 6. Splitting a string
words = my_string.split()
print("Words in the string:", words)

# 7. Joining strings
joined_string = " ".join(words)
print("Joined string:", joined_string)

# 8. Changing case of strings
print("Uppercase:", my_string.upper())
print("Lowercase:", my_string.lower())
print("Title case:", my_string.title())

# 9. Stripping whitespace
whitespace_string = "   Python Programming   "
print("Stripped string (both sides):", whitespace_string.strip())
print("Stripped string (left side):", whitespace_string.lstrip())
print("Stripped string (right side):", whitespace_string.rstrip())

# 10. Replacing substrings
replaced_string = my_string.replace("Python", "Python programming language")
print("Replaced string:", replaced_string)

List

# Initialize a list
my_list = [10, 20, 30, 40, 50]

# Print the original list
print("Original List:", my_list)

# Accessing Elements
print("First element:", my_list[0])  # Accessing the first element
print("Last element:", my_list[-1])  # Accessing the last element
print("Slicing from index 1 to 3:", my_list[1:4])  # Slicing a portion of the list

# Adding Elements
my_list.append(60)  # Append an element to the end
print("After appending 60:", my_list)

my_list.insert(2, 25)  # Insert an element at index 2
print("After inserting 25 at index 2:", my_list)

# Removing Elements
my_list.remove(30)  # Remove the first occurrence of 30
print("After removing 30:", my_list)

popped_element = my_list.pop()  # Remove and return the last element
print("Popped element:", popped_element)
print("After popping the last element:", my_list)

# Modifying Elements
my_list[3] = 45  # Modify an element at index 3
print("After modifying element at index 3 to 45:", my_list)

# Other Operations
print("Length of the list:", len(my_list))  # Length of the list
my_list.sort()  # Sort the list
print("Sorted list:", my_list)

# Concatenating Lists
another_list = [70, 80, 90]
combined_list = my_list + another_list
print("Combined list:", combined_list)

Tuple

# Initialize a tuple
my_tuple = (10, 20, 30, 40, 50)

# Print the original tuple
print("Original Tuple:", my_tuple)

# Accessing Elements
print("First element:", my_tuple[0])  # Accessing the first element
print("Last element:", my_tuple[-1])  # Accessing the last element
print("Slicing from index 1 to 3:", my_tuple[1:4])  # Slicing a portion of the tuple

# Tuple unpacking
a, b, c, d, e = my_tuple
print("Unpacked elements:", a, b, c, d, e)

# Length of the tuple
print("Length of the tuple:", len(my_tuple))

# Concatenating tuples
another_tuple = (60, 70, 80)
combined_tuple = my_tuple + another_tuple
print("Combined tuple:", combined_tuple)

# Checking if an element exists in the tuple
if 30 in my_tuple:
    print("30 exists in the tuple.")
else:
    print("30 does not exist in the tuple.")

Dictionary

# Initialize a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Print the original dictionary
print("Original Dictionary:", my_dict)

# Accessing Elements
print("Name:", my_dict['name'])  # Accessing value by key
print("Age:", my_dict.get('age'))  # Accessing value using get() method

# Adding or Modifying Elements
my_dict['email'] = 'john@example.com'  # Adding a new key-value pair
print("After adding 'email':", my_dict)

my_dict['age'] = 32  # Modifying the value of an existing key
print("After modifying 'age' to 32:", my_dict)

# Removing Elements
removed_value = my_dict.pop('city')  # Removing a key-value pair by key
print("Removed value:", removed_value)
print("After removing 'city':", my_dict)

# Other Operations
print("Keys in the dictionary:", my_dict.keys())  # Get all keys
print("Values in the dictionary:", my_dict.values())  # Get all values
print("Items in the dictionary:", my_dict.items())  # Get all key-value pairs

# Length of the dictionary
print("Length of the dictionary:", len(my_dict))

# Checking if a key exists
if 'name' in my_dict:
    print("'name' exists in the dictionary.")
else:
    print("'name' does not exist in the dictionary.")

Set

# Initialize a set
my_set = {10, 20, 30, 40, 50}

# Print the original set
print("Original Set:", my_set)

# Adding Elements
my_set.add(60)  # Add a single element
print("After adding 60:", my_set)

my_set.update([70, 80, 90])  # Add multiple elements using update()
print("After updating with [70, 80, 90]:", my_set)

# Removing Elements
my_set.remove(30)  # Remove an element
print("After removing 30:", my_set)

# Discarding Elements (if exists)
my_set.discard(100)  # Discard an element (no error if element doesn't exist)
print("After discarding 100 (if exists):", my_set)

popped_element = my_set.pop()  # Remove and return an arbitrary element
print("Popped element:", popped_element)
print("After popping an element:", my_set)

# Set Operations
another_set = {40, 50, 60, 70}

# Intersection
intersection_set = my_set.intersection(another_set)
print("Intersection with another_set:", intersection_set)

# Union
union_set = my_set.union(another_set)
print("Union with another_set:", union_set)

# Difference
difference_set = my_set.difference(another_set)
print("Difference with another_set:", difference_set)

# Subset
subset_check = my_set.issubset(another_set)
print("Is my_set a subset of another_set:", subset_check)

# Superset
superset_check = my_set.issuperset(another_set)
print("Is my_set a superset of another_set:", superset_check)

# Clearing the set
my_set.clear()
print("Cleared set:", my_set)

To gain hands-on experience, follow this link.

In this post, we learned about the basics of Python, including data types and their operations. Practice and review the above concepts to have a strong understanding.
we will cover other topics in the upcoming blog

Additional links to practice:
1. geeksforgeeks
2.W3schools

Happy learning !!