Initial knowledge of Python (conditional judgment, loop control, cycle limit, common data types, string formatting, list common operations, binary operations, nested loops)

Source: Internet
Author: User

First day of study

1, Pycharm use encountered problems:

If you want to run program A, be sure to right-click to execute program a, not directly to the lower left corner of the run, then the other program may appear before running

Pycharm tips:

1, multi-line Select all, Shift+tab the whole forward indent a tab

2, multi-line Select all, tab whole backward indent a tab

3, multi-line Select all, ctrl+/comment The selected code, press ctrl+/comment again to cancel the selected code

4, Pycharm switch 3.5 and 2.7:file menu-settings-project pycharmpreject--project interpreter option, you can switch 2.7 and 3.5 versions

Reference: http://jingyan.baidu.com/article/fec4bce25f677df2618d8be8.html

python2.7 and 3.5 two versions installed simultaneously (Windows), Liniux with Python (2.6 need to upgrade to 2.7)

1. Download these 2 versions of the website

2, respectively installed to the root directory of the C drive, go to different names, such as c:\python2.7 c:\python3.5

When installing 3.5, there is a choice to check, you do not have to configure environment variables, automatically add environment variables

3, 2.7 When the installation is complete, you need to manually configure environment variables

【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】

     如:原来的值;C:\python27,切记前面有分号4, when the environment variable is configured, enter python under CMD to enter the version is 2.7, input Python3 Enter the version is 3.5Reference: http://jingyan.baidu.com/article/b87fe19e94ca95521935686e.html the main differences between the syntax of python2.7 and 3.5 3.5 in1.1/2 =0.5 (2.7 1/2=0) 2.print (), must be enclosed in parentheses (2.7 can be added without parentheses, or add) 3.raw_input gone, into input---here is a string, Input 2.7 in the equivalent of 3.5 in eval (input ()) 4.class Foo: The Classic class is gone, only the new class Foo (object) variable naming:1. Explicit (easy-to-understand) only letters, numbers, underscores 2.NUMS_OF_ALEX_GF = #下划线3. NUMSOFALEXGF = 2 #驼峰 Variable-life error (note):1. NAMES-OF-ALEX-GF = #错误-minus 2.5name = number cannot start, 3. The name special character cannot have a previous row of 4.name of teacher = cannot have spaces 5. keyword declares variable name [' and ', ' class ' ...]

Input (put the user input into memory)

Input 3.5 notation is input 2.7 is raw_input (2.7 input, the string must be a string, "sun" line, input sun No
# but raw_input can input jack)
# 3.5 of input equals 2.7 of raw_input ()

Process Control (if-else\while\for\break\continue)Requirements: Guess number lucky num num=6, guess the number is larger than 6, print guess the number is too big, guess the number is smaller than 6, print guess the number is too small,
# Three input errors, locking, required for use for
num = 6

For I in range (3):
s = Int (input (' Enter Number: ')) #必须放入循环里面才能实现多次
If s > num:
Print (' Too big ')
elif s < num:
Print (' Too small ')
Else
Print (' guessed right ')
break# jump out of the loop
else: #上面的循环正常执行完毕, else will execute if it is not properly exited (break), else will not execute
Print (' 3 input error, lock ')

The difference between continnue and break:

1, break is jumping out of the entire loop, after jumping out, while or for after the else will not be executed

2, continue not jump out of the entire cycle, but just jump out of the current cycle (also known as the current iteration), back to the loop condition judgment, continue the next cycle

#简单的嵌套循环 (two-layer or multilayer cycle)
# for J in Range (2):
# for I in range (10):
# if I<5:
# continue #跳出本次迭代, continue the next iteration
# if J>1:
# Break #跳出整个循环
# Print I

#如何实现一次跳出多层循环 (especially if multiple layers are dead loops), break only jumps one layer at a time

LOOP1 = 0
LOOP2 = 0
While True:
LOOP1 + = 1
Print "LOOP1:", LOOP1
Break_flag = False #设置一个跳出flag, used to control the outer loop jumping out
While True:
LOOP2 + = 1
if Loop2 = = 5:
Break_flag = True #跳出内循环前, first set the bounce flag to True
Break #跳出内循环 (first layer), but the outer loop is still in the loop
Print "LOOP2:", LOOP2
If Break_flag: #外循环跳出的条件具备了 Note that if the if must be the same as the inner loop, but not within the inner Loop code block
Print "Inside loop jumps out, outer loop also should jump out"
Break #跳出外循环

Circular Summary:

#输入正确跳出整个循环的的方式:

# 1 Break

# 2 Flag

#指定3次数锁定的方式

# 1 While count<3 count=0 count + = 1 Else:

# 2 for I in range (2) Else:

String

String formatting

#1字符串格式化--Recommend the following (not recommended plus splicing, wasted memory)%s string%d number (%s can also represent a string)%f floating-point numbers
Name = Raw_input ("Name:"). Strip () #strip () Remove the space parameter on both sides by default is to go to the space strip ("a") to remove the two sides of the "a"
Age = Raw_input ("Age:"). Strip ()
Job = Raw_input ("Job:"). Strip ()
msg = "" "
Information of%s:
name:%s
age:%s
job:%s
"" "% (name,name,age,job) #这里是4个参数, two name
Print msg
# output
# Information of Jack:
# Name:jack
# age:15
# Job:it

String splitting

Name_str = "Jack_tom_bob"
Print Name_str.split ("_") #[' Jack ', ' Tom ', ' Bob '] (string variable list, slicing a string)

List

#列表的作用是为了在一个变量中存储多个信息

Mutual transformation between #1列表和字符串 and meta-groups

Name_str = "Jack_tom_bob"

Print Name_str.split ("_") #[' Jack ', ' Tom ', ' Bob '] (string variable list)

Name_list = ["Jack", "+", "Jack", "Tom", "Jack", "all") #创建列表

Print tuple (name_list) # (' Jack ', ' + ', ' Jack ', ' Tom ', ' Jack ', ') ' #列表转换成元组

STR1 = "_". Join (Name_list) #jack_18_jack_jack_18 (list variable string)

Print str1

Print dir (name_list) #输出列表中包含的内置方法, focusing on not 2 underscores beginning with [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __delitem_ _ ', ' __delslice__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __getslice__ ', ' __ Gt__ ', ' __hash__ ', ' __iadd__ ', ' __imul__ ', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __reversed__ ', ' __rmul__ ', ' __setattr__ ', ' __setitem__ ', ' __sets ' lice__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ',

' Append ', ' count ', ' extend ', ' index ', ' Insert ', ' pop ', ' remove ', ' reverse ', ' sort ']

#列表切片:

Name_list = [' Jack ', ' + ', ' sex ', ' nan ', ' ff ', ' ee ', ' CC ']
Print (Name_list[:3])
Print (Name_list[1:4])
Print (Name_list[:-1])
Print (Name_list[:6:2])
Print (name_list[:])

Name_list = [' Jack ', ' + ', ' sex ', ' 18 ']
Name_list1 = [' ff ', ' ee ', ' CC ']

Name_list.append (' cc ')

Print (name_list = [' Jack ', ' + ', ' sex ', ' nan ', ' cc ') #增加元素到列表, last
Print (Name_list.count ('))   #18在列表中次数    2 times

Name_list.extend (Name_list1)
print (name_list) #[' Jack ', ' + ', ' sex ', ' + ', ' ff ', ' ee ', ' cc '] merge list name_list1 into nam_list

Print (Name_list.index (' sex ')) #列表中元素的索引 2

Name_list1 = [' ff ', ' ee ', ' CC ']
Name_list1.insert (1, ' CC ')
print (NAME_LIST1) # Inserts an element [' ff ', ' cc ', ' ee ', ' cc '] where the index is 1
Name_list1.pop ()       #删除最后一个元素 [' ff ', ' EE ']  
Name_list1.remove (' ff ')      #删除 "ff" this element  [' ee ', ' CC ']
Name_list1.reverse ()         #列表元素进行反转   [' cc ', ' ee ', ' FF ']
Name_list1.sort ()           #按照asci顺序排序列表的所有元素  [' cc ', ' ee ', ' FF ']


#需求: How to delete an element that has a list of elements such as 400w, for example: "Jack" reference http://www.cnblogs.com/wangtp/articles/5079839.html

For I in Range (Name_list.count ("Jack")):

# idea: First calculate the list of the string you want to delete "Jack" is the total number of count, if it is 3, then the time to traverse the list, delete remove3 times "Jack" can

Name_list.remove ("Jack")

Print Name_list

Name_list = ["Jack", "+", "Jack", "Jack", "18"]

For I in range (3):

Name_list.remove ("Jack")

Print Name_list

Meta-group

#元组和列表的区别: Tuples are read-only and cannot be modified

Tuple_name = (1,3) #创建元组

Print dir (tuple_name) #显示元组的内置方法

[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ' ', ' __getitem__ ', ' __getnewargs__ ', ' __getslice__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __rmul__ ', ' __setattr__ ', ' __ Sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' count ', ' index ']

Print List (tuple_name) #[1, 3] tuples converted to lists

Bit arithmetic

# a = 60 # 60 = 0011 1100
# b = 13 # 13 = 0000 1101
# c = 0
# c = A & B; # 12 = 0000 1100 bits and "&" 2 are true 1, the result is true 1
# print "line 1-value of C is", C
#
# c = A |        b # 61 = 0011 1101 or "|" Only one is true. 1, the result is true 1
# print "line 2-value of C is", C
#
# c = a ^ b; # 49 = 0011 0001 xor "^" only one True 11 false 0, the result is true 1
# print "line 3-value of C is", C
#
# c = ~a; # -61 = 1100 0011 #相当于1取反是0,, 0 inversion is 1
# print "line 4-value of C is", C
#
# c = a << 2; # 1111 = 0000 #左移2位
# print "line 5-value of C is", C
#
# c = a >> 2; # = 0000 1111 #右移两位
# print "line 6-value of C is", C

File operations (write, read, append, cursor move)

Open File : # #

File_obj = File ("path", "mode") #

obj = open ("File path", "mode") # #

the mode of opening the file is : # #

R, open the file as read-only #

W, open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. #

A, open a file for append. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. #

w+, open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. # #

read the contents of the file: # #

Load all content into memory at once # Obj.read () # # # #

Load all content into memory at once and split into strings based on rows, each line string as an element of the list # obj.readlines () # # # #

Reads only one row of data at a time, traversing each line of the file # for lines in obj:# # print # # Write the contents of the file: # obj.write (' content ')

close File handle: # #

Obj.close () # obj = open ("Log", "W") #

Write a schema create a new file object

Obj.write ("first\n") #

Write 2 lines of text

Obj.write ("Second line\n") #\n is line break

obj = open ("Log", "a") #追加的模式往文件追加2行 obj.write ("third\n") #追加写入2行文本 obj.write ("Fourth line\n")

obj = open ("Log", "R") #只读的模式, reads the contents of the file into memory #

Print Obj.read () #读出文件所有的内容 #

Print Obj.readlines () #每个行字符串作为列表的一个元素, including line breaks (spaces and newline characters can be removed with strip) #[' first\n ', ' second line\n ', ' third\n ', ' fourth line\n ‘]

For i in obj:

Print I, #这里加上逗号, can remove the blank line print Obj.tell () #40 display the current position of the cursor, is the 40th character

# cursor positioning of the file #

Obj.seek (0) cursor back at the beginning of the file #

Obj.tell () Displays the current cursor position in the file #

#文件的光标的移动

# obj.seek (0) #光标回到文件最开始处, the second argument can not be written, the default is the start of a file 0

# Obj.seek (0,0) #光标回到文件最开始处

Obj.seek (12,0) #光标回到以文件0开始, 12th character

Print Obj.tell ()

Obj.seek (6,1) #光标从当前位置1开始, 6th character

Print Obj.tell ()

Obj.seek (3,2) #光标从文件最后2开始, 3rd character

Print Obj.tell () #0 displays the current position of the cursor, which is the No. 0 character

# Seek Summary

# second argument, 0 for file start, 1 for file current, 2 for end of file

# The first argument, the number of characters representing the displacement










Initial knowledge of Python (conditional judgment, loop control, cycle limit, common data types, string formatting, list common operations, binary operations, nested loops)

Related Article

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.