Udemy-The-Python-Mega-Course-Learn-Python-in-60-Days-with-20-Apps
module 1
print('Enter a todo:')
def print(*values: object,
sep: str | None = “ “,
end: str | None = “\n”,
file: SupportsWrite[str] | None = None,
flush: Literal[False] = False) -> None
*parameter是用来接受任意多个参数并将其放在一个元组中
1 | def demo(*p): |
**parameter用于接收类似于关键参数一样赋值的形式的多个实参放入字典中(即把该函数的参数转换为字典)。
1 | def demo(**p): |
input()
def input(__prompt: object = “”) -> str
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a trailing newline before reading input.
1 | prompt = 'Enter a todo: ' |
type()
type(object) -> the object’s type
1 | print(type('prompt')) # <class 'str'> |
len()
def len(__obj: Sized) -> int
Return the number of items in a container.
1 | length_1 = len('Enter a title: ') |
using leading or trailing underscores
invoke引用
If you invoke something such as a principle, a saying, or a famous person, you refer to them in order to support your argument.
mangling 扭曲
f you say that someone mangles words or information, you are criticizing them for not speaking or writing clearly or correctly.
To avoid name clashes with subclasses, use two leading underscores to invoke Python’s name mangling rules.
_single_leading_underscore
: weak “internal use” indicator. E.g. from M import * does not import objects whose names start with an underscore.single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g. :
tkinter.Toplevel(master, class_=’ClassName’)__double_leading_underscore
: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
Python mangles these names with the class name: if class Foo has an attribute named __a, it cannot be accessed by Foo.__a. (An insistent user could still gain access by calling Foo._Foo__a.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.__double_leading_and_trailing_underscore__
: “magic” objects or attributes that live in user-controlled namespaces. E.g.__init__
,__import__
or__file__
. Never invent such names; only use them as documented.
Python mangles these names with the class name: if class Foo has an attribute named __a, it cannot be accessed by Foo.__a. (An insistent user could still gain access by calling Foo._Foo__a.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.
boolean type
is_male = True
list.append()
def append(self, __object: _T) -> None
Append object to the end of the list
1 | todos = [] |
str.capitalize() str.title()
print('hello world'.title()) # Hello world
def capitalize(self: LiteralString) -> LiteralString
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
print('hello world'.title()) # Hello World
def title(self: LiteralString) -> LiteralString
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
pycharm shortcut
cut a line
ctrl + x
paste a line before this line
ctrl + v
ctrl + b
while loop
1 | password = input("Enter password: ") |
1 | x = 1 |
break statement
break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.
It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.
If a for loop is terminated by break, the loop control target keeps its current value.
When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop
1 | todos = [] |
dir(str)
print(dir(str))
print(dir('Hello'))
def dir(__o: object = …) -> list[str]
Show attributes of an object.
If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__
, it will be used; otherwise the default dir() logic is used and returns:
for a module object: the module’s attributes. for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class’s attributes, and
recursively the attributes of its class’s base classes.
1 | import builtins |
help()
help("Hello".capitalize)
Help on built-in function capitalize:
capitalize() method of builtins.str instance
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.
match
1 | user_action = input("Type add or show: ") |
1 | user_action = input("Type add, show, or exit: ").strip() |
for loop
1 | todo_list = ['todo 1', 'todo 2', 'todo 3'] |
1 | for c in 'meals': |
str.strip()
1 | str1 = 'add ' |
def strip(self: LiteralString, __chars: LiteralString | None = None) -> LiteralString
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead
list index
list indices must be integers or slices, not str
int() float() str()
1 | x = 10.2 |
number = int(input("Number of the todo to edit: "))
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__()
. For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-‘ and be surrounded by whitespace. The base defaults to 10.
number = float('1.23')
str1 = str(12.3)
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__()
(if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.
list.index()
1 | todo_list = ['todo 1', 'todo 2', 'todo 3'] |
def index(self,
__value: _T,
__start: SupportsIndex = 0,
__stop: SupportsIndex = sys.maxsize) -> int
Return first index of value.
Raises ValueError if the value is not present
list.getitem()
def __getitem__
(self, __i: SupportsIndex) -> _T
Return self[index].
'Hello'[2] = 'a'
‘str’ object does not support item assignment
str.replace()
1 | filename = 1.raw data.txt' |
def replace(self: LiteralString,
__old: LiteralString,
__new: LiteralString,
__count: SupportsIndex = -1) -> LiteralString
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
tuple
1 | filenames1 = ('1.raw data.txt', '2.reports.txt', '3.presentations.txt') |
python local variable only in function
1 | filenames = ['1.raw data.txt', '2.reports.txt', '3.presentations.txt'] |
enumerate function
enumerate
to name things on a list one by one
class enumerate(Iterator[tuple[int, _T]], Generic[_T])
Return an enumerate object.
The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), …
iterable
an object supporting iteration
1 | # 0 - todo 1 |
1 | todo_list = ['todo 1', 'todo 2', 'todo 3'] |
format string
1 | index = 1 |
list.pop()
1 | todo_list = ['todo 1', 'todo 2', 'todo 3'] |
def pop(self, __index: SupportsIndex = -1) -> _T
Remove and return item at index (default last).
list.sort()
def sort(self: list[SupportsRichComparisonT],
*,
key: None = None,
reverse: bool = False) -> None
Sort the list in ascending order and return None.
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
1 | waiting_list = ['sen', 'ben', 'john'] |