Python automated operation and maintenance course learning

Source: Internet
Author: User
This article summarizes the first day of the study of the old boy's Python automated operations course.

The general contents are as follows:

Python Introduction

First Python program: Hello World

Python variables

User interaction (user input, Output)

Process Control: Conditional statement (IF/ELIF/ELSE), loop statement (for/while/break/continue)

First, the Python language introduction:

1. Python is a high-level programming language for explanatory language, dynamic type, and strongly typed definition language. Developed by Guido van Rossum during the 1989 Christmas season, the first official version of the Python compiler was born in 1991. Has now become one of the mainstream programming languages.

2, mainly used in cloud computing, web development, scientific places and data analysis, artificial intelligence, finance, system operations, graphical GUI and so on.

3. Python's pros and Cons:

Advantages: Simple, clear, elegant, high development efficiency, strong portability, extensibility, and embeddable ability.

Cons: Slower execution than C/java (the PyPy interpreter is sometimes faster than c); The code cannot be encrypted (interpreted language); The thread cannot take advantage of multi-CPU problems.

4, Python interpreter: There are many Python interpreter, such as CPython, IPython, PyPy, Jython, IronPython, etc., but the most widely used or CPython.

Second, about all the environments in this article that run Python code:

--Operating system: Ubuntu 16.10 (Linux 4.8.0)

      

--python version: 3.5.2

      

--python Ide:pycharm 2016.3.2

      

Third, the first procedure: Hello World

Create a new Python File with the vim/vi command, the command "helloworld.py", Vim helloworld.py.

Enter the positive content in the helloworld.py:

#!/usr/bin/python3.5                     # tells the Linux system to execute the front code through the/usr/bin/python3.5 interpreter #-*-Coding:utf-8-*-# Python2 must add this line, Tells the Python interpreter to execute the positive code in UTF-8 encoding, and the default UTF-8 in Python3, you can not add the bank.           # author:spencer Jiang # Author print ("Hello, world!") # Print Hello, world!

Two modes of operation:

1), give helloworld.py assign executable permission, then execute: chmod 755 helloworld.py

> chmod 755 helloworld.py>./helloworld.py

    

2), execute directly from Python: Python installation path

>/usr/bin/python3.5 helloworld.py

    

Third, Python variables

1. Rules for variable definitions:

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

        • The first character of a variable name cannot be a number

        • The following keywords cannot be declared as variable names
          [' and ', ' as ', ' assert ', ' Break ', ' class ', ' Continue ', ' Def ', ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ', ' for ', ' F ' Rom ', ' Global ', ' if ', ' import ', ' in ', ' was ', ' lambda ', ' not ', ' or ', ' pass ', ' print ', ' raise ', ' return ', ' try ', ' while ', ' WI Th ', ' yield ']


      • Examples of identifier names are I, __my_name, name_23, and A1B2_C3.

      • Examples of identifier names are 2things, this is spaced out, and my-name.


2, Variable assignment: Assign a value to a variable by an equal sign

Example: Name = "Spencer Jiang"

You can also assign values to multiple variables on a single line. Such as:

A, B = 3, "JMW" Print (A, b) print (type (b), type (a)) ######### output: 3 jmw<class ' str ' > <class ' int ' >

  

Iv. user interaction and formatted output:

The user input Python3 with the input () function is good, Pyhton2 a bit complex first not to learn.

The input () function receives the task character entered from the user and returns the user-entered character as a string type.

Example 1 (userinput.py): name = input ("Please input your name:")

age = Int (input ("please input") # converts the characters entered by the user to the int type, and then assigns to the variable age.

#!/usr/bin/python3.5#-*-coding:utf-8-*-# author:spencer jiangname = input ("Please input your Name:") age = Int (input (" Please input your age: ') print ("Your name:%s, Your Age:%d"% (Name, age))

  

Example 2: The user name, password input, through the Getpass module, the password hidden display. (hidepassword.py)

#!/usr/bin/python3.5#-*-coding:utf-8-*-# author:spencer jiangimport getpassusername = input ("Please input your Userna Me: ") password = getpass.getpass (" Please input your password: ") print (username, password)

    

Formatted output:

1), add the% number to the print () function to format the output.

Output string:%s, output value%d, output floating point%f, etc., example:

#!/usr/bin/python#-*-coding:utf-8-*-# function:the format output# date:2017-02-10# author:spencer Jiangusername = "Spencer Jiang" age = 45salary = 231.32print ("Your name was:%s"% username) print ("Your Age was:%d"% age) print ("Your s Alary is:%f "% salary) print (" Your salary2f is:%.2f "% salary)                        # reserved 2 decimal places

  

2), formatted output through the format () function.

#!/usr/bin/python#-*-coding:utf-8-*-# function:the format output# date:2017-02-10# author:spencer Jiangusername = "Spencer Jiang" age = 45job = "IT Service" salary = 231.32info = "" Name: [_username]age: [_age]job: [_job]salary: [_salary] ] ". Format (_username = username, _age = age, _job = job, _salary = salary) print (info)

  

V. Process Control: Conditional Judgment Statement (IF/ELIF/ELSE):

Each condition is followed by a colon ending, wrapping (code to be executed when the condition is true, indented as a code block flag, Python's official recommendation to indent 4 spaces)

Example 1: Guess age (number) game (guessage.py).

#!/usr/bin/python3.5#-*-coding:utf-8-*-# author:spencer jiangage_of_spencer =         #先设定的年龄的数值guess_age = Int (input ("Guess an Age:")) if guess_age = = Age_of_spencer:    print ("Yes, you got it!") Elif guess_age > Age_of_spencer:    print ("No, your number is a litter bigger") Else:    print ("No, your number is a Litter smaller ")

  

Vi. Process Control: For loop (for X in range (10)), Break, continue:

When the loop condition is met, the code for the Loop statement block is executed, and the loop statement ends when the loop condition is not met.

For/while can also be followed by an else outside the loop.

Break: Ends the entire loop when a break is performed;

Continue: When the continue is executed, the loop is closed and the next cycle is carried out directly.

Example 1: Output 0 to 15 in 2, 4, 6, 8, and 4 digits (printnumber.py).

#!/usr/bin/python3.5#-*-coding:utf-8-*-# author:spencer jiangfor i in Range (0,15,2):    if i = = 0:                                      # Skip 0 This number C2/>continue    If i > 9:     # greater than 9 exit loop        break    else:        print (i)

  

Vii. Process Control: While loop, break, continue (similar to For loop)

While loop, you need to have a counter, or a statement that terminates the while condition in a loop statement block, otherwise it will continue to run.

Example 1 (whileloop.py): Printing 0~9 numbers

#!/usr/bin/python3.5#-*-coding:utf-8-*-# Author:spencer jiangcount = 0 # counter while True:    print (count) 
  count = count + 1    if Count > 9:        break

  

Example 2 (guessagewhile.py): Guess Age (number): Guess only 3 chances.

#!/usr/bin/python3.5#-*-coding:utf-8-*-# author:spencer jiangage_of_spencer = 65count = 0while Count < 3:    GUE ss_age = Int (input ("Guess an Age:"))    if guess_age = = Age_of_spencer:        print ("Yes, you Got it!")        Break    elif guess_age > Age_of_spencer:        print ("No, your number is a litter bigger")    else:        print ("No, y Our number is a litter smaller ")    count + = 1else:    print (" You guess to much times!!! ")

  

 

Example 2, after each guess 3 times incorrect, pop-up prompts to see if the user will continue to guess. If the user enters "n" it means stop.

#!/usr/bin/python3.5#-*-coding:utf-8-*-# author:spencer jiangage_of_spencer = 65count = 0while Count < 3:    GUE ss_age = Int (input ("Guess an Age:"))    if guess_age = = Age_of_spencer:        print ("Yes, you Got it!")        Break    elif guess_age > Age_of_spencer:        print ("No, your number is a litter bigger")    else:        print ("No, y  Our number is a litter smaller ")    count + = 1    if Count = = 3:        continue_confirm = input (" Do you want to continue To guess? ")        If continue_confirm! = ' n ':            count = 0else:    print ("You guess to much times!!!")

  

Eight, Python code comments:

# One-line comment starts with the pound sign "#"

The "or" "multiline comment is enclosed in 3 pairs of single quotes or 3 pairs of double quotation marks that will be annotated.

At the same time 3 pairs of quotes, you can also represent the assignment of a string (paragraph text), such as:

info = "" "Your Information:name:jmwage:32" ""

Nine, the operation:

1, the Analog user login interface: 1) by the user input user name, password; 2) login is successful, the welcome message is displayed, 3) login failed more than 3 times to lock the account.

2, Level Three menu: Provincial, city and county Level 3 is the menu.

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.