The path to python practice (2-Basic python syntax, traffic control), python-python

Source: Internet
Author: User

The path to python practice (2-Basic python syntax, traffic control), python-python

For Tom, it is really hard to read the code, the progress is very slow, and the mind is quite complicated, walking silently, hoping to turn persistence into a habit and learn the Code with hard work.

I. character encoding/variable

1. character encoding

When the python interpreter loads the code in the. py file, it will encode the content (default ASCII ).

The introduction of the ASCII code is skipped, but the ASCII code cannot represent all the texts and symbols in the world. Therefore, we need to generate a new encoding that can represent all characters and symbols, namely: unicode.

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...

 

Therefore, when the python interpreter loads the code in the. py file, it will encode the content (ascill by default)

 

In python3, you can recognize Chinese characters and print ("Hello World") directly ")

In the python2 environment, Chinese characters cannot be recognized directly. You need to tell the python interpreter what encoding is used to execute the source code, that is:

 

#!/usr/bin/env python

 

# -*- coding: utf-8 -*- print( "Hello, world ")  2. VariablesI can't really understand the definition of variables, but I only know that the function of variables is to store them, which makes it easy to remember. In the python3 environment, you can directly define variables without defining variables. name = "A"However, in the python2 environment, you must declare the variable first: # -*- coding: utf-8 -*-Name = "" Variable definition rules:
  • 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', 'effect', 'exec ', 'Finally', 'for ', 'from', 'global', 'if', 'import ', 'in', 'is, 'lambda ', 'not', 'or', 'pass', 'print ', 'raise', 'Return ', 'try ', 'while', 'with', 'yield ']
name = "A" name2 = name print (name,name2)...... However
Name = ""
Name2 = name

Name = "B"
Print ("my name is", name, name2)

During program execution

My name is paoche ge alex li

Process finished with exit code 0

Note: The name2 variable points to A through name, that is, the name2de variable is defined as A and has nothing to do with name. This is very important.

 

Ii. Notes

Current comment: # commented content

Multi-line comment: "commented content """

 

Iii. Input

#!/usr/bin/env python #_*_coding:utf-8_*_
name = input("name:")
age = input("age:")
job = input("job:")
salary = input("salary:")
print(name,age,job,salary)
When entering the password, if you want to be invisible, you need to use the getpass method in the getpass module, that is: #!/usr/bin/env python # -*- coding: utf-8 -*-

Importgetpass

Uername = input ("uername :")

Password = getpass. getpass ("password :")

Print (uername, password)

 

Formatting output and splicing

In the formatted output, String concatenation can be in the form of +, % Yes, {}, and []. However, we do not recommend using String concatenation, especially the + concatenation, do not use it unless you have .)

 

+ Type stitching

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

Name = input ("name :")
Age = input ("age :")
Job = input ("job :")
Salary = input ("salary :")
Info = '''
------- Info of + name + '''------

Name: ''' + age + '''
Age: ''' + job + '''
Job: ''' + salary + '''
Salary :'''
''' % (Name, name, age, job, salary)

Print (info)

 

% S character concatenation

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

Name = input ("name :")
Age = input ("age :")
Job = input ("job :")
Salary = input ("salary :")
Info = '''
------- Info of % s -------

Name: % s
Age: % s (here % S can also be changed to % d [detection string type], note: % d is a number)
Job: % s
Salary: % s
''' % (Name, name, age, job, salary)

Print (info)
 

Note: age: % d, age = inptu ("age") is a string, not a number, and must be converted,

Age = int (input (age) print (type (age ))

 

{} Splicing

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

Name = input ("name :")
Age = input ("age :")
Job = input ("job :")
Salary = input ("salary :")
Info = '''
------- Info of {name }-------

Name: {name}
Age: {age}
Job: {job}
Salary: {salary}
'''. Formate (name = name, name, age = age, job = job, salary = salary)
Print (info)

 

[] Type

#!/usr/bin/env python
# -*- coding: utf-8 -*-

name = input("name:")
age = input("age:")
job = input("job:")
salary = input("salary:")
info = '''
-------info of {0}-------

name:【0】
age:【1】
job:【2】
salary:【3】
'''.formate(,name,age,job,salary)
print(info)

Iii. if else expression  Scenario 1: user login verification  # Prompt for username and password    # Verify the user name and password # If an error occurs, the output username or password is incorrect. # If yes, output welcome, XXX! 

 

Example:

#!/usr/bin/env python

 

# -*- coding: encoding -*-# Import Getpass cannot be written.Uername = Apassword = Bname = input ("uesername:") # password = getpass. getpass ("password:") if uername = uername and password = password: # (= indicates a value, = indicates a value, remind me that a white paper like me must remember, it is very important) print ("welcom uer {name} login... ". formate (name = uername ))

 

Else:

Print ("invalid uername or passwaord! ")

 

Scenario 2: Age Prediction

 

#!/usr/bin/env python

 

# -*- coding: encoding -*-A = XXX

 

Guess_age = int (iput ("guess age") (in python3, the default input result type is string, which needs to be converted. int () is OK. knowledge points, you know)

If guess_age = age_of_A

Print ("yes, you got it .")

Elif guess_age> age_of_A:

Print ("think smaller ...")

Else:

Print ("think bigger! ")

 

Scenario 3: Output permissions based on user input

# A --> super Administrator

# B --> General Administrator

# C, d --> business Supervisor

# Others -- "common users

Name = iput ("uername :")

If name = "":

Print ("Super administrator ")

Elif name = "B ":

Print ("common administrator ")

Elif name = "B" or name = "c ":

Print ("Business supervisor ")

Else:

Print ("normal user ")

 

Iv. whlie Loop

Expand the scenario by two or three guesses.

 

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-

Age_of_A = 20
Count = 0
While count <3:
Guess_age = int (input ("guess age :"))
If guess_age = age_of_A:
Print ("yes, you got it .")
Break
Elif guess_age> age_of_A:
Print ("think smaller ...")
Else:
Print ("think bigger! ")
Count + = 1
Else:
Print ("you have tried too hours times .")

While also has a wireless loop. Once it runs, it cannot be stopped.

Count = 0
While true:
Print ("count + 1", count)
Count + = 1 (equivalent count = count + 1)
If the code above exits after 100 loops, then:
Count = 0
While true:
Print ("count + 1", count)
Count + = 1
If count = 100
Print ("count + 1", count)
Break

 

V. for Loop

#!/usr/bin/env python
# -*- coding: utf-8 -*-

age_of_A = 20
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age ==age_of_A:
print("yes,you got it.")
break
elif guess_age>age_of_A:
print("think smaller...")
else:
print ("think bigger!")

else:
print("you have tried too many times.")

Extended for Loop

Enter the numbers 1-9.

For I in range (0, 10 ):

Print ("loop", I)

Jump to the numbers 1-9

For I in range (0, 10, x ):

Print ("loop", I)

Note: x indicates the step size. When x = 2, it indicates 2, 4, 6, and 8. When x = 3, it indicates 3, 6, and 9.

 

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.