This is the 15th day of my participation in the August More Text Challenge

Now that you know the history of Python, let’s start with the basics of Python. If you have studied other programming languages, you may want to skip this article

PyCharm uses diagrams

You can develop Python with your own choice of tools, but the PyCharm interface I recommend is the same as WebStorm. If you have worked on the front end, you will be familiar with it

To download and install the software, you can read this article:

http://blog.csdn.net/qq_29883591/article/details/52664478

Hello world File->New Project hello World File->New Project

Here, select your Python installation path and click Create to complete the creation. With the project created, start creating our file

Let me run this one last time

variable

What is a variable?

To give you an official answer:

A variable refers to the name of a value of each type. When you use the value again, you can refer to the name

The syntax for defining a variable in Python:

Name =input(" please input your name ")Copy the code

In this way, we have successfully defined a variable. Unlike other programming languages, the variable has no data type modifier. This is the dynamic type we talked about earlier, where the type of the variable is determined by its value

Q: Poof, one more question: what the hell is that #

A: In Python, # is a single line comment, and multiple lines comment content.

Q: What is input

A: Python3. X input accepts user input, which in python3.X asks you to enter a name and assign it to the variable name. In Python2. X raw_input

Naming rules for variables:

  1. Variable names can only be any combination of letters, numbers, or underscores
  2. The first character of a variable name cannot be a number
  3. You cannot use keywords in Python

Python3 has a total of 33 keywords, none of which can be used as variable names: False/None/True/and/as/assert/break/class/continue/def/del/elif/else/except/finally/for/from/global/if/import/in/nonloc al/lambda/is/not/or/pass/raise/return/try/while/with/yield

The data type

Data types in Python:

  1. Number (Number)Python3 supports three different numeric types: int, float, and complex
  2. Boolean value (true or false)
  3. String(String)
  4. The List (List)
  5. The Tuple (a Tuple)
  6. Sets (set)
  7. The Dictionary (Dictionary)

Story: Why is it called a Boolean value? In honor of a man whose name was Boolean, he published the Mathematical Analysis of Logic, a Study of the Laws of Thought named Boolean algebra after him, because of his special contribution to symbolic logic operations, many computer languages call logical operations Boolean operations, the results of operations called Boolean values

Use type() to view data types

Copyright (c) 2009 Microsoft Windows [Version 6.1.7601] all Rights Reserved. All rights reserved. C:\Users\Administrator> Python Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", >>> type(" zhang SAN ") <class 'STR '> >>>Copy the code

In addition, we can use isinstance to determine:

a = 111
isinstance(a, int)
True
Copy the code

Isinstance differs from type in that:

class A:
    pass

class B(A) :
    pass

print(isinstance(A(),A)) # True
print(isinstance(B(),A)) # True
print(type(A())==A)      # True
print(type(B())==A)      # False
#type() does not consider subclasses to be a superclass type. Isinstance () considers a subclass to be a superclass type.
Copy the code

Of course, data types can also be converted

>>> type("Zhang")
<class 'str'> > > >type(int("18"))
<class 'int'> > > >Copy the code

Data type conversion

Data type conversion
# number="1"
# number=1
# number="True"
# number="aa,bb,cc"
# number=65
number="A"
print(type(number))
print(number)
# number1=int(number) # convert to int
# number1=float(number) # convert to float
# number1= STR (number) # convert to STR
# number1=bool(number) # convert to STR
# number1=list(number) # Convert to a list
# number1= CHR (number) # Convert an integer to a character
# number1=ord(number) # Convert a character to its integer value
print(type(number1))
print(number1)
Copy the code

string

A String is a String of characters consisting of digits, letters, and underscores. It is usually enclosed with a pair of single or double or triple quotation marks. Usually denoted as: s = “a1A2 ···an” it is the data type that represents text in programming languages. Escape characters: Python escapes characters with a backslash () when special characters are needed in a character.

Python lists of strings can be evaluated in two order:

  1. Indexing from left to right starts at 0 by default, and the maximum range is 1 less in string length
  2. Index from right to left starts at -1 by default, and the maximum range is at the beginning of the string

If you want to extract a substring from a string, you can use the variable [header subscript: tail subscript] to truncate the corresponding string, where the subscript starts at 0 and can be positive or negative, and the subscript can be null to indicate the end or the end. Such as:

s = 'ilovepython'
The result of # s[1:5] is love.

Copy the code

The new string obtained using the above method is “love”. The value of S [1] is L, and that of S [5] is P. It is not difficult to notice that the result above contains the value of the left boundary (s[1] ‘s value L), but not the value of the right boundary (s[5] value P). The plus sign (+) is the string concatenation operator, and the asterisk (*) is a repeat operation. Examples are as follows:

str = 'Hello World! '
str=R"helloPython"
print('ha' not in str)
print(str)          Print the full string
print(str[0])        # Print the first character in the string
print(str[2:5])      Print the string between the third and fifth strings in the string
print(str[2:)# print the string beginning with the third character
print(str * 2 )      Print the string twice
print(str + "TEST")  Print the connection string
# the full version
str=" Hello python ll5 "
print(str.capitalize()) Converts the first character of the string to uppercase
The #Python count() method counts the number of occurrences of a character in a string. Optional arguments are the start and end positions of the string search.
print(str.count('l'.0.10)) 
Sub - the substring of the search start - the position where the search of the string begins. Default is the first character, the first character index value is 0. End - The position in the string where the search ends. The index of the first character in a character is 0. Defaults to the last position in the string. ' ' '
print(str.count('l'))
print(str.endswith('l')) # return true and false if l ends
print(str.endswith('o'.0.5)) # What ends in the specified range
print(str.find('wl')) 
print(str.index('l')) # Same as the find() method, except an exception is raised if STR is not in the string.
print(str.isalnum()) # Return True if the string has at least one character and all characters are alphanumeric, otherwise return False(including all other symbols)
print(str.isalpha()) # Return True if the string has at least one character and all characters are letters, False otherwise
print(str.isdigit()) # Return True if string contains only numbers, False otherwise..
print(len(str)) # return the length of the string
print(str.lower()) Convert all uppercase characters in the string to lowercase.
print(str.upper()) Convert lowercase characters in a string to uppercase
print(str.swapcase()) # convert uppercase to lowercase in string, lowercase to uppercase
print(str.lstrip()) # Truncate the space or specified character to the left of the string.
print(str.rstrip()) # Delete the space at the end of the string string.
print(str.strip(str)) # execute lstrip() and rstrip() on strings
Copy the code

Boolean value

Boolean values are exactly the same as Boolean algebra. A Boolean value has only two values, either True or False. In Python, we can use True or False to represent a Boolean value (sensitive to case), or we can calculate it using Boolean operations:

>>> True
True
>>> False
False
>>> 3 > 2
True
>>> 3 > 5
False
Copy the code

Boolean values can be computed with and, OR, and not. And is and only True if everything is True: Booleans are often used in conditional judgments

The list of

List is the most frequently used data type in Python. Lists are identified by [], python’s most common composite data type. There should be no doubt what a list is. For example, if A goat is a sheep, then sheep in sheep village should be represented by a list. List is a built-in data type in Python where elements can be added and removed at any time.

list1 = ['Google'.'Baidu'.1997.2000];

print(list1[-2]) # Read from the right, starting at -1
print(list1[1:)Output all elements starting with the second element
print(len(list1)) # return the list length
print([1.2.3] + [4.5.6]) # combination
print(list1*4) # repeat
print(1997 in list1) Whether the element exists in the list
Iteration #
for x in list1: 
    print(x)
# list nesting
list2=[1.2.3]    
list1=["baidu",list2]
print(list1[1] [5]) # 2 output
print(max([1.2.3])) Output # 3
print(min([1.2.3])) Output 1 #
yangcun=["Jubilant"."Beautiful Goat."."Lethargy"]Define a list
print(yangcun)
List base operations
list = [ 'runoob'.786 , 2.23.'john'.70.2 ]
tinylist = [123.'john']
# list.clear()
# list.reverse()
print(list)               Print the complete list
print(list[0])            Print the first element of the list
print(list[1:3])          Print the second to third elements
print(list[2:)Print all elements from the third to the end of the list
print(tinylist * 2)       Print the list twice
print(list + tinylist)    Print a list of combinations
Copy the code

Q: How do I get an element of a list?

A: By indexing, notice that the index starts at 0 yangcun[0]

Q: can indexes be negative

A: If yangcun[-1] takes the last element, and so on

Q: What if new sheep come to the sheep village

Answer: Yangcun. Append (” Boiling Sheep “)

Q: can the new lamb choose his position

Insert (1,” Boiling Sheep “) so Boiling Sheep runs to Beautiful Sheep

Ask: the name of beautiful sheep sheep hit wrong, how to do

A: Don’t worry, Yangcun [1]=” Mei Yangyang “will do

Ask: grey Wolf is coming, I want to find out where Xiyangyang is, how to find the index of Xiyangyang

Answer: Yangcu.index (” Yangyangcun “)

Ask: that in case there are sheep captured by grey Wolf sheep village sheep less how to express

Yangcu.pop () deletes the element at the end of the list. Yangcu.pop (1) deletes the element at the specified index position

Q: Yangcun [1:3] What is this grammar

A: This is sharding in Python, which means taking elements with indexes 1 and 2.

After a series of questions you should get the basic list operation, of course, this is not all, you can enter the list name. Look at the tips below and try any of the above methods.

yangcun=["Jubilant"."Beautiful Goat."."Lethargy"["The lamb 1"."The lamb 2"]]
xinyangcun=yangcun.copy();
yangcun2=yangcun[:];
yangcun[3] [0] ="Little Lamb"
print(xinyangcun[3] [0]) # q: What is the output result
print(yangcun2) # q: Output what
Copy the code

Understand the list:

  1. Xinyangcun only points to the same memory address as Yangcun, but when the contents of this space change, the output will definitely change. In turn, if you change the value of Xinyangcun, yangcun will also change.
  2. The output[" Happy Goat "," Beautiful Goat "," Lazy ",[" Lamb 1"," Lamb 2"]]

tuples

An element is conceptually the same as a list. The main difference is that tuples cannot be modified once created, so they can be read-only lists.

yangcun=("Jubilant"."Beautiful Goat."."Lethargy")
print(yangcun[0]) # pleasant goat
# Tuple base operation
tuple = ( 'runoob'.786 , 2.23.'john'.70.2 )
tinytuple = (123.'john')

print(tuple)               Output the full tuple
print(tuple[0])            Print the first element of the tuple
print(tuple[1:3])          Print the second to third elements
print(tuple[2:)Print all elements from the third to the end of the list
print(tinytuple * 2)       Output tuple twice
print(tuple + tinytuple)   Print the tuple of the composition
Copy the code

So the difference between tuples and lists:

  1. Tuples are immutable, lists are mutable. Tuples are mutable, lists are mutable.
  2. Tuples usually consist of different data, while lists are queues of the same type of data. Tuples represent structures, while lists represent orders.
  3. You can’t use lists as dictionary keys, whereas tuples can.
  4. Because tuples support smaller operations than lists, tuples are slightly faster than lists
A = (1, 2) = b (4, 5) c = c = {a: "tuples"} {b: "a list"}Copy the code

Some common methods for strings

title=" hello world "

print(title.capitalize()) #Hello world capitalized
print(title.casefold()) Convert all to lowercase
print(title.upper()) Convert all to uppercase
print(title.swapcase()) Case transposition
print(title.center(30."-")) #---------hello world----------
print(title.find("h")) If no index is found, return -1
print(title.index('h'))# return index
print(title.endswith("com"))# check whether com ends with False
print(title.strip()) # removes the specified characters around the string, writes the specified characters to the parentheses, defaults to Spaces
print(len(title)) # String length
print(title.count('l'))# String statistics, number of occurrences
print(title.replace('l'.'a'))  # replace string
print(title.split(' ')) # string separation
print("aa".isalpha())  # Is not an English letter, returns a Boolean value
print("111".isdigit())  # Is a number, returns a Boolean value
print('_name'.isidentifier())  # is a valid variable name that returns a Boolean value
print('aaaAAAA'.islower())  # is a lowercase character that returns a Boolean value
print('AAAAA'.isupper())  # is a capital letter and returns a Boolean value

Copy the code

The dictionary

Dictionary A key-value data type, used like the dictionary we used in school, which uses strokes and letters to look up the details of the corresponding page. No subscripts are unordered in the dictionary

The difference between a list and a dictionary is that elements in a dictionary are accessed by keys, not by indexes. The dictionary creation format is as follows: Note that the keys must be unique

d={key1:value1,key2:value2}
# dictionary base operations
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john'.'code':6734.'dept': 'sales'}


print(dict['one'])          # output the value with the key 'one'
print(dict[2])              Print the value of key 2
print(tinydict)             Print the complete dictionary
print(tinydict.keys())      Print all keys
print(tinydict.values())    Print all values

moviesdict={
    "Youth":"Huang Xuan"."Psychological crime":"Deng chao"
}
print(moviesdict.items())
print(moviesdict.keys())
print(moviesdict.values())
print("Youth" in moviesdict) Whether the specified key exists in the list
# print(moviesdict.pop(" "))# print(moviesdict.pop(" "))# print(moviesdict.pop(" ")
# print(moviesdict.keys())
print(moviesdict.popitem()) # Delete the trailing element
# moviesdict.clear()
print(moviesdict.keys()) 
print(moviesdict.get("Youth")) Select value from key
Copy the code

Dictionary common methods:

yang={
    "y1":"Beautiful Goat."."y2":"Lethargy"."y3":"Jubilant"."y4":Boiling Sheep
}
# add
yang["y5"] ="Slow Sheep"
Value by key
print(yang["y1"])
# modified
yang["y1"] ="Beautiful Goat 1"
print(yang)
# remove
del yang["y1"]
print(yang)
# to find
print(yang.get("y2"))
print(yang.keys());Get all keys
print(yang.items())
Copy the code

Set the set

Collection like abandoned the value, the only key dictionary, are not allowed to repeat between key and key, if you just want to know whether a certain element existed and don’t care about others, using the collection is a very good choice, if you need additional information for key, it is recommended to use a dictionary set is unordered collection, there can be no duplicate elements, also cannot sort, Sort () is not available. A set verifies the existence of elements faster than a list. Note: To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary. Create a set: myset = {3, 4, 5, 1} type(myset) output set

The operator

Class of Python operators:

  1. Arithmetic operator (+ – * // % ** //)
  2. The relational operator (==! = > < >= <=)
  3. Assignment operator (= += -= *= /= %= **= //=)
  4. Logical operators (and or not)
  5. An operator (& | ^ ~ < < > >)
  6. Member operator (in not in)
  7. Identity operator (is is not)

** : power, returns the y power of x // : returns the integer part of the quotient in: Returns True if a value is found in the specified sequence, otherwise false is: Is determines whether two identifiers refer to an object

Branch statements

Branching is also called flow control, which means that a computer is stupid, because if you don’t tell it what to do, it will do it line by line from the first line, but all of our programs have logic, which is telling the computer what to do with the code that we write.

If you are too lazy to read the long list above, take a look at the picture below (Happy Goat and Big Big Wolf) to help you understand the branching statements better

huitailang="Big Big Wolf"

# Basic usage
# hongtailang=input(" please input ")
# if hongtailang==" eat sheep ":
# # pit
# print(" Red Wolf makes Grey Wolf go to catch sheep ")
# print(" la la la la la la la ")
# else:
# print(" Go get the sheep yourself ")
# print("lalla")

If () {if (); if ()
# Yang =input(" # Yang =input ")
# if Yang ==" Yang Yang ":
# print(" Escape successfully ")
# elif Yang ==" Yang ":
# print(" Wait for the jubilant to come to her ")
# elif Yang ==" lazy ":
# print (" cry ")
# else:
# print(" eat ")

# Branch nesting: It is not recommended to nest too many layers 3
hongtailang=input("Please enter red Wolf if you want to eat sheep :")
if hongtailang=="Sheep":
    yang=input("Which sheep did grey Wolf catch?")
    if yang=="Jubilant":
        print("A successful escape.")
    elif yang=="Beautiful Goat.":
        print("Wait for the jubilee to come to her.")
    elif yang=="Lethargy":
        print("Cry")
    else:
        print("Eat") 
else:
    print("Grey Wolf catches the sheep by himself.")    

Copy the code

What would you do if you tried it in code

huitailang="Big Big Wolf"
hongtailang=input("Does the red Wolf want to eat the sheep?")
if hongtailang=="Sheep":
    print("Red Wolf drives Grey Wolf to catch sheep.")
else:
    print("{name} catch the sheep yourself".format(name=huitailang))
Copy the code

The syntax doesn’t change much from other languages, so indentation is pretty good when you get used to it

Q: Can the indentation of print or the colon be deleted

Answer: can not delete, will report syntax error

Q: Is there else if in Python as in other languages?

A: Of course, but not else if, a short elif, note that elif cannot be used alone, it must be used with if

Do you understand the above “if”? Let’s add some ingredients to make an “if” nesting. Scenario: When Grey Wolf meets Happy Goat

huitailang="Big Big Wolf"
xiyangyang="Jubilant"
hongtailang=input("Does the red Wolf want to eat the sheep?")
if hongtailang=="Sheep":
    print("Red Wolf drives Grey Wolf to catch sheep.")
else:
    print("{name} catch the sheep yourself".format(name=huitailang))
    yang=input("Which sheep to catch?")
    if yang==xiyangyang:
        print("A successful escape.")
    else:
        print("Catch the sheep")

Copy the code

Looping statements

A loop is easy to understand. A loop is a repetition, a repetition of a statement

The first is the while loop

Let’s write down the code and execute it with me

while True:
    print("Execute when the condition is established.")
Copy the code

What do you see? In order to let you understand the role of this loop condition, we found that accidentally wrote an infinite loop, which is also the taboo of writing loops, how to avoid the infinite loop, is also very simple, in the loop body must have the code to change the loop condition.

In jubilant and Big Big Wolf, when does the big Big Wolf catch the sheep, remember? Is it rage 3? So let’s simulate it in code

nuqizhi=0; While nuqizhi<3: nuqizhi= nuqizhi + 1 print(" nuqizhi= "+ STR (nuqizhi)) if nuqizhi==3: print(" nuqizhi= ")Copy the code

Second: the for loop

Let’s use for to count the sheep in the sheep village

Yangcun =[" Happy Goat "," lazy "," beautiful Goat "," Boiling Goat "] for Yang in Yangcun: Print (Yang)Copy the code

Output result: happy goat lazy beautiful sheep sheep boiling sheep sheep

How to jump a loop (break, continue)

Yangcun =[" Happy Goat "," lazy "," beautiful goat "," Boiling goat "] for Yang in Yangcun: if Yang ==" Beautiful goat ": break; print(yang)Copy the code

The output: cheerful and lazy

Yangcun =[" Happy Goat "," lazy "," beautiful goat "," Boiling goat "] for Yang in Yangcun: if Yang ==" Beautiful goat ": continue; print(yang)Copy the code

Output results: Happy goat lazy boiling sheep

The execution of Python

In the previous chapter we introduced compiled languages, interpreted languages, and of course hybrid languages such as JAVA. JAVA execution is compiled into bytecode files by the compiler and then interpreted into machine files by the interpreter at runtime, so JAVA is a compiled and interpreted language.

And python is an interpreted language, so have you noticed that the.pyc file (in the __pycache__ folder in the installation path) actually compiles Python when you run it, just like JAVA, which compiles before execution and stores the compiled results in memory, And then write it to the.pyc file. The second run will read the.pyc file first, and if it is not available, the compile write step will be performed.

Just a quick summary

You should get the basics of Python syntax, data types, branching, and loops above