

This way, even if an exception is raised within the with block, the file will be closed again.Ĭode faster with these quick tips. You can save a line and the potential to introduce bugs by using with open: > with open('file.txt') as f: > for line in f: > print line The traditional way of opening files implies that you need to close them again: > newfile = open("file.txt") > data = newfile.read() > print(data) > newfile.close() Keep them in mind! Automate opening and closing files These are quick and easy ways to access variables without too much fuss. Like so: > "Happy > myfriendsfunction(**friendanne) Name: Anne Age: 26 Profession: Senior Developer That’s why Python introduced str.format() from version 2.6 on.Įssentially, the %s symbols are replaced by curly braces. This is all well and good, but it gets messy when you’re dealing with a lot of strings at a time. Welcome to Python!" % (day, name) 'Happy Tuesday, Monty. Like this: > name = "Monty" > day = "Tuesday" > "Happy %s, %s. All you need to do is mark the places where you’d like to insert your string with %s, and then reference these strings after the statement. The good old %s-method is fine when you’re dealing with short expressions. In Python, there are three ways of formatting strings: the original %s-method, the str.format(), and, since Python 3.6, f-strings. Using more efficient functions and structures Avoid string hiccups with f-stringsįrom processing input to printing messages on the screen, strings are a vital part of any programming language. To really make your code shine, however, you’ll also need to adopt long-term habits like keeping your code as simple as possible and being consistent with your style.

There are a few quick fixes, like efficient functions and handy automations. Like with everything in life, there is no silver bullet to boost your code to stellar-performance. It’s also about readability and maintainability. Therefore, good code isn’t only about speed and efficiency. In this context, it makes perfect sense to up your game a little bit.ĭevelopers don’t code one thing and then leave it untouched for years to come.

Whether you’re a beginner or a seasoned engineer, you’re probably dealing with Python on a regular basis. And even though newer languages like Rust, Go, and Julia are gaining traction, Python’s reign will likely carry on over the next few years. Its versatility, beginner-friendliness, and huge community are just a few factors that have contributed to its tremendous growth over the last few years. Photo by David Clode on Unsplashĭespite its downsides, Python remains the king of today’s programming world.
