Python BASICS (day1) and python basics day1

Source: Internet
Author: User

Python BASICS (day1) and python basics day1

I. Differences between py2 and py3

The biggest difference is that py3 supports Unicode.

Official support for py2.7 will be suspended on March 13, 2020

One popular module that don't yet support Python 3 is Twisted (for networking and other applications ).

 

Ii. Hello World Program

Create a file named hello. py in linux and enter

1 print("Hello World!")
View Code

Then execute the command: python hello. py, and output

1 localhost:~ jieli$ vim hello.py 2 3 localhost:~ jieli$ python hello.py 4 5 Hello World!
View Code

Specify Interpreter

When running python hello. py in the previous step, it is clearly pointed out that the hello. py script is executed by the python interpreter.

If you want to execute a python script like a shell script, for example:./hello.py In the header of the hello. py file, specify the interpreter as follows:

1 #!/usr/bin/env python2 3   4 5 print "hello,world"
View Code

In this way, run :./hello.pyYou can.

Ps: You must grant the "hello. py" execution permission before execution. chmod 755 hello. py

 

Iii. Variables

 VariablesAre used to store information to be referenced and manipulated in a computer program. they also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. it is helpful to think of variables as containers that hold information. their sole purpose is to label and store data in memory. this data can then be used throughout your program.

 Rule for variable definition:

    • Variable names can only be any combination of letters, numbers, or underscores
    • The first character of the variable name cannot be a number.
    • The following keywords cannot be declared as variable names: ['and', 'as', 'assert ', 'Break', 'class', 'contine', 'def ', 'del', 'elif', 'else', 'else t', 'exec ', 'Finally', 'for ', 'from', 'global', 'if ', 'import', 'in', 'is ', 'lambda', 'not ', 'or', 'pass', 'print', 'raise ', 'Return ', 'try', 'wait', 'with', 'yield ']

 Variable assignment:

1 name = "oldboy"2 name2 = name3 name = "newboy"4 print("my name is",name,name2)
View Code

The running result is:
My name is newboy oldboy

The reason is: name and name2 point to the same string "oldboy", after the name is assigned a value, name points to "newboy", while name2 points to unchanged, still "oldboy"

 

Iv. character encoding

Common encoding types: ASCII (applicable to modern English and other Western European languages); GB2312 (7000 + Chinese characters) and GBK1.0 (21000 + Chinese characters) GBK18030 (27000 + Chinese characters); big5 for traditional Chinese

ASCII (American Standard Code for Information Interchange) is a computer coding system based on Latin letters. It is mainly used to display modern English and other Western European languages, it can only be expressed in 8 bits (one byte), that is, 2 ** 8 = 256-1. Therefore, the ASCII code can only represent 255 symbols at most.

Obviously, ASCII codes cannot represent all types of characters and symbols in the world. Therefore, you need to create a new encoding that can represent all characters and symbols, that is, Unicode.

Unicode (unified code, universal code, Single Code) is a character encoding used on a computer. Unicode is generated to address the limitations of traditional character encoding schemes. It sets a uniform and unique binary encoding for each character in each language, it is specified that some characters and symbols are represented by at least 16 bits (2 bytes), that is, 2*16 = 65536. Note: here we are talking about at least 2 bytes, maybe more

UTF-8 is the compression and optimization of Unicode encoding, which no longer uses at least 2 bytes, but classifies all characters and symbols: the content in the ascii code is saved in 1 byte, the European characters are saved in 2 bytes, and the East Asian characters are saved in 3 bytes...

Code comment

Single Row gaze: # commented content

Multi-line comment: "commented content """

 

V. Input and character formatting

There are multiple string formatting methods using input:

 1 name = input("name:") 2 age = input("age:") 3 job = input("job:") 4 salary = input("salary:") 5  6 info = """-------info of {_name}-------- 7 name:{_name} 8 age:{_age} 9 job:{_job}10 salary:{_salary}11 """.format(_name=name,_age=age,_job=job,_salary=salary)12 13 info2 = """-------info of %s--------14 name:%s15 age:%d16 job:%s17 salary:%d18 """%(name,name,int(age),job,int(salary))19 20 info3 = """-------info of {0}--------21 name:{0}22 age:{1}23 job:{2}24 salary:{3}25 """.format(name,int(age),job,int(salary))26 27 print(info)28 print(info2)29 print(info3)
View Code

For Password Input, if you want to be invisible, use the getpass method in the getpass module, that is:

1 import getpass2 3 # assign the user input content to name variable 4 5 pwd = getpass. getpass ("Enter Password:") 6 7 # print input content 8 9 print (pwd)
View Code

If there is a problem with using pyCharm, You can execute it in the command line to check the getpass effect.

6. if... else expression

Scenario 1: Determine whether the account and password entered by the user are correct based on conditions. If the password is correct, a welcome word is displayed.

1 # prompt to enter the user name and password 2 3 4 5 # verify the user name and password 6 7 # If the user name or password is incorrect 8 9 # If the user name or password is successful, output welcome, XXX! 10 11 12 13 14 15 #! /Usr/bin/env python16 17 #-*-coding: encoding-*-18 19 20 import getpass21 22 23 24 name = raw_input ('Enter the User name :') 25 26 pwd = getpass. getpass ('enter password: ') 27 28 29 30 if name = "alex" and pwd = "cmd": 31 32 print ("Welcome, alex! ") 33 34 else: 35 36 print (" incorrect user name and password ")
View Code

Scenario 2: Set your age in the program, and start the program to let the user guess. After the user inputs, the system prompts the user to enter the correct information based on the input. If the input is incorrect, indicates whether to guess whether it is big or small.

1 guess_age = int(input("guessage:"))2     if guess_age == my_age:3         print("yes,you got it!")4         break5     elif guess_age > my_age:6         print("guess smaller...")7     else:8         print("guess bigger!")
View Code

 

7. while Loop

Through the while loop, the program is optimized to guess the age, and the program is set to guess three times. If not, the program exits. Pay attention to the use of else in the Loop:

1 my_age = 34 2 count = 0 3 while count <3: 4 guess_age = int (input ("guessage:") 5 if guess_age = my_age: 6 print ("yes, you got it! ") 7 break 8 elif guess_age> my_age: 9 print (" guess smaller... ") 10 else: 11 print (" guess bigger! ") 12 count + = 113 else: # note here, else statements can be used for while loops to make the program simpler and more refined 14 print (" too processing times, byebye! ")
View Code

 

8. for Loop

The for loop is used to achieve the same while effect. The else statement is also used:

 1 my_age = 34 2 for i in range(3): 3     guess_age = int(input("guessage:")) 4     if guess_age == my_age: 5         print("yes,you got it!") 6         break 7     elif guess_age > my_age: 8         print("guess smaller...") 9     else:10         print("guess bigger!")11 else:12     print("too many times,byebye!")
View Code

In the end, the optimization is implemented again, so that users can keep guessing based on their own needs:

 1 my_age = 34 2 count =0 3 while count <3: 4     guess_age = int(input("guessage:")) 5     if guess_age == my_age: 6         print("yes,you got it!") 7         break 8     elif guess_age > my_age: 9         print("guess smaller...")10     else:11         print("guess bigger!")12     count +=113     if count ==3:14         continue_confime = input("try again?")15         if continue_confime != "n":16             count = 0
View Code

 

Note the difference between break and continue in a loop:

Break is the entire loop that jumps out of the current loop.

1 for i in range(4):2     print("-----------",i)3     for j in range(4):4         print("&&&&&&",j)5         if j <2:6             print("***",j)7         else:8             break

Execution result:

----------- 0
& 0
* ** 0
& 1
* ** 1
& 2
----------- 1
& 0
* ** 0
& 1
* ** 1
& 2
----------- 2
& 0
* ** 0
& 1
* ** 1
& 2
----------- 3
& 0
* ** 0
& 1
* ** 1
& 2

 

Continue jumps out of the current loop

1 for i in range(4):2     print("-----------",i)3     for j in range(4):4         print("&&&&&&",j)5         if j <2:6             print("***",j)7         else:8             continue

Execution result:
----------- 0
& 0
* ** 0
& 1
* ** 1
& 2
& 3
----------- 1
& 0
* ** 0
& 1
* ** 1
& 2
& 3
----------- 2
& 0
* ** 0
& 1
* ** 1
& 2
& 3
----------- 3
& 0
* ** 0
& 1
* ** 1
& 2
& 3

 

 

 

 


 

 

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.