【Python】Python基本语法

    xiaoxiao2023-10-01  156

    Python基本语法

    本文内容主要从Learn Python The Hard Way、笨方法学python、RUNOOB.COM\Python3 教程整理汇总。

    Python CommandsPython FormatKey WordsInput and Output Functions Basic IO Print on ScreenInput from keyboard File IO Data Type String Generate strings.String-Related Functions.Escape Sequences ListTupleDictionary Import FunctionDefine FunctionLogical FunctionConditional FunctionLoop FunctionClass Function Get Attributes From Class Iterator and Generator Iterator: iter() & next()Create IteratorExpection of StopIteration Generator

    Python Commands

    # look for help described by python using pydoc with names. python -m pydoc <names> # show the function definition. help(function)

    Python Format

    Python脚本的首行应该添加:

    # !/usr/bin/env python

    该命令用以引导脚本程序找到python的解释器(Interpreter)。 该命令仅适用于linux/unix环境,因为它们根据文件的首部内容决定文件的执行方式。 而windows环境根据后缀名决定文件的执行方式。

    Python脚本的首部还应该添加:

    # coding:utf-8

    该命令表示该脚本使用utf-8编码格式,如此该脚本内容使用的中文才能被正常显示。

    Key Words

    and not or del from while for as if else elif break continue global with assert pass yield except import print class exec in raise try finally is def return lambda

    Input and Output Functions

    Basic IO

    Print on Screen

    Print marker of quotes by using single quote ‘’ in double quote “” OR double quote “” in single quote ‘’. print("My name is 'Ylonge'") print('My name is "Ylonge"') Print sequential strings with variables. print("There are", 5, "people in", 3, "rooms") Print one line with two separate sentences by change the end of first string to other marker instead of default ‘\n’. print("My name is", end = ' ') print("ylonge yu") Print multiple lines as you wish using triple double quotes like “”" or triple single quotes like ‘’’. print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """) Print special characters using \ (backslash) character to change a special character into a string. print("I am 6'2\" tall.") print('I am 6\'2" tall.')

    Input from keyboard

    Input something (always store in variable as string) using function input(string) with the string present as a guideline. Age = input() Age = input("What's your age?") Input something and preserve the type of input, e.g. str, int, list and so on. Age = eval(input())

    File IO

    # open file txt = open(filename) # read all contents in file print(txt.read()) # read one line from file print(txt.readline()) # read all lines from file print(txt.readlines()) # wipe out context in file txt.truncate() # jump to file position with offset pos compared to the start txt.seek(pos) # write stuff in file txt.write(stuff)

    Data Type

    String

    Generate strings.

    Generate a string using variables, use double-quote “” or single-quote ‘’ following a ‘f’ meaning ‘format’ and {} containing the variables. # variable directly in {}. stringGenerate = f"string{variable}" # variable indicated by format. stringGenerate = f"string{}".format(variable) # string format is pre-defined. stringFormat = "Isn't that joke so funny?! {}" print(stringFormat.format{variable} Generate a string using regular expression indicated by %. stringFormat = "My name is %s and my weight is %dKG" % ("Ylonge", "76.5")

    String-Related Functions.

    str.split()

    功能:根据delimiter将字符串分割。

    函数形式:

    str.split(delimiter=None, num=-1)

    参数解释:

    参数解释delimiter分隔符可以是space, \n, \t等。分隔符不存在时,分割所有类型的分隔符。num默认值为1,此时分割所有分隔符。如果给定数目少于分隔符最大数目,则前num个元素被分割。

    返回值:返回分割后的字符串列表。

    str.isalnum()

    功能:检查是否所有元素都是数字。

    str.join(iterable)

    功能:返回一个将iterable中所有元素连接并以str为连接符的字符串。

    Escape Sequences

    \\ \' \" \a \b \f \n \r \t \v

    List

    功能:包含一组有序元素,元素由index索引。其中元素类型可以是数字、字符串、列表、字典、函数。

    # list construction hairs = ['brown', 'blond', 'red'] eys = ['brown', 'blue', 'green'] weights = [1, 2, 3, 4] # list functions ## remove and return item with given index. If index is not given, the last item is removed. itemPop = list.pop([index])

    Tuple

    元组与列表类似,不同之处在于元组的元素不能修改。

    # tuple construction. tuple1 = ('Google', 'Runnob', 1997, 2000) tuple2 = 'a', 'b', 'c', 'd' emptyTuple = () # delete tuple. del tuple1 # add tuple. tuple3 = tuple1 + tuple2 # initialize values for a tuple of variables. a, b, c = 1, 2, 3

    Dictionary

    功能:包含一组键值和对应元素,元素由键值key索引。其中元素类型可以是数字、字符串、列表、字典、函数。

    # dict construction. stuff = {'name': 'Zed', 'age': 36, 'height': 6 * 12 + 2} # check whether keys exist in dict. if '0' not in next or '1' in next: # delete element in dictionary. del stuff['name'] # list all items in dictionary. Items include key and value. Can be used for iterable accessing. dictEg.items() # create and return a dict with keys in listKey and values equal to initValues. dictEg = dict.fromkeys([listKey], initValues) # return an iterable key and can be changed to list using list() keyIterable = dictEg.keys() keyList = list(dictEg.keys())

    NOTE: 当字典的键值为列表或字典时,为了获取/赋值键值中字典/列表的值,有两种方法可以实现:

    方法一:逐层引用,先赋值/获取最高层的键值,再赋值/获取下一层的值: # assign values. dic1 = {'test': {}, 'anchor': {}} dic11 = {'qp1': 32, 'qp2': 37} dic12 = {'qp1': 22, 'qp2': 27} dic1['test'] = dic11 dic1['anchor'] = dic12 # obtain values. val111 = dic1.get('test')['qp1'] # get() can be replaced by setdefault(). val122 = dic1.get('anchor')['qp2'] # get() can be replaced by setdefault(). 方法二:多重索引引用,类似C++中二维数组的使用: # assign values. dic1 = {'test': {}, 'anchor': {}} dic1['test']['qp1'] = 32 dic1['test']['qp2'] = 37 dic1['anchor']['qp1'] = 22 dic1['anchor']['qp2'] = 27 # obtain values. val111 = dic1['test']['qp1'] val122 = dic1['anchor']['qp2']

    值得注意的是,方法二的赋值和获取在vscode中会被pylint标记为error,但是并不影响执行结果。目前还不太清楚是否方法二会产生什么问题,有待学习。

    Import Function

    Import argv function from the module sys, where the argv including: script contain the repository and script name as the first one. other input arguments in order. from sys import argv script, first, second, third = argv print("The script is called:", script) print("Your first variable is:", first) print("Your second variable is:", second) print("Your third variable is:", third) Check whether a file exists by importing the exists function from os.path. from os.path import exists Import all functions in sys module import sys Import all functions in module test and use the functions without typing the module name. from test import *

    Define Function

    Define functions with different number of arguments. # define a new function with multiple arguments. def print_two(*args): # define a new function with two arguments. def print_two_again(arg1, arg2): # define a new function with one argument. def print_one(arg1): # define a new function with no argument. def print_none(): Define function with help information. def sort_words(words): """Sorts the words.""" return sorted(words)

    Logical Function

    True and True True and False not False 1 == 1 2 != 1 3 >= 1 1 <= 5

    Conditional Function

    # simple condition if people < cats: print("Too many cats! The world is doomed!") # multiple conditions if cars > people: print("We should take the cars.") elif: print("We should not take the cars.") else: print("We can't decide.")

    Loop Function

    # while while i < 6: print(i) i += 1 # for for i in range(0, 6): print(i) for item in listTmp: print(item) for key in dictTmp: print(dictTmp[key])

    Class Function

    class TheThing(object): ''' Define a class. The first argument of functions in class must be self which represents the class itself. The object can be any other class that is parent class of the current class, which is the class inherit. ''' # __init__ is used to declare self-contained elements and initialize them. # __init__ is called by using the class name. def __init__(self): self.number = 0 def some_function(self): print("I got called.") def add_me_up(self, more): self.number += more return self.number

    Get Attributes From Class

    # Function: Get a named attribute from an object. getattr(x, 'y') is equivalent to x.y room = getattr(self, next)

    Iterator and Generator

    Iterator

    功能:迭代器从集合的第一个元素开始访问,知道所有的元素被访问完结束。

    特点:

    迭代器只能前进不能后退。字符串、列表和元祖对象(即有序对象)都可以用于创建迭代器。

    iter() & next()

    list = [1, 2, 3, 4] it = iter(list) # create iterator. print(next(it)) # output next element of iterator. # traverse all elements by iterator with for function. for x in it: print(x, end=' ') # traverse all elements by iterator and next. import sys while True: try: print(next(it)) except StopIteration: sys.exit()

    Create Iterator

    创建迭代器类需要在类中实现两个方法__iter__()和__next__()。

    # create a iterator which start from 1 and increase with step 1. class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x # run MyNumbers iterator. myClass = MyNumbers() myIter = iter(myClass) print(next(myIter)) print(next(myIter))

    Expection of StopIteration

    StopIteration异常用于标识迭代的完成,防止出现无限循环的情况,可以在__next__()方法中设置在完成指定循环次数后触发异常来结束迭代。

    class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration

    Generator

    定义:使用了yield的函数被称为生成器Generator。

    特性:

    生成器是一个返回迭代器的函数,只能用于迭代操作。调用生成器运行时,每次遇到yield时函数会暂停并保存当前所有的运行信息,返回yield的值,并在下一次执行next()方法时从当前位置继续运行。生成器的返回值为迭代器对象。 import sys def fibonacci(n): # this is a generator. a, b, counter = 0, 1, 0 while True: if counter > n: return StopIteration yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f is an iterator. while True: try: print(next(f), end=' ') except StopIteration: sys.exit()
    最新回复(0)