Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 24, 2020 01:26 pm GMT

3 Tricks every Python programmer needs to know

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 enter3  # hit enter again# output15

Ugh.

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

# inputhello world # enter (in one single line)# outputworld 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

# inputhello darkness my old friend # hit enter# outputfriend old my darkness hello# inputjust three strings # hit enter# outputstrings 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 intfirst_int, second_int = [int(a) for a in input().split()]print(first_int + second_int)# Or convert to floatfirst_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

# input1 2# output3# input2 3 3 4# output12

We read a list of integers and sum them up afterwards

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

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 13 1 2 3     # input 24 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()]list_of_ints.pop(0)

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 pathsome_file = open('/home/gabriel/test_file.txt', 'w')# Open test_file.txt for reading (r) using a relative pathsome_other_file = open('test_file.txt', 'r')# Copy the content from some_other_file to some_filecontent = some_other_file.read()some_file.write(content)# Close filessome_file.close()some_other_file.close()

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 = some_other_file.read()    some_file.write(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.


Original Link: https://dev.to/gmelodie/3-tricks-every-python-programmer-needs-to-know-n9c

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To