Python学习日志

本文深入探讨了Python编程的多个核心概念,包括流程控制结构、数据结构的创建与使用,如列表、字典、集合的生成式,以及函数参数的灵活应用。文章还详细解释了匿名函数、生成器和迭代器的使用场景,展示了Python语言的强大与灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

Cancel with break

Skip with continue

Positional Arguments

Keyword Arguments

Gather Positional Arguments with *

Gather Keyword Arguments with **

Uses of _ and __ in Names

preferences:


       The # character has many names: hash, sharp, pound, or the sinister-sounding octothorpe.

 

       In Python, indentation determines how the if and else sections are paired.

 

 

>>> while True:

...     stuff = input( "String to capitaliza [type q to quit]: ")

...     if stuff == "q":

...             break;

...     print(stuff.capitalize())

...

String to capitaliza [type q to quit]: ffergeg

Ffergeg

String to capitaliza [type q to quit]: wrqqrwq

Wrqqrwq

String to capitaliza [type q to quit]: tveteverETE3453

Tveteverete3453

String to capitaliza [type q to quit]: 3534WER

3534wer

String to capitaliza [type q to quit]:

 

Cancel with break

        A break in a for loop breaks out of the loop, as it does for a while loop.

Skip with continue

        Inserting a continue in a for loop jumps to the next iteration of the loop, as it does for a while loop. 

        zip() stops when the shortest sequence is done.

 

        The simplest form of list comprehension is:

[ expression for item in iterable ]

 

        Here’s how a list comprehension would build the integer list:

>>> number_list = [number for number in range(1,6)]

>>> number_list

[1, 2, 3, 4, 5]

        In the first line, you need the first number variable to produce values for the list: that is, to put a result of the loop into number_list .

 

        The list comprehension moves the loop inside the square brackets. This comprehension example really wasn’t simpler than the previous example, but there’s more. A list com‐prehension can include a conditional expression, looking something like this:

[ expression for item in iterable if condition ]

 

        The simplest dictionaries comprehensions form looks familiar:

{ key_expression : value_expression for expression in iterable }

 

        The simplest sets comprehensions version looks like the list and dictionary comprehensions that you’ve just seen:

{ expression for expression in iterable }

 

        Tuples do not have comprehensions!

 

        You might have thought that changing the square brackets of a list comprehension to parentheses would create a tuple comprehension. And it would appear to work because there’s no exception if you type this:

>>> number_thing = (number for number in range(1, 6))

        The thing between the parentheses is a generator comprehension, and it returns a generator object:

>>> type(number_thing)

<class 'generator'>

 

        A generator is one way to provide data to an iterator.

 

        A generator can be run only once. Lists, sets, strings, and dictionaries exist in memory, but a generator creates its values on the fly and hands them out one at a time through an iterator. It doesn’t remember them, so you can’t restart or back up a generator.

 

        Python requires the pass statement to show that this function does nothing. It’s the equivalent of This page intentionally left blank (even though it isn’t anymore).

 

        None is a special Python value that holds a place when there is nothing to say. It is not the same as the boolean value False , although it looks false when evaluated as a boolean.

        Here’s an example:

>>> thing = None

>>> if thing:

...

print("It's some thing")

... else:

...

print("It's no thing")

...

It's no thing

        To distinguish None from a boolean False value, use Python’s is operator:

>>> if thing is None:

...

print("It's nothing")

... else:

...

print("It's something")

...

It's nothing

        This seems like a subtle distinction, but it’s important in Python. You’ll need None to distinguish a missing value from an empty value. Remember that zero-valued integers or floats, empty strings ( '' ), lists ( [] ), tuples ( (,) ), dictionaries ( {} ), and sets( set() ) are all False , but are not equal to None .

        Let’s write a quick function that prints whether its argument is None :

>>> def is_none(thing):

...

if thing is None:

...

print("It's None")

...

elif thing:

...

print("It's True")

...

else:

...

print("It's False")

...

Now, let’s run some tests:

>>> is_none(None)

It's None

>>> is_none(True)

It's True

>>> is_none(False)

It's False

>>> is_none(0)

It's False

>>> is_none(0.0)

It's False

>>> is_none(())

It's False

>>> is_none([])

It's False

>>> is_none({})

It's False

>>> is_none(set())

It's False

 

Positional Arguments

        Python handles function arguments in a manner that’s unusually flexible, when compared to many languages. The most familiar types of arguments are positional arguments, whose values are copied to their corresponding parameters in order.

 

Keyword Arguments

        To avoid positional argument confusion, you can specify arguments by the names of their corresponding parameters, even in a different order from their definition in the function.

 

        If you call a function with both positional and keyword arguments, the positional arguments need to come first.

 

Gather Positional Arguments with *

        If you’ve programmed in C or C++, you might assume that an asterisk ( * ) in a Python program has something to do with a pointer. Nope, Python doesn’t have pointers.

        When used inside the function with a parameter, an asterisk groups a variable number of positional arguments into a tuple of parameter values.

 

Gather Keyword Arguments with **

        You can use two asterisks ( ** ) to group keyword arguments into a dictionary, where the argument names are the keys, and their values are the corresponding dictionary values.

 

        If you mix positional parameters with *args and **kwargs , they need to occur in that order. As with args , you don’t need to call this keyword parameter kwargs , but it’s common usage.

 

        An inner function can be useful when performing some complex task more than once within another function, to avoid loops or code duplication.

 

        The lambda takes one argument, which we call word here. Everything between the colon and the terminating parenthesis is the definition of the function.

 

        In Python, a lambda function is an anonymous function expressed as a single statement. You can use it instead of a normal tiny function.

 

        Often, using real functions such as enliven() is much clearer than using lambdas.

        Lambdas are mostly useful for cases in which you would otherwise need to define many tiny functions and remember what you called them all. In particular, you can use lambdas in graphical user interfaces to define callback functions.

 

        A generator is a Python sequence creation object. With it, you can iterate through potentially huge sequences without creating and storing the entire sequence in memory at once. Generators are often the source of data for iterators.

 

        Every time you iterate through a generator, it keeps track of where it was the last time it was called and returns the next value. This is different from a normal function, which has no memory of previous calls and always starts at its first line with the same state.

 

        If you want to create a potentially large sequence, and the code is too large for a generator comprehension, write a generator function. It’s a normal function, but it returns its value with a yield statement rather than return.

 

       Yield is a keyword that is used like return, except the function will return a generator.

 

        To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky.

 

        To access the global variable rather than the local one within a function, you need to be explicit and use the global keyword (you knew this was coming: explicit is better than implicit).

 

        If you don’t say global within a function, Python uses the local namespace and the variable is local. It goes away after the function completes.

 

       The local namespace within change_local() contained only the local variable animal . The global namespace contained the separate global variable animal and a number of other things.

 

Uses of _ and __ in Names

        Names that begin and end with two underscores ( __ ) are reserved for use within Python, so you should not use them with your own variables. This naming pattern was chosen because it seemed unlikely to be selected by application developers for their own variables.

 

        In some languages, errors are indicated by special function return values. Python uses exceptions: code that is executed when an associated error occurs.

 

        It’s good practice to add exception handling anywhere an exception might occur to let the user know what is happening. You might not be able to fix the problem, but at least you can note the circumstances and shut your program down gracefully. If an exception occurs in some function and is not caught there, it bubbles up until it is caught by a matching handler in some calling function. If you don’t provide your own exception handler, Python prints an error message and some information about where the error occurred and then terminates the program.

 

        Sometimes, you want exception details beyond the type. You get the full exception object in the variable name if you use the form:

except exceptiontype as name

 

        In Python, an exception is a class. It is a child of the class Exception .

 

preferences:

Bill Lubanovic. Introducing Python[M]. O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值