Date
Jul. 21st, 2024
 
2024年 6月 16日

Post: Python : Tips for Beginners

Python : Tips for Beginners

Published 12:09 Sep 06, 2015.

Created by @ezra. Categorized in #Programming, and tagged as #Python.

Source format: Markdown

Table of Content

Here are some useful tips and tricks in Python for beginners to the language who's coming from a traditional programming language like C or Java, and I assume you are using Python 3.

Swapping Elements

Here is the way that you're probably used to swap elements:

a = 1
b = 2
tmp = a
a = b
b = tmp

But here's a better way:

a = 1
b = 2
a, b = b, a

Initializing Lists

Sometime you just need a list of some integers set to zero. So you may do something like this:

arr = []
for _ in range(5):
    arr.append(0)

Elegantly:

arr = [0] * 5

But, do note that this will create a shallow copy if you are working with a list within a list.

For example:

arr = [[0]] * 5
# [[0], [0], [0], [0], [0]]
arr[0][0] = 1
# [[1], [1], [1], [1], [1]]

String building

Now, you're going to need to print strings.

tom = "boy"
lucy = "girl"
string = "Tom is a " + tom + " and Lucy is a " + lucy + ".";

Ugh, how messy. Do this instead:

tom = "boy"
lucy = "girl"
string = "Tom is a {0} and Lucy is a {1}.".format(tom, lucy)

List Comprehensions

Then, suppose you have a list like this:

arr = [1, 2, 3, 4, 5]

And you want to double each element in that list:

for i in range(len(arr)):
    arr[i] = arr[i] * 2
# [2, 4, 6, 8, 10]

Well, I can't say it's wrong, but I do have a cleaner way:

arr = [elem * 2 for elem in arr]

Returning tuples

To make life easier, Python allows you to return multiple elements (which is called tuples) in a function.

def getTwoNumber():
    return 1, 2

first, second = getTwoNumber()

And you can use an underscore if you don't need all of the elements returned, like so:

_, second = getTwoNumber()

Accessing Dictionaries

dict = {}
keys = [1, 2, 9]

dict = {i: 100 for i in keys}

for i in range(10):
    print("value for key {} is {}".format(i, dict.get(i, "empty")))

Nifty, huh?

Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF