Python basic syntax

Source: Internet
Author: User
Tags arithmetic operators logical operators

Five basic types of objects

Strings (String)
Use "or" to enclose
Integers (integer)
Decimal: 123, octal: 025, Hex 0x15
Floating point (float)
2.13, 2.,. 2.1E1,
Boolean Number (Boolean)
True, False
Plural (complex)
1+2j
Object types can be viewed through type ().

type(2)<type‘int‘type(‘2‘)<type‘str‘1+2#整数相加3‘1‘+‘2‘#字符串相接‘12‘
Types of casts

Int (' 123 ') #将字符串强制转换为整数
Int (123.9) #将浮点数强制转换为整数, the result is 123
STR (123) #将整数强制转换为字符串
Float (' 123 ') #将字符换强制转换为浮点数
Float (123) #将整数强制转换为浮点数
BOOL (123) #将整数强制转换为布尔数
BOOL (0) #将整数强制转换为布尔数

Relational operators

= = equals
! =, <> not equal to

Greater than
< less than
= greater than or equal to
<= less than or equal to

Arithmetic operators
    • Add
    • Reducing
    • By
      /except
      % redundancy
      * * Index

Attention:
In Python2,/means rounding down.
Divides two integers, the result is an integer, and the decimal is rounded off.
If there is a floating-point number, the result is a floating-point number
If the two objects that participate in the operation are of the same type, the result type is unchanged.
If the two objects that are participating in the operation are of different types, the result is automatic type conversion according to the following rules
Bool?int?float?complex

>>> Import Math#引入math模块>>> dir (Math)#查看模块内容[' __doc__ ',' __name__ ',' __package__ ',' ACOs ',' Acosh ',' ASIN ',' Asinh ',' Atan ',' atan2 ',' Atanh ',' Ceil ',' Copysign ',' cos ',' cosh ',' degrees ',' E ',' Erf ',' ERFC ',' exp ',' EXPM1 ',' Fabs ',' factorial ',' floor ',' Fmod ',' Frexp ',' Fsum ',' Gamma ',' Hypot ',' Isinf ',' isNaN ',' Ldexp ',' Lgamma ',' log ',' log10 ',' log1p ',' MODF ',' pi ',' POW ',' radians ',' sin ',' Sinh ',' sqrt ',' Tan ',' Tanh ',' trunc ']>>> Math.PI3.141592653589793>>> Math.sqrt (4)2.0>>> Help (Math.exp)#查看帮助内容Help on built-inch functionExpinchModule Math:exp (...) exp (x) Return e raised to the power of X.
logical operators

And and
OR OR
Not non-

To judge leap years:
If the year can be divisible by 4, but not divisible by 100, it is leap years. If it can be divisible by 400, it is also a leap year.

>>> 200040and20001000or20004000True
Operator Precedence

Brackets: ()
Unary operations: +,-
Power Operation: * *
Arithmetic operation: *,/,%,//
Arithmetic operations: +,-
Comparison operations: = =,! =, <> <= >=
Logical non: not
Logic with: and
Logical OR: OR
Assignment operation: =, *=,/=, + =,-=,%=,//=

Rule 1: Top-down, highest brackets, lowest logic.
Rule 2: Unary priority, from right to left.
Rule 3: From left to right, combine in turn.

Increment operator

+=, -=, =, /=, %=, //=, *=

Identifier

Identifiers are the names of variables, functions, and modules
Naming rules:
The first character must be a letter or an underscore. Identifiers contain numbers, letters, and underscores. is case sensitive. Identifiers can be arbitrarily long. The identifier cannot be a keyword.

Keywords in Python2:

Elif Global or with assert else if pass yield broke except import print class exec in Raise cont Inue finally is return def for Lambda try

Input/Output

Raw_input
Function: Reads the keyboard input and treats all inputs as strings.
Syntax: Raw_input ([prompt])
Example: Radius = float (raw_input (' radius: '))
PI = 3.14
Radius = float (raw_input (' radius: '))
Area = pi*radius**2
Print Area

Input
Function: Read the keyboard input, can enter the number
Syntax: Raw_input ([prompt])
Example:
Radius = float (raw_input (' radius: '))
Radius = input (' Radius: ')

Print
Function: Output
Output variables:
Print a
Print (a)
Output string:
print ' ABCD '
Print "ABCD"
Print (' ABCD ')
Print ("ABCD")

To output multiple objects to one line:

3.14float(raw_input(‘Radius:‘))area = pi*radius**2‘when radius =‘‘the area is‘area
Escape characters:

\ n Enter
\ t tab
A
\a Bells
\ ' Single quotation mark
\ "Double quotation marks

If selection structure

Elif is equivalent to Else:if, but is tied to the first if condition.
When there is an else condition in the If-elif-else statement, the else condition is placed last.

"Eg.1:"

if c<10:    print("c<10")elif c>50:    print("c>50")else:    print("10<c<50")
While loop structure:

"Eg.2:"

num130whilenum <= total_num:    grade = input("input No."+str(num)+"student‘s grade:")    if60:        1    else:        pass       # do nothing    num1"passed student number is ", count

"Eg.3:" Calculates the value of E according to the Taylor theorem

n = 1  ee = 1  factor = 1  infactor = 1  while  Infactor > 1  e-6 : e1 = ee + infactor n + = 1  factor = Factor*n  infactor = 1.0 /factor ee = e1print  " E = ", Eeprint   "E = %.  5f " %ee   #小数点后保留5位数字  print  ( "E = %.  5f ") %ee   #小数点后保留5位数字  
For loop structure:

For I in range (A, B)
Range (A, b) a,a+1,..., b-1

For I in range (b)
Range (b) is equivalent to range (0,B)

For I in range (a,b,k)
Range (a,b,k) a,a+k,..., b-x

Transition from while loop to for loop:
i = InitialValue
While I < endvalue:
......
i + = 1
The above code can be used instead of:
For I in range (InitialValue, endvalue):
......
"Eg.4:"
For I in Range (1,10):
Print (i)
For I in Range (1,10):
Print ("Item {0},{1}". Format (i, "Hello Python"))

"Eg.5:" Eg.2 's rewrite:

0forin range(1,4):#注意这里输入的是字符串#grade = raw_input("input No."+str(i)+" student‘s grade:")    grade = input("input No."+str(i)+" student‘s grade:")    print(grade)    if60:        1    else:        passprint"passed student number is ", count

Break and Continue
As in C, Matlab, in Python:
Break forces the current loop body to terminate
Continue forced termination as secondary cycle

Programming exercises--finding the solution of the two-quadratic equation

#coding =utf-8#为了显示中文, you need to add #coding=utf-8 to your head.Import Matha, b, c = input ("Enter three coefficients:") Tag = b*b-4*a*cifTag <0:Print "Equation without real roots"elif Tag = =0: Sqrttag = Math.sqrt(b*b-4*a*c) R = (-b+sqrttag)/(2*a)Print " The only Root is"RElse: Sqrttag = Math.sqrt(b*b-4*a*c) R1 = (-b+sqrttag)/(2*a) r2 = (-b-sqrttag)/(2*a)Print "distinct roots is", R1, R2
Function

Custom Function – No pass-through parameters

def SayHello():    print("Hello World")SayHello()

Custom functions – with Pass parameters

def max(a,b):    if a>b:        return a    else:        return bprint(max(1,3))
Local variables and global variables

Variables defined outside the function are global variables
Variables defined inside the function are local variables
If you want a variable inside a function to be a global variable, you need to declare the variable with global within the function.

1def add():    global x    1    print xadd()print x

Recursion: Ask for factorial of 12

def p(i):    if1or0:        return1    else:        return i*p(i-1)print p(12)

Python basic syntax

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.