The Python Programming Tricks for Beginners

The Python Programming Tricks for Beginners

In this article, I will introduce 5 useful Python tips for beginners. Whether you choose just a Python programming book or you've been through one or two projects, some or all of these tips may be helpful for your future projects.

Python is an object-oriented, high-level programming language with integrated dynamic semantics primarily for web and app development. It is extremely attractive in the field of Rapid Application Development because it offers dynamic typing and dynamic binding options.

Python is relatively simple, so it's easy to learn since it requires a unique syntax that focuses on readability. Developers can read and translate Python code much easier than other languages. In turn, this reduces the cost of program maintenance and development because it allows teams to work collaboratively without significant language and experience barriers.

In this article, I will introduce 5 useful Python tips for beginners. Whether you choose just a Python programming book or you've been through one or two projects, some or all of these tips may be helpful for your future projects.

Trick #1: Nested Lists Combination

itertools is probably one of my favorite Python library. Imagine your code had a dozen of lists and after some manipulation, you ended up with a deeply nested list. itertools is exactly what you need to resolve this syntactical mess.

>>> import itertools
>>> flatten = lambda x: list(itertools.chain.from_iterable(x))
>>> s = [['"', 'An', 'investment'], ['in'], ['knowledge'], ['pays'], ['the', 'best'], ['interest."', '--'], ['Benjamin'], ['Franklin']]
>>> print(' '.join(flatten(s)))
" An investment in knowledge pays the best interest." -- Benjamin Franklin

As you can see from the example above, we can combine nested lists and strings using .join() and itertools . .combinations() method in itertools is also a powerful tool to return the length subsequences of elements from the input iterable. ` .

Trick #2: Powerful One-Liners

Are you tired of reading through lines of code and getting lost in conditional statements? Python one-liners might just be what you are looking for. For example, the conditional statements

>>> if alpha > 7:
>>>    beta = 999
>>> elif alpha == 7:
>>>    beta = 99
>>> else:
>>>    beta = 0

can really be simplified to:

>>> beta = 999 if alpha > 7 else 99 if alpha == 7 else 0

This is ridiculous! Should you pay more attention to the code you wrote, you’d always find places where you can simplify as one-liners. Besides conditional statements, for loops can also be simplified too. For example, doubling a list of integer in four lines

>>> lst = [1, 3, 5]
>>> doubled = [] 
>>> for num in lst:
>>>    doubled.append(num*2)

can be simplified to just one line:

>>> doubled = [num * 2 for num in lst]


Of course, it might get a bit messy if you chain everything into one-liners. Make sure you aren’t overusing one-liners in your code, as one might argue that the extensive use of one-liners is “un-Pythonic”.

>>> import pprint; pprint.pprint(zip(('Byte', 'KByte', 'MByte', 'GByte', 'TByte'), (1 << 10*i for i in xrange(5))))


Trick #3: Simple Data Structures

Going back to Trick #2, it is also very easy to use one-liner to initialize data structures in Python. Harold Cooper has implemented a one-liner tree structure using the following code:

>>> def tree(): return defaultdict(tree)


The code shown above simply defines a tree that is a dictionary whose default values are trees. Other one-liner functions such as prime number generator

>>> reduce( (lambda r,x: r-set(range(x**2,N,x)) if (x in r) else r), 
        range(2,N), set(range(2,N)))

can be found all over Github and Stack Overflow. Python also has powerful libraries such as Collections , which will help you to solve a variety of real-life problems without writing lengthy code.

>>> from collections import Counter
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print(Counter(myList))
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})


Trick #4: Quick String Manipulations

String manipulations can be tricky , but Python has hidden shorthands to make your life significantly easier. To reverse a string, we simply add ::-1 as list indices

>>> a =  "ilovepython" 
>>> print a[::-1] 
nohtypevoli

The same trick can be applied to a list of integers as well. String manipulation is extremely easy in Python. For example, if you want to output a sentence using the following predefined variables str1 , str2 and lst3

>>> str1 = "Totally"
>>> str2 = "Awesome"
>>> lst3 = ["Omg", "You", "Are"]

Simply use the .join() method and arithmetic operators to create the desired sentence.

>>> print ' '.join(lst3)
Omg You Are
>>> print ' '.join(lst3)+' '+str1+' '+str2
Omg You Are Totally Awesome

Besides string manipulation, I also recommend reading more about regex (regular expressions) to effectively search through strings and filter patterns.

Trick #5: Printing Made Easy

The last trick is something I wish I had known earlier. Turns out to print an array with strings as one comma-separated string, we do not need to use .join() and loops.

>>> row = ["1", "bob", "developer", "python"]
>>> print(','.join(str(x) for x in row))
1,bob,developer,python

This simple one-liner will do:

>>> print(*row, sep=',')
1,bob,developer,python


Another neat printing trick is to make use of enumerate. enumerateis a built-in function of Python which is incredibly useful. So instead of writing a four-line code to print

>>> iterable = ['a','b','c']
>>> c = 0 
>>> for item in iterable: 
>>>     print c, item 
>>>     c+= 1
0 a
1 b
2 c

The same can be done under just two lines

>>> for c, item in enumerate(iterable):
>>>     print c, item

This article is the end ! These are 5 Python Tricks I want to share with you, hope it will help you.
Thanks for reading !

Learn More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more:

Learn Python Programming

Learn Python Programming

Learn Python Programming

Description
Learn Python Programming

Learn Python Programming and increase your python programming skills with Coder Kovid.

Python is the highest growing programming language in this era. You can use Python to do everything like, web development, software development, cognitive development, machine learning, artificial intelligence, etc. You should learn python programming and increase your skills of programming.

In this course of learn python programming you don't need any prior programming knowledge. Every beginner can start with.

Basic knowledge
No prior knowledge needed to learn this course
What will you learn
Write Basic Syntax of Python Programming
Create Basic Real World Application
Program in a fluent manner
Get Familiar in Programming Environment