DEV Community

Cover image for 3 Tricks every Python programmer needs to know

3 Tricks every Python programmer needs to know

gmelodie profile image Gabriel Cruz (he/him) ・3 min read

If you've never touched Python before or if you're just getting started, this post if for you. These are the things I simply can't live without being a Python programmer.

1 - Using Python 3

Don't use Python 2. Use Python 3.

There's no secret here. Just don't use Python 2.

Really, don't use it. Use Python 3.

Got it? Use Python 3.

No Python 2. Ever.

2 - Reading inputs

So you're learning Python. What's the first thing that you learn?

Hello World, okay.

But what's the second thing you learn? To me it's always summing up two integers. How do you do that in Python? Well, most people do something like this

first_int = int(input())
second_int = int(input())
print(first_int + second_int)

For that code, the input would look like so

12 # hit enter
3  # hit enter again
# output


Reading two strings in the same line

Forget about the last example for a bit. Let's say you want to do a code that gets two strings in one line and invert them like

# input
hello world # enter (in one single line)

# output
world hello

You could use split

first_string, second_string = input().split()
print(second_string, first_string) # out: 'world hello'

Obs: split can also receive the delimiter characters as arguments. Let's say your strings are divided by a comma and a space like

hello, there

To split those you could use

first_string, second_string = input().split(', ')
print(second_string, ', ', first_string) # out: 'world, hello'

Mind the space on the split argument: split(', '), not split(',')

Variable length inputs

In the last example we knew we were going to receive two strings as input. But what about when we don't know how many strings are there beforehand?

Let's say we want to make our code invert the order of all strings passed in the input, no matter how many are there

# input
hello darkness my old friend # hit enter
# output
friend old my darkness hello

# input
just three strings # hit enter
# output
strings three just

You can use list comprehensions

all_strings = [string for string in input().split()]
print(all_strings[::-1]) # all_strings[::-1] inverts the list

Going back to our first example (adding two integers), wouldn't it be better if we could pass in the two numbers in the same line?

If you need to read numbers instead of strings, you can use type casting

# Mind the int(a) converting each string to int
first_int, second_int = [int(a) for a in input().split()]
print(first_int + second_int)

# Or convert to float
first_float, second_float = [float(a) for a in input().split()]
print(first_float + second_float)

Now what if we wanted to sum up as many numbers as come in the input? Like so

# input
1 2
# output

# input
2 3 3 4
# output

We read a list of integers and sum them up afterwards

# Mind the int(a) converting each string to int
list_of_ints = [int(a) for a in input().split()]

This may also be useful in competitive programming or algorithm exercises when you have an input like <number N> [list of N numbers]

2 9 8       # input 1
3 1 2 3     # input 2
4 8 9 8 7   # input 3

As in Python you don't need to know the length of a list beforehand (you could just use len(my_list)), you can discard the first number of the list using slices

list_of_ints = [int(a) for a in input().split()][1:]

Or even pop

list_of_ints = [int(a) for a in input().split()]

3 - Files

If you're familiar with the C API for handling files, Python will seem very similar, but with all the features you always wanted in C.

First: opening, reading, writing, closing

# Open test_file.txt for writing (w) using an absolute path
some_file = open('/home/gabriel/test_file.txt', 'w')

# Open test_file.txt for reading (r) using a relative path
some_other_file = open('test_file.txt', 'r')

# Copy the content from some_other_file to some_file
content =

# Close files

Mind that, even though they seem like the same file, some_other_file may not the same as some_file because it's specified by a relative path instead of an absolute one

A better way of doing the above, however, is to use context managers, more specifically a with statement

with open('/home/gabriel/test_file.txt', 'w') as some_file, \      
     open('test_file.txt', 'r') as some_other_file:

    # Copy the content from some_other_file to some_file
    content =

With that, you don't need to remind yourself of closing the file, the context manager does that for you when the with statement finishes.


Editor guide
lizard profile image

Also something I see people ignore sometimes is the enumerate function. It can turn

i = 0
for foo in foos:
    print(f"{i} : {foo}")
    i += 1
Enter fullscreen mode Exit fullscreen mode

into this

for i, foo in enumerate(foos):
    print(f"{i} : {foo}")
Enter fullscreen mode Exit fullscreen mode

It's a bit more elegant.

svemaraju profile image

Ah neat, I didn't know about the last one, where you can have multiple files open within the same "with" block. Interesting post.