Python Basic Learning

Source: Internet
Author: User
Tags arithmetic operators bitwise bitwise operators logical operators modulus

Python installation (under Windows platform)

1. Download the installation package: https://www.Python.org/downloads/

2. Default installation path: C:\Python2.7

3. Configure the variable environment:

Right-computer→ properties → advanced system settings → advanced → environment variables → in the second content box find a row of the variable named path, double-click the →python installation directory to append to the variable value;

Specify interpreter

When you run a Python program, you must explicitly specify that the program is executed by the Python interpreter. As follows:

#!/usr/bin/env python →→→→ The function of this phrase: declarative interpreter

print "Hello World"

Character encoding

Before the program starts running, you need to tell the interpreter what kind of character encoding to use, in addition to declaring the interpreter. We generally use the UTF-8 encoding. In the program, write the following:

#!/usr/bin/env python

#-*-coding:utf-8-*- or #coding = Utf-8

Variable definition and rules

The purpose of defining variables is to create a container with a "number" in memory for the data, and then store the required data in this container. When the program is running later, if you want to use the data inside the container, you can point directly to the variable name.

It is summed up as: The value it uses for the next program

Rules:

1. Variable names can only be any combination of letters, numbers, or underscores.

2. The first character of a variable name cannot be a number

3. The following keywords cannot be declared as variable names

And ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ', ' for ', ' fro M ', ' global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' Try ', ' when ', ' with ', ' yield '

Comments

Single-line gaze: # Annotated content

Multiline Comment: "" "Annotated Content" ""

User input

#!/usr/bin/env python

#-*-coding:utf-8-*-

Name = Raw_input ("What is your name?") #raw_input它仅在python2. x in effect

Name = input ("What is your name?")

Print ("Hello" + name)

When entering a password, if you want to be invisible, you need to take advantage of the Getpass method in the Getpass module, namely:

#!/usr/bin/env python

# -*- coding: utf-8 -*- import getpass pwd  = getpass.getpass( "请输入密码:" )  # 将用户输入的内容赋值给 name 变量 print (pwd) # 打印输入的内容Note: The Getpass command cannot be implemented in the Pycharm password is not visible ModulePython's strength is that he has a very rich and powerful standard library and third-party library, almost any function you want to implement has the corresponding Python library support, later in the course will be in depth to explain the various libraries commonly used, now, we first to symbolically learn 2 simple. Sys #!/usr/bin/env python # -*- coding: utf-8 -*- import sys print (sys.argv)The result of its final output is: [' C:/users/administrator/pycharmprojects/first/day1/hello word.py '] #它输出了当前运行程序所在的路径 os #!/usr/bin/env python # -*- coding: utf-8 -*- import os os.system( "df -h" #调用系统命令A complete combination. import os,sys os.system(‘‘.join(sys.argv[ 1 :]))  #把用户的输入的参数当作一条命令交给os.system来执行

The following code is a formatted string
%s string
%d integers
%f floating Point

#!/usr/bin/env Python3

#-*-coding:utf-8-*-

# Author:alex

Name = input ("In Put Your name")
age = Int (input ("in Put your"))
Job = input ("In Put Your Job")

msg = "'
Information of user%s:
---------------------
Name:%s
Age:%d
Job:%s

---------End---------
"% (Name,name,age,job)

Print (msg)

Exit ("exited") #直接退出程序

Operator:
Arithmetic operators:
+ addition-Adds value A + b = 30 on both sides of the operator
-Subtract-subtracts the right operand from the left operand A-B =-10
* Multiply-multiplies the values on both sides of the operator A * b = 200
/except-by the right operand divided by the left operand b/a = 2
% modulo-by the right operand and remainder return divided by the left operand b% A = 0
* * Exponent-Performs a calculation of the operation Exponent (power) A**b = 10 to a power of 20

Comparison operators:
= = Check that the values of the two operands are equal, and if so, the condition becomes true. (A = = B) is not true.
! = checks that the values of the two operands are equal, and if the values are not equal, the condition becomes true. (A! = B) is true.
<> checks whether the values of the two operands are equal, and if the values are not equal, the condition becomes true. (a <> B) is true. This is similar to the! = operator
> checks if the value of the left operand is greater than the right operand, and if so, the condition is true. (A > B) is not true.
< Checks if the value of the left operand is less than the value of the right operand, and if so, the condition is true. (A < b) is true. The
>= checks whether the value of the left operand is greater than or equal to the value of the right operand, and if so, the condition is true. (a >= B) is not true. The
<= checks whether the value of the left operand is less than or equal to the value of the right operand, and if so, the condition is true. (a <= B) is true. The

Assignment operator
= simple assignment operator, assignment from the left operand of the right operand C = A + B will specify the value A + B to c
+ = addition and assignment operator, which adds the right operand to the left operand and the result assigned to the left operand C + a equals c = C + A The
-= minus and assignment operator, which subtracts the right operand from the left operand and assigns the result to the left operand C-a equals the C = c-a
*= multiplication and assignment operator, multiplies the right operand to the left operand and assigns the result to the left operand C *= a equivalent to C = c * A
/= division and assignment operator, which puts the left operand with the correct operand and assigns the result to the left operand c/= a equals = c/a
% = modulus and assignment operator, which requires a modulus of two operands and assigns the result left operand C%= A is equivalent to c = c% A
**= exponent and assignment operator, perform exponential (power) calculation operator and assign to left operand C **= a equals c = c * * A

Bitwise operators:
Bitwise operators Act on bit and bit operation execution bits. Suppose that if a = 60; and B = 13; now in binary format they will look like this:
The smallest unit that a computer can represent is a bits
The smallest unit a computer can store is a bits
A BITS unit is bit (8bit is 1byte[bytes])
A = 0011 1100 60

b = 0000 110113

-----------------

a&b = 0000 1100

a|b = 0011 1101

A^b = 0011 0001

~a = 1100 0011

Python language supports bitwise operators binary movement operation is faster than multiplication
& with operations 0 and 0 for 0 1 and 0 for 0 1 with 1 for 12 and copy operation, as a result, if it exists in two operands. (A & B) = 12 that is 0000 1100
| or operations 0 and 0 for 0 1 and 0 for 1 1 and 1 for 12 or copy operation with one bit if it exists in one operand. A binary or copy operation has a bit, if it exists in an operand. (A | b) = 61 that is 0011 1101
^ XOR operations 0 and 0 are 0 1 with 0 for 1 1 with 1 for a replica of 2 binary XOR operator if it is set at an operand instead of two bits. A copy of the binary XOR operator, if it is set to an operand instead of two bits. (a ^ b) = 49 that is 0011 0001
~ bitwise reverse the binary inverse of a number, and then subtract (the maximum value that the standard number can represent + 1) For example, the bitwise inversion of the 60 195-256=-61 binary is unary and has the effect of a "flip" bit. (~a) = 61 is 1100 0011 in the form of a 2 complement due to the signed binary number.
<< binary left shift operator. The sitting-shift is equivalent to multiplication. The left operand's value is shifted left by the number of digits specified by the right operand. b << 1 = 26 or 0001 1010
>> binary right shift operator. Move right equals division, but takes integers only. The value of the left operand is moved to the right by the number of digits specified by the right operand. A >> 2 = 15 or 0000 1111
Note: Each time the binary is shifted to the left or to the right n bits, which is equivalent to multiplying or excluding a 2 N-th

logical operators
And so-called logic and operators. If the two operands are true, then the condition is set. (A and B) is true.
Or the so-called logical OR operator. If there are two operands that are non-0 then the condition becomes true. (A or B) is true.
Not the so-called logical non-operator. The logical state used to invert the operand. If a condition is true, the logical non-operator returns false. Not (A and B) is false.

Member operators:
In evaluates to true if it finds the order of the variable in the specified, otherwise false. X in Y, where a 1 is generated, if X is a member of sequence Y.
The not in evaluates to true if it is not found in the specified variable order, otherwise false. X is not in Y, where the result is not 1 if X is not a member of sequence Y.

Identity operators:
is evaluates to true if the variables on either side of the operator point to the same object, otherwise false. X is y, where the result is 1 if the value of ID (x) is ID (y).
Is does not evaluate to false, or true if the variable operators on both sides point to the same object. X is not y, where the result is not 1, when ID (x) is not equal to ID (y).

Operator Precedence:
* * Power (raised to exponent)
~ +-complement, unary plus and minus (the last two of the method name [email protected] and-@)
*/%//multiply, except, modulo and floor removal
+-Addition and subtraction
>> << left, right bitwise shift
& Bit ' and '
^ | bitwise XOR ' or ' and periodic ' or '
<= < > >= comparison operators
<> = = = Equality operator
=%=/=//=-= + = *= **= assignment operator
is isn't identifier operator
In no in member operator
Not OR and logical operators

Expression If ... else

Scenario One, user login verification

#!/usr/bin/env python # -*- coding: encoding -*- import getpass name  = input ( ‘请输入用户名:‘ ) pwd  = getpass.getpass( ‘请输入密码:‘ ) if name  = = "alex" and pwd  = = "cmd" :      print ( "欢迎,alex!" ) else :      print ( "用户名和密码错误" )Scenario two, Guess age game

#!/usr/bin/env python

# -*- coding: utf-8 -*- my_age  = 28 user_input  = int ( input ( "input your guess num:" )) if  user_input  = = my_age:      print ( "Congratulations, you got it !" ) elif user_input < my_age:      print ( "Oops,think bigger!" ) else :      print ( "think smaller!" ) For Loop#!/usr/bin/env python #_*_coding:utf-8_*_ __author__  = ‘Alex Li‘ for in range ( 10 ):      print ( "loop:" , i )

Output:

loop: 0

loop:  1 loop:  2 loop:  3 loop:  4 loop:  5 loop:  6 loop:  7 loop:  8 loop:  9Or the above program, but encountered less than 5 cycle times will not go, jump directly into the next cycle for in range ( 10 ):      if i< 5 :          continue #不往下走了,直接进入下一次loop      print ( "loop:" , i )is still the above program, but encountered more than 5 cycle times will not go, direct exit for in range ( 10 ):      if i> 5 :          break #不往下走了,直接跳出整个loop      print ( "loop:" , i )While Loop loop

count =0

whileTrue:

     print ( "你是风儿我是沙,缠缠绵绵到天涯..." ,count)      count  + = 1The loop above is a dead loop, and it will run when it runs.   If you go to check CPU usage, you can see that it has risen a lot in an instant. So the cycle of death to write less ... In the above program, add a break, when the number of cycles reached 100 times, the program stops running. count  = 0 while True :      print ( "你是风儿我是沙,缠缠绵绵到天涯..." ,count)      count  + = 1      if count  = = 100 :          print ( "循环100次已经完成..." )          breakWrite an age-guessing program with a for loop #!/usr/bin/env python # -*- coding: utf-8 -*- my_age  = 28 count  = 0 while count <  3 :      user_input  = int ( input ( "input your guess num:" ))      if user_input  = = my_age:          print ( "Congratulations, you got it !" )          break      elif user_input < my_age:          print ( "Oops,think bigger!" )      else :          print ( "think smaller!" )      count  + = 1 #每次loop 计数器+1 else :      print ( "猜这么多次都不对,你个笨蛋." )

Python Basic Learning

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.