Introduction to Python Notes (Basic) __python

Source: Internet
Author: User
Tags delete key stdin sublime text timedelta
Getting Started with Python 3 notes A brief introduction to Python

Python is a high-level combination of interpretative, compiler, interactive, and object-oriented scripting languages. Python's design is highly readable and has a more distinctive grammatical structure than other languages, often using English keywords and some punctuation in other languages.
   Python is an interpreted language: this means that there is no compilation in the development process. Similar to PHP and Perl languages. Python is an interactive language: This means that you can directly interact with a Python prompt to write your program. Python is an object-oriented language: This means that Python supports object-oriented style or code encapsulation in object programming techniques. Python is the language of beginners: Python is a great language for novice programmers, and it supports a wide range of application development, from simple word processing to WWW browsers to gaming. python environment to build the operating system: Win8 64bit Download the response to the win platform of the Python installation package download link, will download the installation package as prompted to install. Environment variable Configuration
Programs and executables can be in many directories, and these paths are most likely not in the search path where the operating system provides executable files. Python Chinese Code

On the support of Chinese encoding in sublime text
When you use sublime to build a Python program, you sometimes encounter decode Error-output not utf-8 or cp936.
The reason is that Python compiles the stream after the run is encoded in a different way than the Sublime decoding, Sublime ctrl+b build a python program,
The output is not cp936, which shows that the Python build in Sublime is the default received encoding for cp936.
If your Python program is UTF-8 encoded and has Chinese character output, sublime will report the error of not cp936.
If the report is output not utf-8, it means that Python sends the output to the sublime by default after compiling the source code cp936.
The default receive encoding in Sublime is utf-8. After receiving the Python output, Sublime text attempts to encode cp936 encoded streams in UTF-8 encoding.
When there is no Chinese characters in the cp936 encoded stream, Utf-8 decoding is not an error, when the cp936 encoded stream has Chinese characters, because the man set in the cp936 and Utf-8 encoding is incompatible, so with the Utf-8 decoding will be an error.
The key to solving the problem is to figure out the encoding of your Python program and the code specified in the sublime Python build.
Python sublime decode errorcp936 utf-8 output not utf-8utf-8 cp936 output not cp936 For example, your Python code has coded format is utf-8, now sublime Wrong to output not cp936, set the Python build encoding in sublime as Utf-8, and vice versa. Python.sublime-build
Location:
Sublime Text 2:sublimetext2/data/packages/python/python.sublime-build
Sublime Text 3:sublimetext3/packages/python.sublime-package
Python.sublime-build file:

{
"cmd": ["Python", "-U", "$file"],
"File_regex": "^[]*file/" (... *?) /", line ([0-9]*)",
"selector": "Source.python",
"encoding": "Utf-8"
}
input function Problem solving

The interactive question about user input is resolved in sublime text.
Sublime3 compiles the Python program eoferror:eof when reading a line.
Specific solutions have been found on the web, links here, hoping to help you. In general, it is: Download a SUBLIMEREPL plugin, put the plug-in in the position shown in the following figure to select the following figure:

Solution

#!/usr/bin/python
Print ("dddd China")
if True:
    print ("True");
    Print (' True hello ')
else:
    print ("false");
    Print ("dddd China")

word = ' word '
sentence = ' This is a sentence. "
paragraph =" "This is a paragraph.
contains more than one statement "" "
print (paragraph) '
annotation
multiline annotation
'
item_one=1;
item_two=2;
item_three=4 Total
= item_one +
        Item_two + \
        item_three;

Print (total);

Import sys; 
x = ' Runoob '; 
Sys.stdout.write (x + ' \ n ')

import sys
print (sys.stdin.encoding);
Print (sys.stdout.encoding);


x = ' Runoob '; 
Sys.stdout.write (x + ' \ n ')
#input ("\n\npress the" enter key to exit.) )
#测试输入效果
xx=input ("\n\npress the Enter key to exit:");
Print ("current character" +xx);
a reference tutorial for basic syntax

Write link content here
This tutorial is mainly oriented to Python2, so some of the python3 in the different places, I give the following code case: Data type

Import sys print (sys.stdin.encoding);


Print (sys.stdout.encoding);  #自动类型包装 counter = 100 # Assignment integer variable miles = 1000.0 # floating-point name = ' John ' # string print (counter) print (miles) print (name) A, B,
c = 1, 2, "John" Print (a) print (b) print (c) # #Number numeric data type is used to store numeric values.
VAR1 = 1 Print (var1) var2 = # #String Strings or strings (string) is a string of characters that consist of numbers, letters, and underscores. str = ' Hello world! ' Print (str) # Output full string print (Str[0]) # The first character in the output string print (Str[2:5]) # The string print between the third and fifth in the output string (str [2:]) # output string print starting from third character (STR * 2) # output string two times print (str + "TEST") # Output concatenated string # #list list = [' ABCD ', 786, 2.23, ' John ', 70 .2] Tinylist = [123, ' John '] Print List # output full list print List[0] # The first element of the output list print List[1:3] # prints the second to third element print list[2
:] # Output from the third start to the end of the list all elements print Tinylist * 2 # Output List two times # #元组 tou1 = (' 11 ', ' 33 ', ' 23 ', ' 1234124 ');
Print (TOU1);
Tup1 = (' Physics ', ' Chemistry ', 1997, 2000);

Tup2 = (1, 2, 3, 4, 5, 6, 7);

Print ("tup1[0]:", tup1[0]) print ("Tup2[1:5]:", Tup2[1:5]) tup3=tup1+tup2;

Print (TUP3); #任意无符号的对象,Separated by commas by default is tuple print (' abc ', -4.24E93, 18+6.6j, ' xyz ');
X, y = 1, 2;


Print ("Value of X, y:", x,y);

Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' A '; Del dict[' Name '];     # The DELETE key is an entry for ' Name ' #dict. Clear ();        # Empty The dictionary all entries #del dict;
# Delete Dictionary print ("dict[' age ']:", dict[' age '); #print ("dict[' School ']:", dict[' School ']);
operatorArithmetic operator comparison (relational) operator assignment operator logical operator bitwise operator MEMBER operator operator Precedence
# #算术运算符 A = b = ten c = 0 c = a + B print ("1-c value is:", c) c = a-b print ("2-c value is:", c) c = A * b print ("3-c Value is: ", c) c = A/b (" 4-c value is: ", c) C = a% B print (" 5-c value is: ", c) # Modify variable A, B., c a = 2 b = 3 C = A**b PR Int ("6-c value is:", c) A = ten b = 5 c = a//b print ("7-c value is:", c) # #比较运算符 a = b = Ten c = 0 if (a = = B): Prin  T ("1-a equals B") Else:print ("1-a not equal to B") if (a!= b): Print ("2-a is not equal to B") Else:print ("2-a equals B") if
   (A < B): print ("4-a less than B") Else:print ("4-a is greater than or equal to B") if (a > B): Print ("5-a greater than B") Else:
Print ("5-a less than equal to B") # modifies the value of variables A and b = 5;
b = 20; if (a <= b): print ("6-a less than equal to B") Else:print ("6-a greater than B") if (b >= a): print ("7-b greater than equals B") El
Se:print ("7-b less than B") # #Python赋值运算符 # a=6;
c=2;        C **= a print ("6-c value is:", c) C//= a print ("7-c value is:", c) # #Python位运算符 C = a ^ b;           # = 0011 0001 print ("3-c value is:", c) c = ~a; # -61 = 1100 0011 Print ("4-c value is:", c) C = a << 2;       # 1111 = 0000 Print ("5-c value is:", c) C = a >> 2; 
# = 0000 1111 Print ("6-c value is:", c) # #Python逻辑运算符 # a = ten B = if (A and B): Print ("1-variable A and B are true")  Else:print ("1-variable A and B have a not true") if (A or B): Print ("2-variable A and B are all true, or one of the variables is true") else:print ("2-variables A and B are not true") # Modify the value of variable a = 0 if (A and B): Print ("3-variable A and B are true") Else:print ("3-Variable A"

and B has a not true ") if (A or B): Print (" 4-variable A and B are all true, or one of the variables is true ") Else:print (" 4-variable A and B are not true ") If not (A and B): Print ("5-variable A and B are false, or one of the variables is false") Else:print ("5-variable A and B are true") # #Python成员运

operator A = ten b = List = [1, 2, 3, 4, 5];
   if (A in list): Print ("1-variable A in the given list") Else:print ("1-variable A is not listed in the given list") if (b is not in list): Print ("2-variable B is not in the given list") Else:print ("2-variable B in the given list") # Modify variable AValue A = 2 if (A in list): Print ("3-variable A in the given list") Else:print ("3-variable A is not in the given list") # #Python身份运算符
   A = b = if (A is B): print ("1-a and B have the same identity") Else:print ("1-a and b do not have the same identity") if (ID (a) = = ID (b)): Print ("2-a and B have the same identity") Else:print ("2-a and b do not have the same identity") # Modify the value of variable B = if (A is B): print ("3-a and B Has the same identity ") Else:print (" 3-a and b do not have the same identity ") if (ID (a) is not ID (b)): Print (" 4-a and b do not have the same identity ") Else:print ("  4-a and B have the same identification ") # #Python运算符优先级 a = b = ten c = d = 5 E = 0 E = (A + b) * C/D # (*)/5 print (" A


 + b) * The result of C/D operation is: ", e)

Basic Statement

# #While i = 1 while I < 10:I + + + 1 if i%2 > 0: # Skip output continue print (i) # output when not in numbers Numbers 2, 4, 6, 8, i = 1 while 1: # cyclic condition is 1 must be set up print (i) # output 1~10 i = 1 if i > 10: # When I am big 10 o'clock out of the loop break # #for Loop statement for letters in ' Python ': # First Instance print (' Current letter: ', letters ') fruits = [' banana ', ' a

Pple ', ' Mango '] for F in fruits:print ("Current Letter", f); For index in range (len (fruits)): print (' Current fruit: ', Fruits[index]) # #python, for ... else to indicate such meaning, the statement in the #for and ordinary no difference, El
In SE #的语句会在循环正常执行完 (that is, the for is not interrupted by breaking out of a break), while ... else is the same.
         For NUM in range (10,20): # Number of iterations 10 through 20 for I in Range (2,num): # based on factor iterations If num%i = 0: # Determine the first factor                  J=num/i # Calculates the second factor print ('%d equals%d *%d '% (NUM,I,J)) Break # jump out of the current loop else: # The else part of the loop is print (num, ' is a prime number ') # # #else是在for正常执行结束之后才会执行else ' Python break statement, just like in C, breaking the least closed for
or while loop. The break statement is used to endStop Loop statement, that is, the loop condition does not have the false condition or the sequence is not fully recursive, also stops the execution of the loop statement.
The break statement is used in the while and for loops.
If you use a nested loop, the break statement stops executing the deepest loop and starts executing the next line of code.
The "' Python continue statement jumps out of the loop, and the break jumps out of the loop.
The continue statement tells Python to skip the remaining statements of the current loop, and then proceed to the next round of loops.
The continue statement is used in the while and for loops.                    "' for letters in ' Python ': # First Instance if letter = = ' h ': Continue print (' current letters: ') var = 10
   # second Instance while var > 0:var = var-1 if var = 5:break;
Print (' Current variable value: ', var ') ' ' Python pass ' is an empty statement to preserve the integrity of the program's structure.
Pass doesn't do anything, it's usually used as a placeholder statement. "' for letters in ' Python": if letter = = ' h ': Pass print (' This is Pass block ') print (' Current: ') # #字符串格式化
Output print ("My name is%s and weight is%d kg!"% (' Zara ')) Hi = ' Hi there ' repr (HI) print (HI)

Print (HI) Hi #repr list = [' Physics ', ' Chemistry ', 1997, 2000];
Print ("Value available at index 2:") print (list[2]);
LIST[2] = 2001;

Print ("New value available at index 2:") print (list[2]); Print (len(list));
Print (1997 in list);
Print (list *4);
Print (list[1:]);
Print (List[1:3]);
Print (list[-2]);
List.append (122);
Print (list) print (List.count (122));
#print (List.reverse ());
print (list);

Print (Len (list));
MyList = [' AA ', ' cc ', ' BB '];
Print (mylist);

Print (min (mylist));

Print (max (mylist)); Print (List.reverse ());
Date-time Functions
# #常用的工具函数 Import time;

# introduce time module ticks = Time.time () print (current timestamp:, ticks) print (Time.localtime (Time.time ())); # Formatted as 2016-03-20 11:45:39 form print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) # formatted as Sat 28 22:24:24 2016-shaped
Print (Time.strftime ("%a%b%d%h:%m:%s%Y", Time.localtime ()) # Converts a format string to a timestamp t = (2009, 2, 17, 17, 3, 38, 1, 48, 0) secs = time.mktime (t) print ("Time.mktime (t):%f"% secs) print ("Asctime (localtime)):%s"% secs (time.asctime Altime (secs)) # #calendar # Get today's date, and calculate yesterday and tomorrow's date ' ' You have a file called operator.py in the current directory, so Impo

RT operator is picking up your module and not the Python standard library module operator.
You are should rename your file to don't conflict with Python ' s standard library. ' Import datetime import Calendar today = Datetime.date.today () yesterday = Today-datetime.timedelta (days = 1) Tomorr ow = Today + Datetime.timedelta (days = 1) print (Yesterday, today, tomorrow) Last_friday = DatetiMe.date.today () Oneday = Datetime.timedelta (days = 1) while last_friday.weekday ()!= calendar. Friday:last_friday-= oneday print (last_friday.strftime ('%A,%d-%b-%y ')) today = Datetime.date.today () target_day = Calendar. FRIDAY; #目标 print ("target", target_day) This_day = Today.weekday (); #今天的星期 print ("Today", this_day) Delta_to_target = (this_day-target_day)% 7 print ("remainder", delta_to_target) va = (0-4)%7 ; # #负数求模就是做差 Print (VA) last_friday = Today-datetime.timedelta (days = delta_to_target) print (Last_friday.strftime ("%d-%

 B-%y "))
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.