• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

wilfredinni/python-cheatsheet: Basic Cheat Sheet for Python (PDF, Markdown and J ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

wilfredinni/python-cheatsheet

开源软件地址:

https://github.com/wilfredinni/python-cheatsheet

开源编程语言:

Jupyter Notebook 100.0%

开源软件介绍:

About Binder

Basic cheatsheet for Python mostly based on the book written by Al Sweigart, Automate the Boring Stuff with Python under the Creative Commons license and many other sources.

Contribute

All contributions are welcome:

  • Read the issues, Fork the project and do a Pull Request.
  • Request a new topic creating a New issue with the enhancement tag.
  • Find any kind of errors in the cheat sheet and create a New issue with the details or fork the project and do a Pull Request.
  • Suggest a better or more pythonic way for existing examples.

Read It

Python Cheatsheet

The Zen of Python

From the PEP 20 -- The Zen of Python:

Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Return to the Top

Python Basics

Math Operators

From Highest to Lowest precedence:

Operators Operation Example
** Exponent 2 ** 3 = 8
% Modulus/Remainder 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3 * 3 = 9
- Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4

Examples of expressions in the interactive shell:

>>> 2 + 3 * 6
20
>>> (2 + 3) * 6
30
>>> 2 ** 8
256
>>> 23 // 7
3
>>> 23 % 7
2
>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0

Return to the Top

Data Types

Data Type Examples
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

Return to the Top

String Concatenation and Replication

String concatenation:

>>> 'Alice' 'Bob'
'AliceBob'

Note: Avoid + operator for string concatenation. Prefer string formatting.

String Replication:

>>> 'Alice' * 5
'AliceAliceAliceAliceAlice'

Return to the Top

Variables

You can name a variable anything as long as it obeys the following rules:

  1. It can be only one word.
  2. It can use only letters, numbers, and the underscore (_) character.
  3. It can’t begin with a number.
  4. Variable name starting with an underscore (_) are considered as "unuseful`.

Example:

>>> spam = 'Hello'
>>> spam
'Hello'
>>> _spam = 'Hello'

_spam should not be used again in the code.

Return to the Top

Comments

Inline comment:

# This is a comment

Multiline comment:

# This is a
# multiline comment

Code with a comment:

a = 1  # initialization

Please note the two spaces in front of the comment.

Function docstring:

def foo():
    """
    This is a function docstring
    You can also use:
    ''' Function Docstring '''
    """

Return to the Top

The print() Function

>>> print('Hello world!')
Hello world!
>>> a = 1
>>> print('Hello world!', a)
Hello world! 1

Return to the Top

The input() Function

Example Code:

>>> print('What is your name?')   # ask for their name
>>> myName = input()
>>> print('It is good to meet you, {}'.format(myName))
What is your name?
Al
It is good to meet you, Al

Return to the Top

The len() Function

Evaluates to the integer value of the number of characters in a string:

>>> len('hello')
5

Note: test of emptiness of strings, lists, dictionary, etc, should not use len, but prefer direct boolean evaluation.

>>> a = [1, 2, 3]
>>> if a:
>>>     print("the list is not empty!")

Return to the Top

The str(), int(), and float() Functions

Integer to String or Float:

>>> str(29)
'29'
>>> print('I am {} years old.'.format(str(29)))
I am 29 years old.
>>> str(-3.14)
'-3.14'

Float to Integer:

>>> int(7.7)
7
>>> int(7.7) + 1
8

Return to the Top

Flow Control

Comparison Operators

Operator Meaning
== Equal to
!= Not equal to
< Less than
> Greater Than
<= Less than or Equal to
>= Greater than or Equal to

These operators evaluate to True or False depending on the values you give them.

Examples:

>>> 42 == 42
True
>>> 40 == 42
False
>>> 'hello' == 'hello'
True
>>> 'hello' == 'Hello'
False
>>> 'dog' != 'cat'
True
>>> 42 == 42.0
True
>>> 42 == '42'
False

Boolean evaluation

Never use == or != operator to evaluate boolean operation. Use the is or is not operators, or use implicit boolean evaluation.

NO (even if they are valid Python):

>>> True == True
True
>>> True != False
True

YES (even if they are valid Python):

>>> True is True
True
>>> True is not False
True

These statements are equivalent:

>>> if a is True:
>>>    pass
>>> if a is not False:
>>>    pass
>>> if a:
>>>    pass

And these as well:

>>> if a is False:
>>>    pass
>>> if a is not True:
>>>    pass
>>> if not a:
>>>    pass

Return to the Top

Boolean Operators

There are three Boolean operators: and, or, and not.

The and Operator’s Truth Table:

Expression Evaluates to
True and True True
True and False False
False and True False
False and False False

The or Operator’s Truth Table:

Expression Evaluates to
True or True True
True or False True
False or True True
False or False False

The not Operator’s Truth Table:

Expression Evaluates to
not True False
not False True

Return to the Top

Mixing Boolean and Comparison Operators

>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True

You can also use multiple Boolean operators in an expression, along with the comparison operators:

>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True

Return to the Top

if Statements

if name == 'Alice':
    print('Hi, Alice.')

Return to the Top

else Statements

name = 'Bob'
if name == 'Alice':
    print('Hi, Alice.')
else:
    print('Hello, stranger.')

Return to the Top

elif Statements

name 
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap