Python Tips – Assignments
The First Tip is —
Always watch out for assignment and related operations. Like what you are planning to do or desired functionality and what you’re coding in real.
Didn’t get what am trying to say ??
Don’t worry, let me explain this using an example.
Suppose we wanna reverse a string without using any in-built attribute or we can say method.
This may sound simple but still able to give you goose bumps if you’re not aware of what you are writing.
Python Snippet | Wrong
Here’s our python snippet for the desired functionality.
# Function Definition def reverse_str (inp_str): out_str = " " # Calling Every Element for char in inp_str: out_str = (out_str + char) # Result return (out_str)
reverse_str ('I Love Python!')
Now, can you guess the output??
Take your shot before looking at the result.
Well, it will just return– ‘I Love Python! ‘.
Didn’t get why? Let me Explain.
It is because inside our for loop, we made a silly mistake and it is–
out_str = (out_str + char)
Python as well as in any other programming language statement is always interpreted by RIGHT ⇐ LEFT. That’s why it will just read every character from our input string and push it to the empty string as declared by us.
Python Snippet | Correct
I hope now you guys have the theme of this tip. So let’s take a look at the solution. The code for this functionality will be like that–
# Function Definition def reverse_str (inp_str): out_str = " " # Calling Every Element for char in inp_str: out_str = (char + out_str ) # Result return (out_str)
Now, you can give this snippet and trust me it will reverse it for sure.
and you will get — ‘!nohtyP evoL I ‘
I hope this tiny tip will be helpful to you guys.
Keep visiting for more Python Tips. Plus, update us if you have any tip, share it with us and with others. 💡 💡