Python Basics (i)

Source: Internet
Author: User
Tags arithmetic operators delete key function definition

1. Notes
    • Single-line Comment:
# 这是一个单行注释print("Hello Wrold!")
    • Multi-line Comments:
'''这是一个多行注释'''
2. Arithmetic operators
# 加法print(1 + 1)# 减法print(20 - 12)# 乘法print(10 * 23)# 除法print(22 / 2)# 取整数,返回除法的整数部分(商)。下面的结果为4print(9 // 2)# 取余数print(9 % 2)# 幂运算print(2 ** 3)
3. Data type
    1. In Python, when you define a variable, you do not need to specify the type of the variable. During the run, the Python interpreter will follow the assignment statement
      The data on the right side of the equal sign automatically infers the exact type of data stored in the variable.
    2. type(变量名)View the type of the current variable.
    3. Data type classification: digital and non-digital
      • Digital type:
        • Integral type (int) (in python2.x, integral type divided into int , long )
        • Float type (float)
        • Boolean type (BOOL)
        • Complex Type (complex), mainly used for scientific calculation.
      • Non-digital type:
        • String
        • List
        • Meta-group
        • Dictionary
# 字符串变量之间可以使用"+"进行拼接a = "Hello "b = "World!"print(a + b)# 字符串变量可以使用"*"进行重复print("A" * 10)# 数字型变量和字符串之间不能进行其他计算# 下面的输出会报错print("A" + 10)
Formatted output of 3.4 variables
    • %Called the format operator, which is designed to handle formatting in strings;
    • %sRepresents a string;
    • %dRepresents a signed decimal integer representing the number of digits in the %06d output of an integer, where insufficient 0 is used
    • %fRepresents a floating-point number that %.2f shows only two digits after the decimal point;
    • %%Output % ;
# 输出学号 000021, 地址是: 江苏南京num = 21address = "江苏南京"print("我的学号是:%06d,地址是:%s" % (num, address))# 输出百分比: 12.45%percent = 12.45print("所占百分比:%.2f%%" % percent)
3.5 Naming of variables
    • The identifier is the variable name defined in the program, the name of the function;
    • Identifiers can consist of letters, underscores, and numbers;
    • Cannot begin with a number;
    • Cannot duplicate the keyword;
    • PythonThe identifiers in the are case-sensitive;
    • In Python , if the variable name needs to consist of more than one word, you can name it in the following way:
      • Use lowercase letters for each word;
      • Use an underscore connection between words and words;
      • For example:, stu_name stu_address ,stu_num
4. Logic Statements 4.1 ifStatement
# 格式:if 条件1:    条件1成立时,需要执行的操作elif 条件2:    条件2成立时,需要执行的操作else:    条件不成立时,需要执行的操作# 注意:代码的缩进为一个Tab键,或者 4 个空格 -- 建议使用空格#      在 Python 开发中, Tab 和 空格不要混用!
4.2 Loop Statements
# while 循环# 打印 5 遍 Hello Pythoni = 1while i <= 5:    print("Hello Python")    i += 1# 示例一:# 在控制台连续输出五行 *, 每一行星号的数量依次递增row = 1while row <= 5:    print("*" * row)    row += 1# 第二种方式:# 备注: 向控制台输出内容结束之后,不会换行#      print("*", end="")row = 1while row <= 5:    col = 1    while col <= row:        print("*", end="")        col += 1    # 表示在一行星星输出完成之后,添加换行!    print("")    row += 1# 示例二: 输出九九乘法表# 备注: 字符串中的转义字符#   \t : 在控制台输出一个制表符,协助在输出文本时,垂直方向保持对齐#   \n : 在控制台输出一个换行符row = 1while row <= 9:    col = 1    while col <= row:        print("%d * %d = %d" % (col,row,col * row), end="\t")        col += 1    print("")    row += 1
5. function 5.1 function definition and function
    • function is to organize code blocks with independent functions into a small module, which is called when needed;
    • function, can improve the efficiency of writing and code reuse ;
# 函数定义:#    函数名称命名规则:#           可以由字母,下划线和数字组成#           不能以数字开头def 函数名():    函数封装的代码# 函数注释:#     在定义函数的下方,使用连续的三对引号#     在函数调用的位置,使用"View -> Quick Documentation"可以查看函数的说明信息#     由于函数体相对比较独立,函数定义的上方, 应该和其他代码(包括注释)保留两个空行# 函数的参数:# 需求: 求两个数字的和def sum_num(num1, num2):    """对两个数字求和"""    result = num1 + num2    print("%d + %d = %d" % (num1, num2, result))sum_num(33, 20)
5. Advanced Variable Type
    • List
    • Meta-group
    • Dictionary
    • String
5.1 Lists (list)
    • The list [] is defined by the use of separation between data , ;
    • The list can store different types of data, but in development, lists are often used to store the same type of data;
    • The index of the list 0 starts from;
Common operations (methods) for 5.1.1 lists:
    • added:
      • Insert (index, data) : Insert data at specified location;
      • Append (data) : Append data at the end;
      • Extend (Listing 2) : Appends data from List 2 to the list;
    • Modify:
      • list [index] = new data : Modify data for the specified index;
    • Delete:
      • del list [index] : Delete data for the specified index;
      • list. Remove (data) : Deletes the first occurrence of the specified data;
      • list. Pop () : Delete end data;
      • list. Pop (index) : Delete the specified index data;
      • list. Clear : Empty list;
    • Statistics:
      • len (list) : Gets the length of the list;
      • list. Count (data) : The number of times the data appears in the list;
    • Sort:
      • list. Sort () : Sort Ascending;
      • list. Sort (reverse=true) : Sort Descending
      • list. Reverse () : reverse (reverse)
# 列表的循环遍历name_list = ["zhangsan","lisi","wangwu","zhaoliu"]for name in name_list:    print(name)# 向列表中添加元素t_list = [1, 2]t_list.extend([3, 4]) # t_list = [1, 2, 3, 4]t_list.append([5, 6]) # t_list = [1, 2, 3, 4, [5, 6]]
5.2 Tuples (tuple)
    • A tuple represents a sequence of multiple elements, and the elements in the tuple cannot be modified;
    • Tuples are typically used to hold different types of data;
    • Tuple usage () definitions;
    • When you include only one element in a tuple, you need to add a comma after the element:a_tuple = (3,)
    • Common ways to tuple:
      • 元组.index(数据): Gets the index of the data in the tuple;
      • 元组.count(数据): Gets the number of times the data appears in the tuple;
    • Conversions between tuples and lists:
      • List(元组): Convert tuples to lists;
      • tuple(列表): Convert list to Narimoto Group;
    • Tuple scenarios:
      • The parameter and return value of the function;
      • Let the list not be modified;
# 格式化字符串后面的 () 本质上就是元组print("%s 年龄是 %d, 身高是 %.2f" % ("张三", 12, 1.53))stu_info = ("张三", 12, 1.53)print("%s 年龄是 %d, 身高是 %.2f" % stu_info)stu_info = "%s 年龄是 %d, 身高是 %.2f" % ("张三", 12, 1.53)print(stu_info)
5.3 Dictionaries (Directory)
    • Dictionaries are typically used to store information that describes an object ;
    • Dictionary use {} definition;
    • The dictionary uses key-value pairs to store data, and to use separation between key-value pairs , ;
      • Use separation between keys and values : ;
      • The key must be unique ;
      • The value can be any data type, but the key can only use strings, numbers or tuples ;
    • The difference between a dictionary and a list:
      • A list is an ordered collection of objects;
      • A dictionary is a collection of unordered objects;
    • Common operations for dictionaries:
      • 字典.pop(key): Delete key value pairs;
      • len(字典): The number of key value pairs of statistics;
      • 字典1.update(字典2): merge dictionary; If the merged dictionary contains key-value pairs that already exist, the original key-value pairs will be overwritten;
      • 字典.clear(): Clears the dictionary;
5.4 String
    • You can use pair of double quotes or pair of single quotation marks to define a string;
    • Although you can use \ " or \ ' to escape a string, but in practice:
      • If you need to use double quotes inside a string, you can use single quotation marks to define the string;
      • If you need to use single quotes inside a string, you can use double quotation marks to define the string;
    • Most programming languages use " to define a string;
    • common operations for strings:
      • len (string) : Gets the length of the string;
      • String. Count (String 2) : Gets the number of times a small string appears in a large string;
      • The
      • string. Index (String 2) : Gets the index of the first occurrence of the small string, or an error if it does not exist;
      • The
      • string. Find (String 2) : Find string, if not present, return-1;
      • The
      • string. Replace (Old_str, NEW_STR) : replace string; When the method executes, a new string is returned, and the original string is unchanged;
      • slice of string: string [start index: End index: Step] ,
# 字符串的遍历string = "Hello Python!"for c in string:    print(c)# string.isdecimal(): 如果 string 只包含数字则返回True, 全角数字# string.isdigit(): 如果 string 只包含数字则返回True, 全角数字, (1), \u00b2(Unicode 码)# string.isnumeric(): 如果 string 只包含数字则返回True, 全角数字, 中文数字# 如果 string 中包含小数, 以上三个方法均返回 False# 需求: 字符串逆序str = "abcdefg"str[::-1]
5.5 Public methods for advanced data types
    • Python built-in functions (that is, import you can call without importing the module)
      • len(item): Calculates the number of elements in the container;
      • del(item): delete variables;
      • max(item): Returns the maximum value of the element in the container, or, if it is a dictionary, only for key comparison;
      • min(item): Returns the minimum value of the element in the container;
    • Member operators
      • in: Returns True if the value is found in the specified sequence, otherwise, false;
      • not in: Returns True if no value is found in the specified sequence, or false;
# 完整的 for 循环语法for 变量 in 集合:    循环体代码else:    没有通过 break 退出循环, 循环结束后, 会执行的代码# 应用场景: 可以用于迭代遍历嵌套的数据类型(例如,一个包含多个字典的列表)# 需求: 要判断某一个字典中是否存在指定的值#      如果存在, 提示并且退出循环;#      如果不存在,在循环整体结束后,希望得到一个统一的提示;students = [    {"name": "张三",     "age": 18,     "gender": True,     "height": 1.69},     {"name": "李四",       "age": 23,       "gender": False,        "height": 1.74}]find_name = "李四"for stu_dict in students:    if stu_dict["name"] == find_name:        print("找到了 %s" % find_name)        breakelse:    print("抱歉,没有找到 %s" % find_name)print("循环结束!")


Resources:

    • Python Basics

Python Basics (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.