Category: python

Should I Use Elif In Python?

When working on complex projects, you may encounter a situation where you need to make decisions based on multiple conditions. That’s one of the first things I got to know as a new QA engineer who later became a Python developer.

This is where the elif statement in Python comes in.

In this article, we’ll explore what the elif statement is, how it works, and when to use it in your code.

I’m going to answer the “Should I Use Elif In Python?” question based on my experience.

Continue reading

How Do I Store Python Logs In A File?

In many Python programming situations, at some point, as your application grows you want to start storing logs in a file. Since the very early days ( about my Python experience here ) that was the case for me. In this post, I’ll share my ideas for the “How Do I Store Python Logs In A File?” question.

How Do I Store Python Logs In A File?

One way to store these Python logs in a file so you can look at them later is to write them to a file using a built-in logging module. 

Here’s an example of how to use the logging module to store logs in a file in Python:

import logging

# Configure the logging module to use a file
logging.basicConfig(filename='example.log', level=logging.DEBUG)

# Write some log messages
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

In this example, the basicConfig() function is used to configure the logging module to write logs to a file named ‘example.log’.

The level argument is set to logging.DEBUG which means that all log messages, including debug, info, warning, error, and critical messages, will be written to the file.

Then the code uses different logging levels debug(), info(), warning(), error() and critical() to write different log messages.

When you run this code, it will create a new file called ‘example.log’ in the same directory as your script, and the log messages will be written to it.

Obviously, this is a very simplified version of logging in Python, I’ll get into more details and other examples in the following sections of this post.

Continue reading

What Is Python Programming In Short?

The first time you hear about Python Programming you kind of want to explore and understand the capabilities of the language. This is exactly what happened to me when one of my university professors told me about Python and I was just a QA engineer at that time. The first question that came to my mind was: “What Is Python Programming In Short?”. Let me explain…

What Is Python Programming In Short?

As a Python developer who has been using Python for several years now, I can confidently say that it is an incredibly powerful and versatile programming language.

Python is a high-level, interpreted language, which means that it is easy to read and write, and you don’t need to worry about low-level details like memory management and compiling code.

Python is great for beginners who never coded anything before.

I used to be one years ago and all I wanted to do was to just start building a script or a small project, just to start understanding programming from a practical standpoint, not just in theory.

Continue reading

What Is The Order To Learn Python?

Years ago, when I first got into learning Python (while I was still a QA engineer) I wasn’t sure about the order in which I should learn Python. So, what is the order to learn Python? Let’s look into the most common topics and questions people ask when it comes to learning Python properly.

What Is The Order To Learn Python?

As a Python developer with 7+ years of experience, I can say that it’s important for you as a beginner to learn Python in a specific order.

Start with the basic concepts of programming, such as the following:

  • Variables
  • Data types
  • Loops
  • Control structures

These will give you a solid foundation and understanding of fundamentals. From there, you can move on to:

  • Learning the syntax of Python
  • How to write and run programs
  • How to define and call functions
  • How to work with modules.
Continue reading

How Do I Search For A Pattern In Python?

A couple of years back when I was still a QA engineer (not a Python developer yet) I got myself into dozens of situations where I had to figure out how do I search for a pattern in Python.. A pattern in strings, a pattern in files, etc. Let’s look into possible solutions in this post.

How Do I Search For A Pattern In Python?

To search for a pattern in a string in Python, you can use the re module, which stands for regular expression. Regular expressions are a way to describe patterns in strings, and the re module provides several functions to work with them in Python.

Suppose you have a list of emails, and you want to extract the username and domain name from each email address.

The emails look like this:

jane.doe@example.com
john.smith@gmail.com

You can use the re module and regular expressions to extract the username and domain name from the email addresses like this:

import re

email = 'jane.doe@example.com'

# Extract the username and domain name using a regular expression
pattern = r'(.+)@(.+)'
match = re.search(pattern, email)

username = match.group(1)
domain = match.group(2)

print(f'Username: {username}')  # Output: 'Username: jane.doe'
print(f'Domain: {domain}')  # Output: 'Domain: example.com'

In this example, we used the re.search() function to find the first occurrence of the pattern in the email address, and then used the group() method to extract the matching substrings.

The regular expression itself uses several special characters to specify the pattern:

  • . matches any single character (except a newline)
  • + matches one or more occurrences of the preceding character
  • ( ) define a capturing group, which allows us to extract the matching substrings using the group() method
Continue reading

How Do You Repeat Code In Python?

One of my first tasks as a new QA engineer / Python dev back in the day was to figure out how do you repeat code in Python, how to iterate from 0 to 10 in Python or how do I repeat code in Python forever. Let’s look into possible solutions in this post.

How Do You Repeat Code In Python?

There are a few ways to repeat code in Python, but for loops are a very common way to repeat code in Python, especially when you need to iterate over a sequence of items (such as a list, tuple, or string).

They are easy to use and can be more efficient than using a while loop, especially when you know exactly how many times you need to repeat the code.

To repeat a block of code a specific number of times use:

# Repeat 5 times
for index in range(5):
    print(f'iteration index: {index}')
Continue reading

How Do I Open A Log File In Python?

In my early days as a QA engineer / Python developer, I was working on test-related projects a lot. For such projects, the focus is on logging and the question: “How do I open a log file in Python?” comes up on a daily basis. Let’s look into possible solutions in this post.

How Do I Open A Log File In Python?

In Python, you can use the open() function to open a log file.

This function needs to know the file path and the mode (like ‘read’ or ‘write’) that you want to use.

In Python, the r mode is used to open a file in read mode.

with open('log.txt', 'r') as log_file:
    content = log_file.read()

print('content: ', content)

This means that when you open a file with this mode, you can read the data from the file, but you cannot write to it.

Continue reading

What Is dict() In Python? (5 Examples)

Back when I used to work as a QA engineer and when I first got into Python (around 7 years ago), one of the key concepts I learned to use was dict() in Python. You might wonder what is dict()in Python and what are the main features of a dictionary in Python? Let’s discuss the answer to these questions in great detail below. 

What Is dict() In Python?

In Python, the dict() function is used to create a dictionary.

A dictionary is a collection of key-value pairs, where each key is associated with a value.

This function takes in a sequence of items and returns a dictionary with the items in the sequence as keys and values.

For example, you could use the dict() function to create a dictionary like this:

my_dict = dict(
    [
        ('key1', 'value1'),
        ('key2', 'value2')
    ]
)
Continue reading

How Do You Change A Specific Line In A Text File In Python?

I used to be a QA engineer and when I first got into Python, one of the first questions that came to my mind while working on Python scripts was: “How Do You Change A Specific Line In A Text File In Python?” We will discuss the answer to this question in much detail below. 

How Do You Change A Specific Line In A Text File In Python?

To change a specific line in a text file in Python, you can use the replace() method on strings, which allows you to specify the text you want to replace and the text you want to replace it with.

Here is a quick example:

# Open the file in read mode
with open('your_text_file_path.txt', 'r') as f:
    # Read the contents of the file into a list of lines
    lines = f.readlines()

# Use for loop to go through each line in a "your_text_file_path.txt"
for line_index, line in enumerate(lines):

    # Check each line for "old_text" and replace it
    # with "new_text" if it is found
    lines[line_index] = (
        lines[line_index]
        .replace('old_text', 'new_text')
    )

# Open a new file in writing mode (this will create a new file)
with open('your_new_text_file_path.txt', 'w') as f:
    # Write the modified lines to the new "your_new_text_file_path.txt"
    f.writelines(lines)
Continue reading

Can You Parse A String In Python?

If you’re an engineer (I used to be a QA engineer) you’ll have to extract information from a string and it’s likely you’re going to use Python for it. So, can you parse a string in Python? We will discuss the answer to this question in much detail below. 

Can You Parse A String In Python?

Yes, you can parse a string in Python. Parsing a string in Python is a common task that is performed when working with data. It involves taking a string and breaking it down into smaller pieces, or tokens so that it can be more easily manipulated and processed.

Python has a number of built-in functions and methods that can be used to build your own Python parser script. 

Continue reading