python basic learning notes (1)

Keywords: Python Google Lambda C

It's better to have a c++ basis. Update one article every day.

This is a basic article.

1. operator
2. variable
3. Basic Input and Output
4. string
5. list
6. tuple
7. dictionary
8. set
9. Simply talk about the cycle or something.

1. operator

Special

a / b: Floating point number, a // b is an integer, discarding fraction a**b is the B power of a

And c // = a,c ** = a;

 

There's no & &, | |, in python!

For example, if(a and b), if(a or b) if (not a),

and, or, not instead

 

Among them are in and not in

You can use it in strings, lists, or tuple sequences to find out directly whether it exists

And is and is not, as the name implies.

 

2. variable

You don't have to declare variable types directly, such as x = 3

Change can also be directly converted

x = 'a'
y = 'b'
print(x)
print(y)
x = 1
y = 2
print(x)
print(y)

3. Basic Input and Output

Input for input

x = input("x:")
y = input("y:")
#print(x * y)  Error, because the input is returned as a string and should be converted to int type
print(int(x) * int(y))

Input indistinguishable single quotation marks and double quotation marks

Print ('hello nrunoob') # Use backslash () +n to escape special characters
Print (r'hello nrunoob') # adds an R before the string to indicate that the original string will not be escaped.“

Or \ n is written as \ n where \ denotes\

# Writeln
print( x )
print( y )

print('---------')
# Non-newline output
print( x, end=" " )#Represents a space at the end
print( y, end=" " )
print()'''

For print, connect strings and variables

x = "aaaa"
print("x:" ,x)

4. string

str = "wangpeibing"
print(str)
print(str[0:-1])
print(str[0])
print(str[2:5])#Intercept
print(str[2:])#The second character comes to the end
print(str*2)#Output two times
print(str+"Hello")#Connect

Can be found

if("wang" in str):
    print(1)

String formatting: an expression similar to c language

print("My name is %s and weight is %d kg!" % ('peibing', 21) )

5. list

Array similar to c language, with subscripts. It's characterized by brackets, slices, and strings.

a = [1,2,3]
b = [4 ,5 ,6]
print(a + b)#Connect
print(len(a))#length
print(a*4)
del a[0]#Delete the first element
print(a[-1])#The penultimate print(3 in a) for i in a :#Cyclic Iterative Output print(i)

You can also nest

c = [a,b]  #Nesting is similar to two-dimensional arrays
print(c)
print(c[1][0])

Some common methods

max(a)#List Maximum
min(a)#List Minimum
list.append(1)#a Add 1 at the end of
list.count(1)#a Number of occurrences in middle statistics
list.index(1)#Find the index location of the first match of a value from the list
list.insert(Subscript, obj)#Insert objects into the list. obj Self definition
list.pop([index=-1]])#Remove an element from the list (default last element) and return the value of that element
list.remove(obj)#Remove the first match of a value in the list
list.reverse()#Elements in the reverse list
list.clear()#clear list
list.copy()#Copy list

Sort, sort method is not suitable for the comparison of int and str types.

#list.sort(cmp=None, key=None, reverse=False)#Sort the original list
#reverse = True Descending order reverse = False Ascending order (default))
# Get the second element of the list
def takeSecond(elem):#function
    return elem[1]
# list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# Specify the second element sort
random.sort(key=takeSecond)
# Output class
print('Sort List:', random)
list=[ ["1","c++","demo"],  
           ["1","c","test"],  
           ["2","java",""],  
           ["8","golang","google"],  
           ["4","python","gil"],  
           ["5","swift","apple"]  
    ]  
list.sort(key=lambda ele:ele[0])# Sort by the first element
print(list)
list.sort(key=lambda ele:ele[1]) #Sort by the second element first
print(list)
list.sort(key=lambda ele:ele[1]+ele[0]) #Sort first by the second element, then by the first element
print(list)

6. tuple

Tuples and lists are similar in that they can't be modified, parentheses

There is only one element to add.

>>>tup1 = (50)
>>> type(tup1)     # No comma, type integer
<class 'int'>
 
>>> tup1 = (50,)
>>> type(tup1)     # Add commas and type tuples
<class 'tuple'>

If deleted, either all deleted, or not deleted.

Other methods are similar to lists.

List (tuple) converts tuples into lists; tuple (list) converts lists into tuples

7. dictionary

It is understood as map in c++. It's characterized by braces, and each key corresponds to the key value.

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
dict['Name'] = 'peibing' #Modify the corresponding key values
del dict['Name'] # Delete key 'Name' 
dict.clear() # Empty dictionary 
del dict # Delete dictionary

Note that keys must be immutable, so you can use numbers, strings or tuples instead of lists.

 

Some methods

Find length len(dict) 3

Display str(dict)

Judgment type(dict)

8. set

It's similar to the set in c++, mainly for weight removal.

You can use braces {} or set() functions to create collections. Note that creating an empty collection must use set() instead of {}, because {} is used to create an empty dictionary.

 

a = {'abracadabra'}#This time set There's a string value in it.
print (type(a))
print(a)
a = set('abracadabra')#At this time, he was prescribed for this. set The characters of this string are stored in turn.
print (type(a))
print(a)
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # aggregate a Including elements
{'r', 'd', 'b'}
>>> a | b                              # aggregate a or b All the elements contained in it
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # aggregate a and b Elements included
{'a', 'c'}
>>> a ^ b                              # Included at different times a and b Elements
{'r', 'd', 'b', 'm', 'z', 'l'}

 

>>>thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
>>> thisset.pop()
'Facebook'
>>> print(thisset)
{'Google', 'Taobao', 'Runoob'}

9. Simply talk about the cycle or something.

There are two for and while. The basic usage is similar to c, including break and continue. Let's look at while first.

i = 1
while i < 10:   
    i += 1
    if i%2 > 0:    
        continue
    print i        
 
i = 1
while 1:            # Cyclic condition 1 must hold
    print i         # Output 1~10
    i += 1
    if i > 10:     # When i Jump out of the cycle when it's over 10
        break

It's not hard to understand what's based on c++. Note that this is not bracketed. It's judged by indentation and some:

 

Next comes the for loop

Could be

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second example
   print (Current fruit :', fruit)

It can also be

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print ('Current fruit :', fruits[index])

range returns the number of a sequence.

for num in range(10,20):  # Iteration numbers between 10 and 20
   for i in range(2,num): # Iteration by factor
      if num%i == 0:      # Determine the first factor
         j=num/i          # Calculate the second factor
         print ('%d Be equal to %d * %d' % (num,i,j))
         break            # Jump out of the current loop
   else:                  # Cyclic else Part
      print (num, 'It's a prime number.')

Otheif is written as elif in python

Posted by kinaski on Fri, 01 Feb 2019 13:00:15 -0800