Table of Contents
if Statement in line" >if Statement in line
Connection
Number skills
Numerical comparison
List comprehension
Dictionary comprehension
Get elements from dictionary
Getting a subset of a list
60 characters to solve FizzBuzz
Home Backend Development Python Tutorial Must-see Python tips for beginners

Must-see Python tips for beginners

Mar 17, 2017 pm 03:51 PM
python skills

The following are some Python practical tips and tools that I have collected in recent years. I hope they can be helpful to you.

ExchangeVariables

1

2

3

4

5

6

7

x = 6

y = 5

x, y = y, x

print x

>>> 5

print y

>>> 6

Copy after login

if Statement in line

1

2

print "Hello" if True else "World"

>>> Hello

Copy after login

Connection

The last one below This method is very cool when binding two objects of different types.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

nfc = ["Packers", "49ers"]

afc = ["Ravens", "Patriots"]

print nfc + afc

>>> ['Packers', '49ers', 'Ravens', 'Patriots']

  

print str(1) + " world"

>>> 1 world

  

print `1` + " world"

>>> 1 world

  

print 1, "world"

>>> 1 world

print nfc, 1

>>> ['Packers', '49ers'] 1

Copy after login

Number skills

1

2

3

4

5

6

#除后向下取整

print 5.0//2

>>> 2

# 2的5次方

print 2**5

>> 32

Copy after login

Pay attention to the division of floating point numbers

1

2

3

4

print .3/.1

>>> 2.9999999999999996

print .3//.1

>>> 2.0

Copy after login

Numerical comparison

This is one of the few languages ​​I have seen that is so awesome Simple method

1

2

3

4

5

6

7

x = 2

if 3 > x > 1:

   print x

>>> 2

if 1  0:

   print x

>>> 2

Copy after login

Iterate two lists simultaneously

1

2

3

4

5

6

nfc = ["Packers", "49ers"]

afc = ["Ravens", "Patriots"]

for teama, teamb in zip(nfc, afc):

     print teama + " vs. " + teamb

>>> Packers vs. Ravens

>>> 49ers vs. Patriots

Copy after login

Indexed list iteration

1

2

3

4

5

6

7

teams = ["Packers", "49ers", "Ravens", "Patriots"]

for index, team in enumerate(teams):

    print index, team

>>> 0 Packers

>>> 1 49ers

>>> 2 Ravens

>>> 3 Patriots

Copy after login

List comprehension

Given a list, we can The method of brushing to select an even number list:

1

2

3

4

5

numbers = [1,2,3,4,5,6]

even = []

for number in numbers:

    if number%2 == 0:

        even.append(number)

Copy after login

changes to the following:

1

2

numbers = [1,2,3,4,5,6]

even = [number for number in numbers if number%2 == 0]

Copy after login

Isn’t it awesome, haha.

Dictionary comprehension

Similar to list comprehension, a dictionary can do the same job:

1

2

3

teams = ["Packers", "49ers", "Ravens", "Patriots"]

print {key: value for value, key in enumerate(teams)}

>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}

Copy after login

Initialize the value of the list

1

2

3

items = [0]*3

print items

>>> [0,0,0]

Copy after login

Convert the list to String

1

2

3

teams = ["Packers", "49ers", "Ravens", "Patriots"]

print ", ".join(teams)

>>> 'Packers, 49ers, Ravens, Patriots'

Copy after login

Get elements from dictionary

I admit that the try/except code is not elegant, but here is a simple method, try to find the key in the dictionary, if not found The corresponding alue will be set to its variable value using the second parameter.

1

2

3

4

5

data = {'user': 1, 'name': 'Max', 'three': 4}

try:

   is_admin = data['admin']

except KeyError:

   is_admin = False

Copy after login

Replace with this:

1

2

data = {'user': 1, 'name': 'Max', 'three': 4}

is_admin = data.get('admin', False)

Copy after login

Getting a subset of a list

Sometimes, you only need some of the elements in a list. Here are some ways to get a subset of a list.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

x = [1,2,3,4,5,6]

#前3个

print x[:3]

>>> [1,2,3]

#中间4个

print x[1:5]

>>> [2,3,4,5]

#最后3个

print x[3:]

>>> [4,5,6]

#奇数项

print x[::2]

>>> [1,3,5]

#偶数项

print x[1::2]

>>> [2,4,6]

Copy after login

60 characters to solve FizzBuzz

Some time ago Jeff Atwood promoted a simple programming exercise called FizzBuzz. The question is quoted as follows:

Write a The program prints the numbers 1 to 100, replacing the number with "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for numbers that are both multiples of 3 and 5.

Here is a short, interesting way to solve this problem:

1

for x in range(101): print"fizz"[x%3*4::]+"buzz"[x%5*4::] or x

Copy after login

Collection

In addition to python's built-in

data type, in the collection module It also includes some special use cases, where Counter is very useful. If you participated in this year's Facebook HackerCup, you can even find its practicality.

1

2

3

from collections import Counter

print Counter("hello")

>>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

Copy after login

Iteration tool

Like the collections library, there is also a library called itertools, which can really solve certain problems efficiently. One of the use cases is to find all combinations, which can tell you all the impossible combinations of elements in a group

1

2

3

4

5

6

7

8

9

10

11

from itertools import combinations

teams = ["Packers", "49ers", "Ravens", "Patriots"]

for game in combinations(teams, 2):

    print game

>>> ('Packers', '49ers')

>>> ('Packers', 'Ravens')

>>> ('Packers', 'Patriots')

>>> ('49ers', 'Ravens')

>>> ('49ers', 'Patriots')

>>> ('Ravens', 'Patriots')

False == True

Copy after login

This is a very interesting thing compared to practical technology. In python, True and False is a global variable, so:

1

2

3

4

5

6

False = True

if False:

   print "Hello"

else:

   print "World"

>>> Hello

Copy after login

The above is the detailed content of Must-see Python tips for beginners. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: The Power of Versatile Programming Python: The Power of Versatile Programming Apr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

See all articles