Python Basic Learning

Keywords: Python ascii

1. Use of preceding r

       The string in python beginning with R or R represents (non-escaped) the original string

      

2. Usage of u before string

In Python 2.x, u denotes unicode string, type unicode, and no u denotes byte string, type str

       In Python 3. x, all strings are Unicode strings, and the u prefix has no special meaning

       R and u can be used together, such as u r "abc"

3. Coding Notes

       If you want to write Chinese in Python 2's py file, you must add a comment that declares the file code. The purpose is to tell the Python interpreter to read the source code with UTF-8 code. Otherwise, Python 2 will use ASCII code by default.

 # -*- coding:utf-8 -*-

4. List and Tuple types

list and tuple are Python's built-in ordered sets, which are mutable and immutable

list is an ordered collection of elements that can be added and deleted at any time.

      

# -*- coding:utf-8 -*-

#1. Declaration list
s=["liwb","qnn"]

#2. Accessing the first element
s[0]

#3. Access the penultimate element
s[-1]

#4. Add an element after the last element
s.append("liyc")

#5. Insert values at index 1
s.insert(1,"liss")

#6. Delete the last element
s.pop()

#7. Delete the element with index 1
s.pop(1)

#8. Reassign a value to an index

s[1]="lyc"

#9. View the number of elements in the list
len(s)

tuple is an orderly collection that is immutable.

#1, statement
s=("liwb","qnn","liyc")
#2. Get the first element
s[0]
#3. Get the penultimate element
s[-1]

Attention:
1. Comparing with list, it can not add elements.
2. When there is only one element defined
               s=(1,)
3. tuple can have a list
               s=(1,2,["ad","cccc"])

5. dict and set types

dict: Dictionary, stored in key-value form, created in braces {} and separated by colons between keys and values

Exchange space for time, occupy large space, but query speed is fast, key: value, key is unique

#Create dict
d={"chen":60,"zhang":80}
print(d)
#Assignment
d['chen']=65
print(d)
#Value: get() method, which can set default values for it.
print(d.get("liu",0))
#Delete: You can use the pop method to delete the value and return the deleted element.
d['liu']=85
print(d)
d.pop('liu')
print(d)
#keys() and values() methods return keys and sets of values of the dictionary respectively. Although there is no specific order for key-value pairs, the order of results returned by the two methods is the same.
print(d.keys())
print(d.values())
#Dictionary merging: Two dictionaries can be merged using update().
d1={'a':100,'b':99}
d.update(d1)
print(d)
Set: Sets, similar to dict s, are also sets of keys, but do not store value s. Because key cannot be repeated, there is no duplicate key in set.

#Create set
s=set([1,2,3,4,5])
print s
#Additive elements
s.add(6)
print s
#If the element already exists in the set, adding it again will not work.
s.add(6)
print s
#Delete elements
s.remove(6)
print s
#set intersection
s1=set([3,5,7])
print s&s1
#Set union
print s|s1
#The difference between two sets
print s1-s
#XOR of Two Sets
print s^s1
#Determine whether a set is a subset of another set
print {1,3,5}.issubset(s)
#Determine whether a set is a superset of another set
print  s.issuperset({1,5})

6. Function returns multiple values

The fact that python functions return multiple values is an illusion. In fact, python functions still return a single value (tuple)

Grammatically, returning a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, assigning the corresponding value by location, so python's function returns multiple values in fact, returning a tuple

#For example, in games, it is often necessary to move from one point to another, give coordinates, displacements and angles, and then calculate new coordinates.
import math

def move(x, y, step, angle):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny

print(move(100, 100, 60, math.pi / 6))

7. PARAMETERS OF FUNCTIONS

There are four main ways to define python function parameters:

#The most common way of defining
def a(x, y):
    print x, y
#Functions with default values
def a(x,y=3):
    print x, y
#The parameter plus * means that the number of arguments of this function is variable, maybe 0 or n. The parameter receives a tuple.
def a(*args):
    print args
#The parameter plus ** means that the parameter receives a dict. When calling a function, the form of arg1 = value1 and arg2 = Value2 should be used.
def a(**kwargs):
    print kwargs

Variable parameters can be passed in directly: func(1, 2, 3), list or tuple can be assembled first, and then through * args: func(*(1, 2, 3));

Keyword parameters can be passed in directly: func(a=1, b=2), and dict can be assembled first, then through ** kw: func (** {a': 1,'b': 2}).

Using * args and ** kw is a Python idiom, and of course other parameter names can be used, but it's better to use idioms.



Posted by RightNow21 on Sun, 21 Apr 2019 13:45:35 -0700