Python BASICS (II): python Basics

Source: Internet
Author: User
Tags arithmetic operators bitwise operators

Python BASICS (II): python Basics
Variable


Another way to assign values to variables

user = 'ljb'passwd = 'ljb123'user,passwd = 'ljb','ljb123'

 

 

Constant

Uppercase variable

MYSQL_CONNECTION = '192.168.1.1'

 

Pyc File

After the import module, the pyc file is generated in the corresponding directory, and the pyc file is a bytecode file.
Python call module Process
After the module is called, The pyc bytecode file will be generated, and the interpreter will execute the py program by recognizing the binary bytecode file.

Note:
Generate the pyc file directly in the current directory on py2
Py3 will create _ pycache _ directory under the production of similar files like cpython-35.pyc

 

Data Type 1 numeric


Int long float plural

2 Boolean Value


True or False
1 or 0
Judge whether values 1 and 0 represent True and False.
>>> 1 = True
True
>>> 0 = False
True

3 string


Common functions of strings:
• Remove white space

• Segmentation

• Length

• Index

• Slicing

Username = input ('inout you username ')

Username. strip () # Remove Blank

Name = 'ljb, kkk, lll'

Name. split (',') # split

Name [] # split, with 3rd to 4th characters

Name. center (40, '-') # The length is 40, and the name character is displayed in the center. The two sides are filled -.

Name. isdigit # determine whether the input character book is a number

Name. isalnum () # determine whether there are special characters

Name. startwith ('dsfdsa ') # judge whether the string starts with dsfdsa

Name. endwith ('sdf') # judge whether the string ends with sdfaf

Name. find ('l') # search for the l character in the string and print the position of the character.-1 is not displayed.

>>> name = 'langjianbin'>>> name.find('m')-1>>> name.find('j')4>>>

  

Example

#! /Usr/bin/env python #-*-codind: UTF-8-*-# Author: ljb # user = input ('username: ') # if user. strip () = 'ljb ': # blank # print ('Welcome') # name = 'ljb, langjb, langjianbin' # name1 = name. split (',') # separated by commas (,) # print (name1) # print ('| '. join (name1) # combine with | into a string name = 'lang jian bin' print (name. center (40, '-') # center print (''in name) # judge whether the string contains spaces print (name. capitalize () # uppercase msg = "Hello, my name is {Name}, age is { Ge} "print (msg. format (Name = 'ljb ', Age = 33) # format output msg2 = 'lang {0} Age {1}' print (msg2.format ('jianbin', 22 )) # format another method # age = input ('your age: ') # if age. isdigit (): # determine whether it is a number # age = int (age) # print (age) # else: # print ('invalid data ') name4 = 'adsfdg 'name5 = 'aaaddsfda' print (name4.isalnum () # determine whether a special character exists #! @ Print (name4.endswith ('dg ') print (name4.startswith ('sadsf') print (name4.upper () print (name5.lower ())View Code

 

+ Connect to strings

The following example indicates that three strings are connected, but the computer allocates three strings with three Memory Spaces, which occupies a lot of resources, therefore, in writing py programs, try to use such concatenated strings as few as possible.

>>> print ('hello' + '\n' + 'how are you')hellohow are you
4. List


List Common Operations

• Index

• Slicing

• Append

• Delete

• Length

• Slicing

• Loop

• Include

Name = ['ljbv ', 'dsg', '123']

Insert
Name. insert (2, 'kkk ') # insert kkk at 3rd locations

Append
Name. append ('aaa') # append aaa to the end of the list

Delete
Name. remove ('dsfg') # Delete the elements in the list that do not contain dsfg.

Del: delete data in memory
Del name [] # batch Delete (not only for list use, but also for other dictionary tuples)

Exercise
1. Write a list containing all the members of this group.

2. Insert two group members to the center.

3. Retrieve the list of persons in step 3-8.

4. Delete 7th People

5. Delete the two people you just joined at one time.

6. Add the team leader's name to the team leader's remarks.

7. Ask you to print a person by another person.

 

#! /Usr/bin/env python #-*-codind: UTF-8-*-# Author: ljb ''' 1 write a list, the list contains all members of this group. 2 is inserted to the center. Two members of the Group are named. 3 is taken out of the list of members in step 3. 4 is deleted. 7th People are deleted. 5 is deleted. The two members just joined are deleted. 6 is added to the group leader. note 7 you need to print a person by another person '''group _ list = ['ljb0 ', 'ljb1 ', 'ljb2', 'ljb3', 'ljb4', 'ljb5 ', 'ljb6', 'ljb7 '] print ('group member list :') print (group_list) print ('insert two group members: ') group_list.insert (4, 'zhangsan') # insert two group members group_list.insert (5, 'lisi ') # insert print (group_list) print ('retrieve the list of people 3-8 in the middle: ') print (group_list []) # print the 3-8 person list print ('delete 7th person ') group_list.remove (group_list [6]) # Delete 7th person print (group_list) # One-time deletion of the two people just added print ('delete the two people just added one-time delete') del group_list [4: 6] print (group_list) # Add Comment print for the group leader name ('add the group leader name with the team leader note') group_list.remove ('ljb0') group_list.insert (0, 'ljb0 _ zuzhang ') group_list [0] = 'ljb0 _ zuzhang' print (group_list) # print ('requires you to print a person by someone else ') print (group_list [0: 2]) # print (group_list [: 2]) for I in group_list [0: 2]: print (I)View Code

 


Determines whether an element exists in the list.

Name = [, 10] # print ('9 in name') if 9 in name: print ('9 in name') if 9 in name: num = name. count (9) # count 9 the number of occurrences print ('9 num is ', num) name. index (9) # search for 9 in the first position

 

 

Name. extend (name2) # expand to the new list

Name. reverse () # reverse display list

Name. sort () # can only be sorted in 2. This sorting method is not supported in 3.

Name. pop (2) # Delete the value of 2

Name. copy () # Only one layer of the list can be copied. If the list in the list is modified, both lists change.

If you need full copy, you need to import it to the copy module.

Import copy

Name4 = copy. depcopy (name)

When the list is assigned to the second variable, it is equivalent to a soft link.

 

Len (name) # list Length

Common operation exercises

 

#! /Usr/bin/env python #-*-codind: UTF-8-*-# Author: ljbimport copylist1 = ['ljb, 'lang ', 'zhangsan'] print (list1) list2 = list1.copy () # copy list1list3 = copy. deepcopy (list2) # Deep copy. When modifying the nested list, list2 [0] = 'ljb 'is not affected. # modify a value in list2, list1 will not change to list2 [5] [0] = 888888 # modify a value in the nested list. Both list1 and list2 will change (because the copy is a shared memory segment) print (list2) print (list3) for I in range (list1.count (9): first_9 = list1.index (9) list1 [first_9] = 9999999 # Find 9 in the list and change it to 999999 print (list1) for I in range (list1.count (34): first_34 = list1.index (34) # list1.remove (list1 [first_34]) list1.pop (first_34) #34 found in the list and then deleted print (list1) print (list2) list2.reverse () # reverse display # list3 = sorted (list2) # Cannot sorted in py3 # print (list3) print (list2) list1.extend (list2) # Add list2 extension to print (list1) after list)View Code

 

 

 

5 tuples

 

R = (, 5) # Read-only list r. count () # count the number of elements in the tuples r. index () # index position of the element

 

 

6 dictionaries

Common dictionary operations
• Index

• New

• Delete

• Key, value, and key-Value Pair

• Loop

• Length


Init_db.has_key # py2.x
Key in init_db # py3.x

Use this loop as little as possible in the dictionary loop, which occupies a large amount of resources.

For k. v in dict1: print (k, v) # Use for k in dict1: print (k, dict1 [k]) if you need a loop.

 


Exercise

#! /Usr/bin/env python #-*-codind: UTF-8-*-# Author: ljb # dictionary definition init_db = {1: {'name': 'ljb ', 'age': 22, 'add': 'heibei'}, 2: {'name': 'hangsan', 'age': 33, 'add ': 'beijing'} print (init_db) print (init_db [1]) # print valueinit_db [1] ['name'] = 'langjb 'with key 1 # change the value of a value name to langjbinit_db [1] ['qq'] = '2016' # Add a field init_db [1]. pop ('addr ') # Delete the addr field v = init_db.get (1) # Get the value of print (v) dic2 = {'name': '12dsfasdga ', 1: {'name': 'langjainbin'} init_db.update (dic2) # update the value of dic2 to init_db print (init_db) print (init_db.items ()) print (init_db.values () print (init_db.keys () # outputs (1) # only 2.X# 1 in init_db # 3.X equal init_db.has_key (1) print (init_db.setdefault ('3 ', 'langjianbin') # obtain a key value and set it to 'langjianbin' if it does not exist. If it exists, print (init_db) print (init_db.fromkeys ([, 4, (5, 6]), 'ddddd ') # fromkeys (seq [, values]) function is used to create New dictionary, which uses the elements in sequence seq as the dictionary key. value is the initial value corresponding to all keys in the dictionary. # For key in init_db: # print (key, init_db [key])View Code

 

 

 

Operation


Arithmetic Operators (+,-, *,/, %, **, // deploy the Integers of the integer return operator)

Comparison operator (= ,! =, <>,>, <, >=, <=)

Value assignment operator (=, + =,-=, * =,/=, % =, ** =, // =)

Logical operators (and, or, not)

Member operators (in, not in)

Identity operator (is, is not)

Bitwise operators

& Bitwise AND

| By bit or

^ Bitwise OR

~ Bitwise Inversion

> Left shift operation

<Right shift operation

 

Computing priority

 

 

 

While True Loop


Exercise

Automatically exits the loop for 100 times, and does not print between 50-60 times

#! /Usr/bin/env python #-*-codind: UTF-8-*-# Author: ljbcounter = 0 while True: counter + = 1 if counter> 50 and counter <60: continue print ('cycle Times ', counter) if counter = 100: print ('cycle ends 100 times, exit looping') break

 

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.