PYTHON path (Article 2): Basic PYTHON data types, article 2

Source: Internet
Author: User

PYTHON path (Article 2): Basic PYTHON data types, article 2

I. Basics
1. Encoding
UTF-8: Chinese occupies 3 bytes
GBK: Chinese occupies 2 bytes
Unicode, UTF-8, GBK relationships



2. input () function

n = input(" ")>>>hello>>>n>>>'hello'

  

n = input(" ")>>>10>>>n>>>'10'

  

Enter the number 10. Here n is the string '10', not the number 10.
If
N * 10 will be output
'123'
If you convert a string to a number, you can use Int ()

New_n = int (n)


3. while loop, continue, and break

While Condition Statement 1: Function Code 1 else Condition Statement 2: Function Code 2

  

While loop can also be added with else

Example: Use a while loop to input 1 2 3 4 5 6 8 9 10

n = 1while n < 11:    if n == 7 :        pass    else:        print(n)    n = n + 1

  


Or

count = 1while count < 11    if count == 7:        count = count + 1        continue     print(count)     count = count + 1

 

When the while statement is executed to if count = 7, the following print statement and count = count + 1 will not be executed in continue, and the while statement will be skipped again.

 

For example

 

count = 1while count < 11:    count = count + 1    continue    print('123')print('end')

  

Print ('20140901') can never be executed

Example 2

count = 1while count < 11:    count = count + 1    print(count)    break    print('123')print('end')

 

Output result

2end

  

Print ('200') cannot be executed here. When a break statement jumps out of the loop, only one loop can be executed, that is, the print (count) Statement is output once.
The complete execution process of this program is as follows:

 

Conclusion: continue terminates the current cycle for the next cycle, and break terminates the entire cycle.


4. Arithmetic Operators
+-*/% **//
Add, subtract, divide, and return the remainder to the integer operator.

5. String

Name = "Ma dashuai" if "Ma" in name: print ("OK") else: print ("error ")

  

'Ma dashuai 'is called a string
'Map' becomes a character
'Marath' or 'dash' is called a sub-string or a sub-sequence. Note that the characters here must be continuous, while 'marath' cannot be called a sub-string.

6. Member operation:
Determines whether a character is in or not in a string.

Name = "Ma dashuai" if "?" not in name: print ("OK") else: print ("error ")

  

7. Boolean Value

Both the if statement and the while statement use a Boolean value as the condition.
There are only two boolean values:
True or False

If condition judgment statement Function Code

 

The condition judgment statement will eventually generate a Boolean value, either True or False.

Name = "Ma dashuai" p = "?" not in nameprint (p) if p: print ("OK") else: print ("error ")

  

Output result

Trueok

  

Boolean operator: and or not

In Python's opinion, only the following content will be spoofed (Note that there is nothing in the colon brackets, not even spaces !) : False None 0 "" ''() [] {}

Everything else is interpreted as true!

 

 

For example

I = 10 while I: print ("I love learning! ") Print (" end ")

  


Output result

I love learning! I love learning! I love learning! I love learning! I love learning! I love learning! I love learning! I love learning! I love learning !... (Here, "I love learning" is always output ")

  


This program will always output "I love learning", unless you press CTRL + C to stop the program.
The print ("end") Statement will never be executed.
For example

I = 10 while I: print ("I love learning! ", I) I = I-1 print (" end ")

  


Output result

I love learning! 10. I love learning! 9. I love learning! 8. I love learning! 7. I love learning! 6. I love learning! 5. I love learning! 4. I love learning! 3. I love learning! 2. I love learning! 1end

  


By observing the number changes after "I love learning", we can see that the execution process of this loop ends when I loops to 0, that is, while 0:, 0 is False. Start execution
Print ("end") statement.

8. comparison operator: determines the size symbol.
= Equal
> Greater
<Less
> = Greater than or equal
<= Less than or equal
! = Not equal

 

9. Computing priority


Calculate the brackets first. We recommend that you use parentheses for complex expressions.
General execution sequence: from left to right
Boolean operation Priority
From high to low: not and or
Example:

user = 'nicholas'psswd ='123'v = user == 'nicholas' and passwd == '123' or 1 == 2 and pwd == '9876'print(v)

  

Analysis:
V = true and true or
In this case, you do not need to continue the calculation to obtain the true v result. You do not need to consider the priority of the Boolean operation. Note that this operation is left to right, ** instead of seeing and automatically performing operations, and then performing operations from left to right **

Some conclusions:
Left to right
(1) The first expression or
True or ----> returns True.
(2) The first expression and
True and ----> continue operation
(3) The first expression or
False or ----> continue operation
(4) The first expression and
False and ----> False

That is, ** short circuit logic **

Short Circuit Logic
The expression is calculated from left to right. If the left logic value of or is True, all short-circuited or expressions (whether and or) are output directly.
Or expression on the left.

The expression is calculated from left to right. If the logical value on the left side of "and" is False, all and expressions are short-circuited until or appears, and the expression on the left side of "and" is output
Or on the left side of the table to participate in the subsequent logical operations.

If the left side of or is False, or the left side of and is True, short-circuit logic cannot be used.

 

 

10. Value assignment operator
> = Simple value assignment operator c = a + B assigns the result of a + B to c
+ = Addition and value assignment operator c ++ = a is equivalent to c = c +
-= Subtraction value assignment operator c-= a is equivalent to c = c-
* = Multiplication and value assignment operator c * = a is equivalent to c = c *
/= Division assignment operator c/= a is equivalent to c = c/
% = Modulo assignment operator c % = a is equivalent to c = c %
** = Power assignment operator c ** = a is equivalent to c = c **
// = Take the Division assignment operator c // = a is equivalent to c = c //

 

Ii. Basic Data Types
(1) number int
A = 1
A = 2

Int (integer type)
In python3, int is used, and no range exists.
The int value in python2 has a fixed range.
Beyond a certain range, Python2 has a long integer or long
Python3 only contains integer type. int is used to cancel the long type.

* ① **, Int () converts a string to a number.

a = "123"type(a)b = int(a)print(b)type(b)

  

Output

<class 'str'>123<class 'int'>

 

Type () to view the variable type

However
A = "123n"
B = int ()
In this case, int () cannot be used to convert a string to a number.

num = "c"v = int(num,base = 16) print(v)


Note: v = int (num, base = 16) convert num to a hexadecimal number.

② Bit_lenght
The binary value of the current number, represented by at least n digits.

Age = 5r = age. bit_length () # binary of the current number, which occupies at least n bits to indicate print (r)

Output result

3

That is, 5 is expressed as 101 in binary, and must be expressed in at least three positions.



(2) string str
A = 'hello'
A = 'ssssdda'

Introduction to string functions

A -- capitalize ()

# Capital test = "lingou" v1 = test. capitalize () print (v1)

  

Output result

Lingou

  

B -- casefold (), lower ()

# Lower () all smaller writes
# Casefold () all the smaller writes, compared with the lower, casefold is more awesome, and many unknown (not English, such as French, German, etc.) are correspondingly smaller writes

# The lower () method is only ASCII encoded, that is, 'a-Z'. It is valid for other languages (not Chinese or English) to convert uppercase to lowercase, you can only use the casefold () method.

 

test = "LinGou"v2 = test.casefold( )print(v2)v3 =test.lower()print(v3)

Output result

lingoulingou

  

C -- center ()

# Center (): Set the width and center the content. "*" can be left blank by default.
# Here 30 is the total width, in bytes

 

test = "LinGou"v4 = test.center(30,"*" )print(v4)


Output result

************LinGou************

 

Blank

test = "LinGou"v5 = test.center(30 )print(v5)


Output result

          LinGou          

  


Note that the left and right sides of "LinGou" Have Blank bytes.

D -- count ()

# Count () searches for the substring and finds the occurrence times of the subsequence.

# Count (sub [, start [, end])

# Count (subsequence, start position of search, end position of search)

# Count (sub, start = None, end = None) None indicates that this parameter does not exist by default.

 

Test = "LinGouLinGengxin" v6 = test. count ("in") print (v6) v7 = test. count ("in",) # here, is the index code for the string "LinGouLinGengxin, from the third end to the sixth end # L I n G o u L I n G e n g x I n #0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 print (v7) v8 = test. count ("in", 3) # search for print (v8) from the first position)

Output result

302

  

E -- endswith (), startswith ()

# What does endswith () end?

# What does startswith () start?



test = "LinGouLinGengxin"v9 = test.endswith("in" )v10 = test.startswith("in")print(v9)print(v10)


Output result

 

TrueFalse

  

F -- find (), index ()

# Find () from the beginning, find the first one, and obtain its index location
# The index () function is the same as above. If the index cannot be found, an error is returned. We recommend that you use find ()

 

test = "LinGouLinGengxin"v11 = test.find("in" )v12 = test.find("XING" )v13 = test.index("in")# v14 = test.index("XING" )print(v11)print(v12)print(v13)#print(v14)

  

Output result

 

1-11

  

If you cancel the comments of v14 = test. index ("XING") and print (v14), an error is reported when you run the program.
Because index cannot find "XING"


G -- format ()

# Format () format, replace the placeholder in a string with the specified value
# {} Is a placeholder. Use format to replace the placeholder with the specified value.

 

test = "I am {name}"print(test)v15 = test.format(name = "LinGou" )print(v15)

  


Output result

I am {name}I am LinGou

  

-Second

test = "I am {name},age{a}"print(test)v16 = test.format(name = "LinGou",a = 19 )print(v16)

  

Output result

I am {name},age{a}I am LinGou,age19

  

-Third

test = "I am {0},age{1}"print(test)v17 = test.format("LinGou",19 )
print(v17)

 

Output result

I am {0},age{1}I am LinGou,age19

  

When Placeholders are represented by numbers, the specific name = "" is no longer required in the format function ""
Here we will replace them in sequence.

Fourth

# Format_map () format the input value
# Writing format {"name": "LinGou", "a": 19}

 

test = "I am {name},age {a}"print(test)v18 = test.format_map({"name":"LinGou","a":19} )v19 = test.format(name = "LinGou",a = "19")print(v18)print(v19)

  


Output result

I am {name},age {a}I am LinGou,age 19I am LinGou,age 19

  


F -- isalnum ()

# Whether the isalnum () string contains only letters and numbers

 

test = "LinGou"v20 = test.isalnum( )print(v20)test2 = "LinGou+"v21 = test2.isalnum( )print(v21)

  


Output result

TrueFalse

  

 

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.