### python Introduction learning ：6. User input and while loop

Key points ： Input 、while loop

### 6.1 function input() working principle

function input() Pause the program , Wait for the user to enter some text . function input() Take a parameter ： That is, the prompt or instruction to be displayed to the user , Let the user know what to do .

``1message = input("Tell me something, and I will repeat it back to you:")2print(message)   # Returns the value entered ``

6.1.1 Use int() Get numeric input
Using functions input() when ,python Interpret user input as a string .

`` 1age = input("How old are you? ") 2print(age)                        # Input age = '21' 3if age > 18 :                     # Strings cannot be compared with integers  4    print("you are old") 5else: 6    print("you are too young") 7 8How old are you? 23 92310Traceback (most recent call last):11  File "chapter6.py", line 6, in <module>12    if age > 18 :13TypeError: unorderable types: str() > int()``

adopt int() Function to convert the obtained string to an integer

`` 1age = input("How old are you? ") 2age = int(age) 3print(age)                         4if age > 18 :                     5    print("you are old") 6else: 7    print("you are too young") 8How old are you? 23 92310you are old``

6.1.2 Modulo operators
Modulo operators (%) It's a very useful tool , It divides two numbers and returns the remainder ：

``14 % 321     # Remainder is 135 % 342     # Remainder is 256 % 360     # Remainder is 0``

### 6.2 while Introduction to cycle

6.2.1 Use while loop
for Loop a block of code for each element in the collection , and while The cycle goes on and on , Until the specified conditions are met .

``1current_number = 12while current_number <=5:3    print(current_number)4    current_number +=1``

6.2.2 Let the user choose when to quit
You can use while Loop allows the program to run continuously when the user wants to , Control exit through user input

``1prompt = "\nTell me something,and I will repeat it back to you:"2prompt +="\nEnter 'quit' to end the program.\n"3message = ""4while message != 'quit':5    message = input(prompt)6    if message != 'quit':7        print(message)``

6.2.3 Use logo
occasionally , Many conditions are required to be met before the program continues to run , You can define a variable , Used to determine whether a program is active , This variable is called the flag , Act as traffic lights for the program .

``1active = True2while active:3    message = input(prompt)4    if message == 'quit'5        active = False6    else:7        print(message)``

6.2.4 Use break Exit loop
Use keywords break You can end the current loop immediately

``1prompt = "\nPlease enter the name of a city you have visited:"2prompt+= "\n(Enter 'quit' when you are finished.) "3while True:4    city = input(prompt)5    if city == 'quit'6        break;7    else:8        print("I'd love to go to " + city.title() +"!")``

6.2.5 Use... In a loop continue
Use continue End this cycle , Returns when the loop starts .

``1current_number = 0;2while current_number < 10:3    current_number +=14    if current_number %2 == 0:5        continue6    print(current_number)``

### 6.3 Use while Loop through dictionaries and lists

for Loops are an effective way to traverse lists , But in for The list should not be modified in the loop , Otherwise, it will lead to python It's hard to track its elements . To modify the list while traversing , You can use while loop .
6.3.1 Move elements between lists
Suppose there is a list , It contains newly registered but not yet verified website users ; After verifying the user , How to transfer them to another verified user list ？

`` 1unconfirmed_users = ['alice','brain','candace'] 2confirmed_users = [] 3while unconfirmed_users: 4    current_user = unconfirmed_users.pop() 5    print("Verfying user: "+ current_user.title()) 6    confirmed_users.append(current_user) 7# Show all authenticated users  8print("\nThe following users have been confirmed:") 9for confirmed_user in confirmed_users:10    print(confirmed_user.title())``

6.3.2 Delete all list elements that contain specific values
To delete multiple duplicate elements in a list, you can use while loop

``1pet = ['dog','cat','dog','goldfish','cat','rabbit','cat']2print(pets)3while 'cat' in pets:4    pets.remove('cat')5print(pets)``

## python Introduction learning ：6. User input and while More articles about circulation

1. Python Notes on programming from introduction to practice —— User input and while loop

Python Notes on programming from introduction to practice —— User input and while loop #coding=utf-8 # function input() Pause the program , Wait for the user to enter some text . After getting the user's input, store it in a variable , Convenient for subsequent use ...

2. python introduction （6） Input and output

python introduction (6) Input and output Output >>> print 'hello, world' >>> print 'The quick brown fox', 'jum ...

3. Python Introduction learning ：1. Variables and simple data types

python Introduction learning :1. Variables and simple data types Key points : Variable . character string . Numbers 1.1 Variable naming and use 1.2 character string 1.3 Numbers 1.4 notes 1.1 Variable naming and use Variable , As the name suggests, it's a variable quantity , ...

4. python The way ： User input （ One ）

python The way : User input ( One ) Okay , Now I've learned a little bit about blogging , It's not as rustic as it used to be . ok , Not much to say , I'm going to give a lecture . today , I'll give you a scenario example of this user input . The scene is : You are a IT Educational python Take the lead ...

5. python Introduction learning ：9. Files and exceptions

python Introduction learning :9. Files and exceptions Key points : file . abnormal 9.1 Reading data from a file 9.2 write file 9.3 abnormal 9.4 Store the data 9.1 Reading data from a file 9.1.1 Read entire file First create a pi_ ...

6. python Introduction learning ：8. class

python Introduction learning :8. class Key points : class 8.1 Create and use classes 8.2 Use classes and instances 8.3 Inherit 8.4 Import class 8.1 Create and use classes Object oriented programming is one of the most effective software writing methods . In object oriented programming , You write ...

7. python Introduction learning ：7. function

python Introduction learning :7. function Key points : function 7.1 Defined function 7.2 Transfer argument 7.3 Return value 7.4 Delivery list 7.5 Pass any number of arguments 7.6 Store functions in modules 7.1 Defined function Use keywords def ...

8. python Introduction learning ：5. Dictionaries

python Introduction learning :5. Dictionaries Key points : Dictionaries 5.1 Using dictionaries 5.2 Ergodic dictionary 5.3 nesting 5.1 Using dictionaries stay python A dictionary is a series of keys - It's worth it . Each key is associated with a value , You can use the key to access the related ...

9. python Introduction learning ：4.if sentence

python Introduction learning :4.if sentence Key points : Judge 4.1 A simple test 4.2 Conditions for testing 4.3 if sentence 4.1 A simple test if The basic format of the statement is as follows , Be careful not to miss the colon 1if  Conditions  :2     ...

## Random recommendation

1. Folder lock （Source）

Folder lock (Source)private void Lock(string folderPath){    try    {        string adminUserName = Environ ...

2. Git Learning notes —— One NB Distributed version control system

1. command : git init           Create a new warehouse ( In an empty file and then execute the command ) git clone  + route       Check out warehouse , From local or server git status     check ...

3. Protobuf One click code generation bat file

I've been fiddling with Unity Of Socket, Need to use Protobuf, There are usually multiple protocol files , So I studied bat Batch processing of , The batch file code is shown below : @echo off :: Protocol file path , Finally, don't talk to “\” Symbol ...

4. jquery obtain checkbox The chosen value

Just one cycle , You can find out who's chosen checkbox Value var s; \$("[name = b]:checkbox").each(function () {              ...

5. Archlinux stay Btrfs Installation on partition （bios piece ）

In fact, all the contents of this article are Archwiki You can find it all , And it's updated and more comprehensive ( It's just scattered ), What I've done is just a little summary of the installation process , I'll explain each step a little bit , But it won't be particularly detailed , After all, this is just an installation guide , instead of ...

6. Openlays 3 Draw basic figures

<body> <div id="menu"> <label> Geometry type :</label> <select id=" ...

7. MySQL Optimization five SQL Optimize

1. Reduce IO frequency IO It's always the easiest place for a database to bottleneck , This is determined by the responsibility of the database , More than in most database operations 90% All the time is IO Occupied by operation , Reduce IO Times is SQL Optimization needs to be the first priority , Of course ...

8. ubuntu Set up github Secret key

github Of SSH The configuration is as follows : One . Set up Git Of user name and email: \$ git config --global user.name "AmyOrz" \$ git ...

9. POJ 3254 Simple compression DP

Nothing to say , Entry level pressure DP. Just roll it off #include <iostream> #include <cstring> #include <cstdlib> #inc ...

10. 【Android】10.0 UI Development —— How to write program interface 、 Use of common controls

************************ Reprint please indicate the source :https://www.cnblogs.com/xiaofu007/p/10331880.html ***************** ...