Python study notes the first day

  • variable
  • user input
  • if-else
  • for(break,continue)
  • while(break,continue)
  • Comprehensive example
  • Operation

 

1. Variables

1.1. To understand the pointing problem of variables, see the following example:

1 #Variables are  used to store content
 2 name= ' SYR ' #python is a dynamic language, no need to declare data types
 3 name2= name#name2 points to
 4  print(name,name2)#SYR
 5 name= ' XYQ ' #name It points to XYQ, and the point of name2 does not change
 6  print(name,name2)#XYQ SYR
 7 #Rules  of variable definition: only the combination of alphanumeric and underscore can be said, the first character cannot be a number
 8 #The  variable name is semantic
 9 #How to represent constants in python, variable names are capitalized: PI

1.2. Rules for variable definition:

  • 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 used as variable names: ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or ', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

2. User input

2.1 The difference between input and raw_input:

Remember to use input() directly in python3.x, and use raw_input() directly in python2.x. The difference between input() and raw_input() in python2.x can be referred to:

https://www.cnblogs.com/gengcx/p/6707024.html

2.2. The default output of input is str type. If you need int type, you need to add conversion int() by yourself.

username=input('username:')
# age1=input('age:')
age=int(input('age:'))
# print(type(age))

In the above example, the type of age1 is str and the type of age is int

2.3. Several output methods of print:

① Be careful not to add a comma before %(username,username,age,job,salary), which is different from the c language

username=input('username:')
age=input('age:')
job=input('job:')
salary=input('salary:')
print('''
--------------info of %s-----------
Name:%s
Age:%s
Job:%s
Salary:%s
'''%(username,username,age,job,salary))

②.format usage

print('''
--------------info1 of {_name}------------
Name:{_name}
Age:{_age}
Job:{_job}
Salary:{_salary}
'''.format(_name=username,
           _age=age,
           _job=job,
           _salary=salary))

③.Format usage

print('''
---------------info2 of {0}--------------
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
'''.format(username,age,job,salary))

3. if-esle 

Relatively simple, not to mention

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!")

Fourth, for

4.1. Simple for statement

for i in range(10):
    print("loop:", i )

      nested for statement

#nested loop
for i in range(10):
    print('------',i)
    for j in range(10):
        print(j)
        if j>5:
            break
#The large loop is executed 10 times, and the small loop is executed 6 times

  

4.2, for combined with break, continue

break is to end the current entire loop, the following output should be: 0, 1, 2, 3, 4, 5

for i in range(10):
    if i>5:
        break #Don't go down, just jump out of the whole loop
    print("loop:", i )

continue is to end the current loop and continue to the next loop. The following output should be 5, 6, 7, 8, 9

for i in range(10):
    if i<5:
        continue #Do not go down, go directly to the next loop
    print("loop:", i )

4.3、for-else

The following program will be executed when the guess is correct: print('you have tried too many times')?

The answer is: no.

Because break jumps out of the for loop, else and for are side by side, and the else is executed only when the three loops of i in for are executed.

for i in range(3):
    guess_age = int(input("guess age:"))
    if guess_age == age_of_sun:
        print('yes,you got it')
        break
    elif guess_age > age_of_sun:
        print('think smaller')
    else:
        print('think bigger')
else:
    print('you have tried too many times')

五、while 

5.1. The following is an infinite loop, which will run

count = 0
while True:
    print("You are the wind and I am the sand, lingering to the end of the world...", count)
    count +=1
    

5.2. Combining while with break and continue

break, continue is the same as the above for for.

while count<3:
    guess_age = int(input("guess age:"))
    if guess_age==age_of_sun:
        print('yes,you got it')
        break
    elif guess_age>age_of_sun:
        print('think smaller')
    else:
        print('think bigger') 

5.3、while-else

In this example, only the conut in the while loop ends from 1-2, and print("It's wrong to guess so many times, you idiot.")

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 #each loop counter +1
else:
    print("It's wrong to guess so many times, you idiot.")

6. Comprehensive examples

age_of_sun=25
count=0
for i in range(0,3):
    guess_age=int(input('guess age:'))
    if guess_age==age_of_sun:
        print('you got it')
        break
break is to end the current entire loop
    elif guess_age>age_of_sun:
        print('smaller')
    else:
        print('smaller')
    count+=1
    if count==3:
        confirm=input('continue?')
        if confirm != 'n':
            count=0

7. Homework

Work requirements:

  • Write the login interface
  • Enter username and password
  • Welcome after successful authentication
  • Lock account after entering three times

Work ideas:

  • Account locked with file storage more than three times
  • Before the user logs in, determine whether the account is in the file, and if so, mention it 

First edition of the work:

#Author:Yueru Sun
#Write the login interface, enter the username and password, after the authentication is successful, the welcome message will be displayed, and it will be locked after entering it three times.
_username='sunyueru'
_password='sunny@0321'
def lock(username):
    #Write username to lock file
    f=open('lockuser','r+')
    f.write(username)
    f.close()
def check_lock(username):
    f=open('lockuser','r+')
    for name in f:
        if username in name:
            print("Your account is locked")
    f.close()
def main():
    count=0
    while True:
        username=input('Please enter username:')
        # Determine if the account is locked
        check_lock(username)
        password=input('Please enter the password:')
        if username==_username and password==_password:
            print("Login successful")
            break
        else:
            count+=1
            print('Login failed')
            if count>=3:
                #lock account
                lock(username)
                print('You have entered wrong three times and your username is locked')
                break
main()

Improved version:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324974199&siteId=291194637