Taking too long? Close loading screen.
Connect with us

Tech

I thought I had mastered Python — until I discovered these tricks

Published

on

Python is one of the most popular programming languages ​​for beginner developers, making it the most widely taught language in schools around the world.

However, learning Python is not an easy thing. To get started, you first need to find the best online way to get there, which is difficult in itself. There are thousands of Python courses and tutorials, all claiming to be the best.

True, practice alone is not perfect, but perfect practice is. This means you need to make sure you’re always following the best coding practices (commenting on your code, using correct syntax, etc.), otherwise you’ll likely end up adopting bad habits that could harm your future lines of code.

A universal convention supplies all of maintainability, clarity, consistency, and a foundation for good programming habits too. What it doesn’t do is insist that you follow it against your will. That’s Python! — Tim Peters on comp.lang.python, 2001–06–16

In this article, I’m going to give my top 10 tips to help you code in Python quickly and efficiently.

1. Readability is important

Programs must be written for people to read, and only incidentally for machines to execute.

First of all, try to make your programs easy to read by following some programming conventions. A programming convention is one that a seasoned programmer follows when writing his or her code. There’s no quicker way to reveal that you’re a “newbie” than by ignoring conventions. Some of these conventions are specific to Python; others are used by computer programmers in all languages.

Image for post

Essentially, readability is the characteristic which specifies how easy another person can understand some parts of your code (and not you!).

As an example, I was not used to write with vertical alignment and to align the function’s parameters with opening delimiter.

Look at other examples in the  and decide what looks best.

Another important thing that we do very often is resembling programs that we have seen or written before, which is why our exposure to readable programs is important in learning programming.

2. Avoid unuseful conditions

Often, a long if & elif & …. & else conditions is the sign of code that needs refactoring, these conditions make your code lengthy and really hard to interpret. Sometimes they can easily be replaced, for example, I used to do the following:

This is just dumb! The function is returning a boolean, so why even use if blocks in the first place? The correct what of doing this would be:

In a  challenge, you are given the year and you have to write a function to check if the year is leap or not. In the Gregorian calendar three criteria must be taken into account to identify leap years:

  • The year can be evenly divided by 4, is a leap year, unless:
  • The year can be evenly divided by 100, it is NOT a leap year, unless:
  • The year is also evenly divisible by 400. Then it is a leap year.

So in this challenge, forget about ifs and elses and just do the following:

3. Adequate use of Whitespace

  • Never mix tabs and spaces
  • A line break between functions
  • Two line breaks between classes
  • Add a space after “,” in dictionaries, lists, tuples, arguments in a list of arguments and after “:” in dictionaries but not before.
  • Put spaces around assignments and comparisons (except for arguments in a list)
  • No space for opening / closing parentheses or just before a list of arguments.

4. Docstrings and Comments

  • Docstrings = How to use the code
  • Comments = Why (rational) and how the code works

The docstrings explain how to use the code :

  • Explain the purpose of a function even if it seems obvious to you because it will not necessarily seem obvious to another person later.
  • Describe the expected parameters, the returned values ​​and the exceptions raised.
  • If the method is strongly coupled to a single caller, mention the calling function.

The comments explain what are for the maintainers of your code. Examples including notes for yourself, such as:

# !!! BUG: …

# !!! FIX: This is a hack

# ??? Why is this here?

It is on your responsibility to write good docstrings and good comments, so always keep them up to date! When making changes, make sure the comments and docstrings are consistent with the code.

You will find a detailed PEP dedicated for Doctsrings : 

5. Variables and Assignment

In other programming languages :

In Python, it’s better to use the assignment in one line code :

You may have already seen it but do you know how it works?

  • The comma is the syntax for building the tuple.
  • A tuple is created on the right (tuple packing).
  • A tuple is the target on the left (tuple unpacking).

Other examples:

Useful in loops on structured data (the variable user above has been kept):

It is also possible to do the opposite way, just make sure you have the same structure on the right and on the left:

6. List Concatenation & Join

Let’s start with a list of strings:

We want to concatenate these chains together to create a long one. Particularly when the number of substrings is large, avoid doing this :

It is very slow. It uses a lot of memory and performance. The sum will add up, store, and then move on to each intermediate step.

Instead, do this:

The join () method makes the entire copy in one pass. When you only process a few strings, it makes no difference. But get into the habit of building your chains optimally, because with hundreds or thousands strings, it will truly make a difference.

Here are some techniques for using the join () method. If you want a space as a separator:

or a comma and a space:

To make a grammatically correct sentence, we want commas between each value except the last one, where we prefer an “or”. The syntax for splitting a list does the rest. The [: -1] returns everything except the last value, which we can concatenate with our commas.

7. Test true conditions

It is elegant and quick to take advantage of Python with regard to Boolean values:

8. Use enumerate when it’s possible

The enumerate function takes a list and returns pairs (index, item):

It is necessary to use a list to display the results because enumerate is a lazy function, generating one item (a pair) at a time, only when requested. A for loop requires such a mechanism. Print does not take one result at a time but must be in possession of the entire message to be displayed. We therefore automatically converted the generator to a list before using print.

So, using the loop below is much better:

The version with enumerate is shorter and simpler than the two other versions. An example showing that the enumerate function returns an iterator (a generator is a kind of iterator)

The traditional way with for and if:

Using a list comprehension:

The listcomps are clear and direct. You can have several for loops and if conditions within the same listcomp, but beyond two or three, or if the conditions are complex, I suggest you use the usual for loop.

For example, the list of squares from 0 to 9:

The list of odd numbers within the previous list:

Another example:

10. Generator expressions

Let’s sum the squares of numbers less than 100:

We can also use the sum function which does the job faster for us by building the right sequence.

The generator expressions are like list comprehensions, except in their calculation, they are lazy. Listcomps calculate the entire result in a single pass, to store it in a list. Generator expressions calculate one value at a time, when necessary. This is particularly useful when the sequence is very long and the generated list is only an intermediate step and not the final result.

For example if we have to sum the squares of several billion integers, we will reach a saturation of the memory with a list comprehension, but the generator expressions will not have any problem. Well it will take a while though!

The difference in syntax is that listcomps have square brackets, while generator expressions do not. Generator expressions sometimes require parentheses, so you should always use them.

In short :

  • Use a list comprehension when the expected result is the list.
  • Use a generator expression when the list is only an intermediate result.
Image for post
Source : https://www.azquotes.com/quote/669106

In this article, I have presented some of my best tips for learning to program in Python. If you really want to become a programmer or add a coding skill to your skills, learning Python is a great place to start. Look for high quality Python training online and start to find out how to program in Python. I recommend that you learn the basics with an interactive course before moving on to more difficult concepts.

You should not speed up the learning process too much, or you may miss important information. Take notes and make sure to review them regularly and try to practice writing code as often as possible.

Connect with colleagues who are learning like you and don’t be afraid to ask questions when you have them. Helping others when they have problems can be a great review, and working with someone else’s code is a great way to learn new things.

If you do all of this, nothing can stop you! So what are you waiting for? Start programming in Python now!


This article was written by Kamal Chouhbi and originally published on Towards Data Science. You can read the piece here.

Read next: How Gen Z’s travel behaviors are changing the way we all get around for the better

Source

Continue Reading
Advertisement
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Tech

Epic’s latest argument in its fight against Apple keeps antitrust issues front and center

Published

on

Epic Games, the game engine developer and creator of the wildly popular Fortnite game, is keeping the focus squarely on antitrust issues in its lawsuit against Apple as pressures mount to rein in anti-competitive practices of the world’s largest tech companies.

Antitrust arguments are gaining ground on both sides of the political spectrum, which could present a more favorable environment for Epic to make its case.

Earlier this month the Trump Justice Department filed its antitrust case against Google even as Congress laid out its roadmap for how to limit the monopoly power of a quartet of trillion-dollar companies: Facebook, Amazon, Apple and Alphabet (the parent company behind Google).

Epic’s lawyers acknowledged in the filing that the company breached its contract with Apple, but said that it only took that step because Apple’s contract restrictions are illegal, according to the company.

“When Epic took steps to allow consumers on iOS devices to make those payments directly, it breached some of the contractual restrictions that Apple imposes on iOS developers,” the lawyers wrote. “Epic did so because those contractual restrictions are unlawful. Epic chose to take a stand against Apple’s monopoly to illustrate that competition could exist on iOS, and that consumers would welcome and benefit from it. Epic did so without advance notice to Apple because Apple would otherwise have used its monopoly control to prevent that competition from happening.”

Ultimately, the argument comes down to whether Apple can claim ownership of commerce occurring on the phones they make and through the marketplace that companies are forced to use to access the users of those phones.

“It’s a crazy, misguided view,” according to a tweet from Epic Games founder and chief executive, Tim Sweeney.

The argument that Epic is making to the court is that Apple’s contractual restrictions are anticompetitive and deny choice to developers and consumers.

From Epic’s perspective, it took the steps it did in creating an in-game marketplace that its players could access directly, to prove that the App Store is not a necessary part of the iOS ecosystem; “they are just the tools Apple uses to maintain its monopoly,” the company’s lawyers wrote.

“Apple has no right to the fruits of Epic’s labor, other than the rights arising under a contract. Consumers who choose to make in-app purchases in Fortnite pay for Epic’s creativity, innovation and effort—to enjoy an experience that Epic has designed,” the company claimed in its filing.

The legal confrontation between one of the world’s most valuable tech company and one of the tech industry’s rising (and incredibly popular) stars began in August when Epic Games introduced a new payment mechanism to its Fortnite app allowing gamers to purchase its in-game currency directly and bypass Apple’s in-app purchase framework.

The company pushed the same update to its Android game, as well. Both Apple and Alphabet responded by taking down the company’s Fortnite game from its app stores.

Earlier this month, Judge Yvonne Gonzales Rogers, kept a temporary restraining order issued in September in place which simultaneously protected Epic’s Unreal Engine from retaliation by Apple, while allowing Apple to keep Epic’s Fortnite game off of its App Store.

Source

Continue Reading

Tech

Tencent leads $100M Series B funding round into China-based esport provider VSPN

Published

on

Further confirmation that the esports market is booming amid the pandemic comes today with the news that esports ‘total solutions provider’ VSPN (Versus Programming Network) has raised what it describes as ‘close to’ $100 million in a Series B funding round, led by Tencent Holdings . Other investors that participated in the round include Tiantu Capital, SIG (Susquehanna International Group), and Kuaishou. The funding round will go towards improving esports products and its ecosystem in China and across Asia.

Founded in 2016 and headquartered in Shanghai, VSPN was one of the early pioneers in esports tournament organization and content creation out of Asia. It has since expanded into other businesses including offline venue operation.

In a statement, Dino Ying, CEO of VSPN (see also our exclusive interview) said: “We are delighted to announce this latest round of funding. Thanks to policies supporting Shanghai as the global center for esports, and with Beijing, Chengdu, and Xi’an expressing confidence in the development of esports, VSPN has grown rapidly in recent years. After this funding round, we look forward to building an esports research institute, an esports culture park, and further expanding globally. VSPN has a long-term vision and is dedicated to the sustainable development of the global esports ecosystem.”

Dino Ying, VSPN CEO

Dino Ying, VSPN CEO

Mars Hou, general manager of Tencent Esports, commented: “VSPN’s long-term company vision and leading position in esports production are vital for Tencent to optimize the layout of the esports industry’s development.”

We had a hint that Tencent might invest in VSPN when, in March this year, Mark Ren, COO of Tencent Holdings, made a public statement that Tencent would provide more high-quality esports competitions in conjunction with tournament organizers like VSPN.

As we observed in August, Tencent, already the world’s biggest games publisher, that it would consolidate Douyu and Huya, the previously competing live-streaming sites focused on video games.

In other words, Tencent’s investment into VSPN shows it is once again doubling-down on the esports market.

This Series B funding round comes four years after VSPN’s 2016 Series A funding round, which was led by Focus Media Network, joined by China Jianteng Sports Industry Fund, Guangdian Capital, and Averest Capital.

Now, VSPN has become the principal tournament organizer and broadcaster for PUBG MOBILE international competitions, and China’s top competitions for Honor of Kings, PUBG, Peacekeeper Elite, CrossFire, FIFA, QQ Speed, and Clash Royale. This will tally-up 12,000 hours of original content. The company has partnered with over 70% of China’s esports tournaments.

In March, another huge esports player, ESL, joined forces with Tencent to become a part of the PUBG Mobile esports circuit for 2020.

In addition to its core esports tournament and content production business, VSPN has branded esports venues in Chengdu, Xi’an, and Shanghai. In May, VSPN launched its first overseas venue, V. SPACE in Seoul, South Korea.

And even offline events are coming back. VSPN hosted the first large-scale esport event with offline audiences in August this year. And the LOL S10 event will open 6,000 tickets. However, all tournaments will operate under strict COVID-19 prevention measures and approval processes by the Chinese government, and not all esports events are allowing offline audiences. In the main, only high-level ones are approved.

VSPN said it will continue to focus on building an esports short-form video ecosystem, improving the quality of esports content creation, and reaching more users via different channels. VSPN currently houses more than 1,000 employees in five business divisions.

Source

Continue Reading

Tech

Esports pioneer Dino Ying talks to TechCrunch about the next phase of VSPN

Published

on

Following the news that China’s esport giant VSPN (Versus Programming Network) has raised close to $100 million in a Series B funding round, led by Tencent Holdings, TechCrunch interviewed founder and CEO Dino Ying via email about his strategy for the company.

Founded in 2016 and headquartered in Shanghai, VSPN was one of the early pioneer in esports tournament organization and content creation out of Asia. It has since expanded into other businesses including offline venue operation.

VSPN began hosting the first large-scale esport event with offline audiences in August, although tournaments now operate under strict COVID-19 prevention measures.

TechCrunch: VSPN has a large content production ecosystem surrounding its esports activity. Can you expand on the detail behind your stated short-form video strategy? Will this involve TikTok?

Ying: VSPN intends to use our world-class video production capabilities and industry insights to create different forms of content. We will give our existing fans and a wider audience a new and vivid esports experience. Kuaishou, as our investors and a strategic partner, will support in all ways as a media platform to help our content reach more users. Short-form video is an important part of our future strategy and we look forward to working with platforms all over the world in this regard.

TC: What is VSPN’s share of the eSports market?

Ying: There is no official estimation of the size of the esports market but VSPN is far the largest esports organization in China, with over 1000+ employees and covering every major esports tournament you’ve ever heard of. By many measures, we are the largest esports organization in the world and will continue to expand.

TC: Why do you think Shanghai has become a center for esports?

Ying: As the biggest and perhaps most international city in China, it has a vibrant and increasingly sophisticated economy. Tech innovation and new industries are actively encouraged to grow here.

The Shanghai government has implemented supportive measures and policies to encourage the growth of esports both domestically and internationally. Thanks to these measures Shanghai has become an international hub for the biggest and best tournaments in the world

VSPN events have returned, despite COVID-19

VSPN events have returned, despite COVID-19

TC: How important is research into eSports for VSPN and why?

Ying: It is vital for VSPN. As an esports total solutions provider aiming to build a sustainable global esports ecosystem, data and R&D allows us to give our fans a richer experience. The research center will allow us to continually improve as a company and develop the industry.

TC: You are the cofounder and chairman and CEO by title. What is the role of cofounder Ethan Teng?

Ying: Ethan Teng is Co-founder and president of VSPN. Ethan as one of the most important partners of VSPN, with his dedicated esports industry experience, he plays a vital role in leading and managing the company’s strategic goal setting and day to day management.

TC: What is the nature of the strategic relationship with Tencent?

Ying: VSPN is a key partner of Tencent in the esports industry. With Tencent’s support, VSPN has built a leading position in esports tournament content production. Since the emergence of esports in China, our deep-rooted industry expertise has helped further develop the esports ecosystem to grow and mature. Alongside Tencent we will continue to generate new opportunities within the industry.

TC: What made you choose these partners and why? What was the strategic thinking behind these decisions?

Ying: Together with Kuaishou, VSPN aims to establish an esports short-form video ecosystem to diversify existing content, and to build the connections between top quality creators and channels. With an extensive portfolio in the consumer and TMT sectors, both Tiantu Capital and SIG will utilize their industry insights and expertise to aid VSPN’s strategic development. With our investors, we will empower esports to be the new sports for the next generation.

TC: In addition to the core esports tournament and content production business, VSPN has branded esports venues. How important are these other businesses – like the venues – to the core offering of VSPN? What sort of growth do you expect in the next few years?

Ying: Regardless of business lines, VSPN’s core mission is to provide the best eSports experiences for our fans. And these experiences include not just online viewing experiences, but also offline ones where fans physically attend. We see our offline business as a natural way to extend our services to our fans; it is an important supplement to our overall offerings. We expect to grow it per our fans’ and partner’s demands.

TC: Mobile esports, especially the KPL and PUBG MOBILE (or Peacekeeper Elite in China), have attracted more and more female audiences. What is the future of eSports among women / girls?
Ying: Mobile gaming has really helped extend eSports’ reach to female participants and audiences. Rightfully so, we see a future of eSports where female participants take a more prominent role than they have done. Not just on stage as athletes, but also off stage as fans and more importantly backstage as top quality producers and decision-makers in the industry. The impact of having more female fans, athletes and professionals is exciting and will be hugely beneficial to the wider industry.

TC: What is the future of esports in Augmented Reality?

Ying: We think eSports in its full form will look and feel a lot different from what we’ve seen so far in sports and entertainment. The possibility of integrating real world gaming and virtual competitions is fascinating. VSPN is only beginning to test the boundaries of new technologies such as AR, VR. The emergence of these technologies will help us create fresher experiences, and the possibilities are endless.

VSPN headquarters

VSPN headquarters

TC: Please tell us more about your personal history?

Ying: Firstly, thank you for having me – it is a real pleasure to speak to TechCrunch and be able to announce our fundraise to the world. I have been working in the gaming and esports industry all my life and I’m excited about the future. With the team at VSPN we are proud to be pioneers in the esports industry.

I live between Beijing and Shanghai, but I spend a lot of my time travelling to other Chinese cities like Xi’an, Chengdu, Guangzhou and Shenzhen where we have esports arenas and business interests. Usually I travel internationally to some of our overseas operations and competitions, so I look forward to that when travel becomes easier.

I am a fan of traditional sports too and an avid football fan. I follow some of the European leagues – whenever I can, I go to matches to enjoy the atmosphere; I went to Stamford Bridge early this year and loved it, but seeing the AC vs Inter Derby live is hard to beat…

TC: Why did you get into this business and how?

Ying: Mostly because I am a HUGE gaming fan! I’ve been playing computer games since I was a teenager and enjoy playing all types. Earlier this year I played COD Warzone as soon as it came out and often play PUBG Mobile; I’m extremely lucky to be in an industry which I’ve loved since I was very young. It’s a great way to connect with friends and I am proud to have worked in game development and publishing for my whole career. 5 years ago, esports seemed like the obvious next step because of the competitive element. We saw the beginnings of a trend and founded VSPN with a world-class team to make that potential a reality.

VSPN is very proud to be leading the world in a relatively new industry. We think esports will continue to grow exponentially and will be an incredibly important part of the entertainment industry in years to come. To lead a Chinese company with a global future is really exciting.

TC: What motivates you as a businessman?

Ying: Bringing new forms of entertainment to millions of people around the world and building a global business.

TC: Who inspires you most in the business world?

There are so many fantastic businessmen in China who are doing some really innovative things at the moment. For example, the live-streaming industry has become enormous in 2020 due to the pandemic and has offered entrepreneurs a new way to sell products and engage with new audiences.

If I had to name one it would be Mark Ren (COO at Tencent Holdings) – he is an exceptional businessman. The way he has helped create sustainable ecosystems in the entertainment space and captured trends is something every businessman should aspire to. This is something VSPN works hard at and we are very proud to be such close partners of Tencent.

TC: What is your opinion of Silicon Valley?

Ying: It’s an amazing place and has shown the world how technology can improve lives all over the world. For many years it has led the world as a centre for creativity and innovation and continues to be an inspiration to entrepreneurs around the world. In China, we have lots of Silicon Valleys!

TC: Is there anything else you’d like to say to TechCrunch readers?

Ying: This has been a challenging year for many businesses and the esports industry has had to adapt, but I think the world has seen how big esports is and how it can bring communities and cultures together. As the industry grows there will bigger and bigger online and offline tournaments across the world, especially with 5G and mobile gaming becoming even more popular. We look forward to being at the forefront of esports for competitors all over the world and hopefully some of your readers will enjoy watching our original content and tournaments.

Finally, with celebrities and big brands seeing live streaming and casual gaming as a new way to engage with a wider audience, the future for VSPN is very, very bright.

Source

Continue Reading

Trending