Change your way to put logic in your code – Python
Last Updated :
28 May, 2020
Aren’t you bored coding in the same traditional logic over these years. It’s time to bring some differences. Well, be it any programming language. When we are asked to do some sort of basic programming exercises like sorting, searching, prime number checking, etc. we are all driven towards the same boat, which is the same coding logic. Now, we are in the past 2020, so let’s also take an initiative to change our thinking styles when it comes to coding. It is because, only if we think differently, we can code differently.
Lets dive deep into those wonderful coding tips.
Check whether a given number is Odd or Even
Of course, what a simple question. We can easily check for even or odd using the modulus operator. You want to know how? Just see the below Python code snippet –
Python3
a = 4
if(a % 2 == 0):
print("even")
else:
print("odd")
|
Output:
even
Here, the modulus operation is used to determine the remainder obtained. All even numbers are divisible by 2. That means, upon dividing an even number say 4 with 2, we will obtain the remainder as 0. So applying modulus operation between the two numbers will leave the answer as 0. This basic principle is always applied to programming whenever we are asked to check for odd and even numbers.
Can you think it differently? We all have taught our brains the logic that dividing a number by 2 determines whether it’s odd or even. And that line of code is followed traditionally by all those who code. So let’s start excavating an evergreen, but the unused method .
Python3
a = 4
if(a & 1):
print("odd")
else:
print("even")
|
Output:
even
This was done using bitwise AND operation. Cool enough!
Bitwise operators are operating on integers bit by bit. This is done by converting the integers into binary and then performing logical AND operation on each of the corresponding bits.
Note: For more information, refer to Python Bitwise Operators
Checking whether a given number is prime or not?
Those numbers which are divisible by 1 and that number only are called prime numbers. Examples for prime numbers are 2, 3, 5, 7, etc. which do not have any other factors(excluding themselves and 1). We all have been taught about the below logic for checking the prime numbers.
Python3
a = 10
if a>1:
for i in range(2, (a//2)+1):
if a % i == 0:
print(a, "is not prime ")
break
else:
print(a, "is prime ")
else:
print(a, "is not prime ")
|
Output:
10 is not prime
But we can optimize it even more. And it will look like:
Python3
a = 10
i = 2
if a>1:
while(i * i<a):
if a % i == 0:
print(a, "is not prime ")
break
else:
print(a, "is prime ")
i += 1
else:
print(a, "is not prime ")
|
Output:
10 is not prime
Both the codes are correct and output the same result. But the second code is more optimized because to check for factors, it is sufficient to loop till the square root of the given number instead of checking until its half.
In the above code, we are checking for the factors of a given number. And after each iteration, we have to increment the value of the loop variable ‘i’. It functions till i^2 less than the given number.
Multiply a given number k by 2^k and display the output
This can be coded easily in any language by basic mathematical steps. So the steps are:
- Assign a value, say 5 to a variable ‘k’
- Then, we have to store the value of 2^5 in another variable j.
- Multiply the contents of both k and j.
- Display the output .(Here 160 will be the resultant output)
This can be coded in a few lines and the code is as follows:
Python3
k = 5
j = 2**k
p = k * j
print(p)
|
Output:
160
But there is another method which is much simpler and efficient. That is by using shift-operator. Left shift operation on the variable k, k times will result in the same function as displayed above. So the optimized code will become:
Output:
160
Both these will result in the same output.
Divide a given number by 2^k and display the output
The dividing function also works similar to the multiply function. Only the operator changes. So the steps for dividing a number by 2^k are listed below:
- Assign a value, say 5 to a variable ‘k’
- Then, we have to store the value of 2^5 in another variable j.
- Divide the contents of both k and j.
- Display the output .(Here 160 will be the resultant output)
The Python 3 code for basic division is as follows:
Python3
k = 5
j = 2**k
p = k//j
print(p)
|
Output:
0
We can use ‘//’ for integer division and ‘/’ for floor division as per our requirement.And the optimized code using right shift operation will look like :
Output:
0
Both the codes will result in the output ‘0’(integer division).
Note: For more information, refer to Python Bitwise Operators.
All these operations already existed since history. But we forgot to practice using them. For our changing future, let’s adopt these small changes and become a part of it.
Similar Reads
Change your way to put logic in your code - Python
Aren't you bored coding in the same traditional logic over these years. It's time to bring some differences. Well, be it any programming language. When we are asked to do some sort of basic programming exercises like sorting, searching, prime number checking, etc. we are all driven towards the same
5 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and goin
3 min read
Must Know Things to Clear Your Python Coding Interview
Python is not only one of the most loved languages but rather it is used in various different domains. Due to its high dependency and usage in a lot of fields, there has suddenly been an increase in the job openings in Python programming language and related frameworks. Python developers are in high
6 min read
How to Change Values in a String in Python
The task of changing values in a string in Python involves modifying specific parts of the string based on certain conditions. Since strings in Python are immutable, any modification requires creating a new string with the desired changes. For example, if we have a string like "Hello, World!", we mi
2 min read
How to Take a Tuple as an Input in Python?
Tuples are immutable data structures in Python making them ideal for storing fixed collections of items. In many situations, you may need to take a tuple as input from the user. Let's explore different methods to input tuples in Python. The simplest way to take a tuple as input is by using the split
3 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks
2 min read
Best Practices to Write Clean Python Code
Python is one of the most loved programming languages today. Shockingly, Python has overtaken Java in the list of top programming languages and is now the most studied language! It is the second most used language after JavaScript and is slowly beating the competition to be on the top. It is used ex
6 min read
Check for True or False in Python
Python has built-in data types True and False. These boolean values are used to represent truth and false in logical operations, conditional statements, and expressions. In this article, we will see how we can check the value of an expression in Python. Common Ways to Check for True or FalsePython p
2 min read
Customize your Python class with Magic or Dunder methods
The magic methods ensure a consistent data model that retains the inherited feature of the built-in class while providing customized class behavior. These methods can enrich the class design and can enhance the readability of the language. So, in this article, we will see how to make use of the magi
13 min read
10 Tips to Maximize Your Python Code Performance in 2024
Python is a powerful programming language that has been gaining popularity in recent years. It's known for its versatility and ease of use, making it a great choice for beginners and experienced programmers alike. However, with so many resources available on the internet, it can be difficult to know
15+ min read