Chapter vii. User input and while loop

7.1 function input() How it works

function input() Will pause the program for a while , Wait for the user to enter some text . After getting the text entered by the user ,python Store it in a variable , So that we can use .

function input() Receive a parameter : That is, the prompt or instruction to be displayed to the user , Let users know how to do . Input variables are stored in message.

7.1.1 Write a clear program

You can put a space after a colon , Let users clear where to start .

The figure above shows a way to create a multiline string . The first line stores the first half of the message in the variable nn in ; In the second line , Operator += It's stored in nn The string is appended to the end of the string in ( It feels like C Linguistic +=. Namely nn= First half part + In the second half, we input )

7.1.2 Use int() To get numerical input
analysis :

Using functions input() when ,python Interpret the user's input as a string .

We type in 21,python When providing a value , On return ‘21’, But according to the previous judgment , There should be false, But it's wrong , because python Cannot compare string to integer , So the characters ‘21’ Unable to join 19 Compare

result :

So we can use it int() function , He will let python The input is a numerical value .

function int() Convert a string of numbers to a numeric representation .

Apply it to real life ...

7.1.3 Modulo operators

Processing numerical information , Modulo operators (%) It's a good tool . Namely Division returns the remainder

Make a solution to the problem :

I forgot when I entered “+str(shu)+”.....

msg = input(" Please enter the name of the car you want to rent :")

print("Let me see if I can find you a " + msg)

Feel like this is not necessary to add at the end of the line .. It feels so simple , It's a face ....

7.1.4 stay python2.7 Get the input

Not with input(), Using functions raw_input() To prompt the user for input . And with python3 The same as , Interpret the input as a string .

7.2 while Introduction to cycle

for Loop is used for a block of code for each element of the collection , and while The cycle goes on and on , I know I'm not satisfied .

7.2.1 Use while loop

Don't explain ...

7.2.2 Let the user choose when to quit

Only the input quit You can quit , Otherwise, it's going to cycle all the time

We create a variable --message, Give Way python First execution while There's something to check when you run a line of code .python First execution while When the sentence is , Need to put message The value of is equal to ‘quit’ Compare .

Further modification and beautification , Give Way quit Messages don't print out .

It's a direct exit .

7.2.3 Use logo

In a program that requires many conditions to be met to continue running , You can define a variable , It is used to judge whether the whole program is active or not . This variable is called the flag

It can control whether the program can be carried out .

use active As a sign ,(ture,false Initial must be capitalized , Don't be able to , Otherwise, it will report a mistake .) If user input ‘quit’, So we're going to put variables active Set to False, This will lead to while The loop no longer executes .

7.2.4 Use break Exit loop

To quit immediately while loop , No longer run the rest of the code in the loop , No matter what the conditional test results are , You can use break.

With while Ture The beginning of the cycle , Only meet break Will stop .

In this program , Only the input quit To terminate the current cycle . So much so that python Exit loop .

brwak Statement can also be used to exit from traversing a list or dictionary for loop .

7.2.5 Use... In a loop continue

To return to the beginning of the loop , And according to the result of condition test, decide whether to continue to execute the loop .

Unlike break Jump straight out of the loop , It's skipping , similar C Linguistic continue

1 To 10 The odd number :

Don't explain ...

7.2.6 Avoid wireless loops


while x <5 :


If it's in the loop , It can be used ctrl+c, You can also close the terminal window that displays the program output

This is an exercise , It used to be msg Variable , unchanged , The last input value will appear in the next loop , So we're going to use two variables ..

7.3 Use while Loop to process lists and dictionaries

By way of while The loop is the same as the list 、 Dictionaries come together , Can be collected 、 Store and organize large amounts of input , For later viewing and display .

7.3.1 Move elements between lists

Don't explain ...

7.3.2 Delete all list elements that contain specific values

In chapter three , Method of use remove() Delete specific values , To delete all elements in the list that contain specific values, you need to ---

use while Loop reattachment method remove()

Until it doesn't appear again in the list remove Value , Stop the cycle .

7.3.3 Use user input to fill the dictionary


Looking at this question , A little confused , After asking the boss , got it .

stay responses[name] in , We just added variables name Input the value of to the dictionary , Why is there... On the penultimate line name and response Usage of , I'm lost here , Because I am not familiar with the dictionary , After looking at it again , got it , key - It's worth it ....................

Chapter viii. function

A function is a named block of code , For specific work .

I like this chapter best , It's interesting , Ha ha ha ha , Woo woo

8.1 Defined function

This is a simple function structure , The first line of code uses keywords def tell python You need to define a function . And then to python Point out the function name . Here it is , The function is called greet(), It doesn't need any information to do its job , because kuohaoshikongde( Even so , You can't miss the brackets ), Last , The definition ends with a colon .

Feel similar C The definition of a language is like a macro

Keep up with the def gret(): The following indentation becomes the body of the function ,greet() Only one job : Print cao......

To use this function , First we need to call it .

To call a function , You must specify the function name and the information enclosed in brackets in turn .

8.1.1 Passing information to a function

Add... In parentheses name, You can make the function accept what you give name Any value specified . Now? , This function requires us to call it for name Specify a value .

call greet() when , You can pass a name on to him . Just like the one above .

Code greet('youxiu') Call function greet(), And provide him with executive print The information needed for the statement .

When called, no matter what name is transferred , Will generate the corresponding output .

8.1.2 Arguments and formal arguments

In the example above , Variable name It's a formal parameter -- Function to do its job .

In the code greet('youxiu') in ,'youxiu' It's an argument .

An argument is a call to a function, a message passed to it .

principle : We call functions , Put the information you want the function to use in parentheses . stay greet('youxiu') in , Real parameter 'youxiu' Pass to function greet(), This value is stored in the formal parameter name in .

It can also be in def Where? , Define two formal parameters

8.2 Transfer argument

8.2.1 Location parameter

Location parameter

When you call a function ,python Each argument in a function call must be associated with a parameter in the function definition , therefore , The simplest way to relate is based on the order of arguments .

Where it's easy to make mistakes : forget def After the end of : The colon

Quotation marks for arguments

1. Call function many times

On the next line, type in the format of the last line

In the function , Any number of positional arguments can be used as needed ,python The arguments in the function call are sequentially associated with the corresponding formal parameters in the function definition .

2. The order of positional arguments is important

Confirm that the order of the arguments in the function call is the same as the order of the formal parameters in the function definition .

8.2.2 Keyword arguments

Keyword arguments :

Is the name passed to the function - It's worth it . You can associate a name with a value directly in an argument , So there's no confusion when passing arguments to functions .

The order of keyword arguments doesn't matter , because python Know which parameter each value should be stored in . So it's equivalent in the diagram above .

Be sure to accurately indicate the formal parameter name of the function definition

8.2.3 The default value is

When you write a function , You can give each parameter a default value . When an argument is provided to a formal parameter in the calling function ,python The specified argument value will be used ; otherwise , The default value of the formal parameter will be used .

Call this function , If you don't give it a value ,python Just set this parameter to beibei

I think we only used one argument above dog, In the absence of a special statement , They all correspond to formal parameters in order , therefore name Is the default value .

8.2.4 Equivalent function call

It's the same with either one , Just conform to your own habits , I feel that when there are few formal parameters , In simple ’‘, If there are too many, use the one with the formal parameter name .

8.2.5 Avoid argument errors

When more or less arguments are provided than the function needs to complete its work , An argument mismatch will occur .

python It is found that the function call lacks necessary information , and traceback Point out this

The second line points out where the problem is

The third line indicates that there is a problem with the function call

The fourth line says we're missing two arguments , And the names of corresponding formal parameters are pointed out .

8.3 Return value

Functions don't directly display output , Sometimes , It can process some data , Return to one 、 The value of the group . The value returned by a function is called the return value ...

8.3.1 Returns a simple value

This output Chen Youxiu

In programs that need to store a large number of first names and last names separately , Functions like this are easy to use ,

8.3.2 Make arguments optional

Sometimes it only provides now,last, Not provided lasted, He's not going to work properly . By equals to lasted=’ ‘ To make it optional , You can provide a default value for its value , An empty string , And use this argument when the user doesn't type .

Optional values allow functions to handle a variety of situations at the same time , Make sure the function calls as much as possible

8.3.3 Return dictionary

person() Accept now and last, And encapsulate these values in a dictionary . Stored in now when , Use the key ’now‘.. Finally, the original two items of text information are stored in a dictionary

8.3.4 Use a combination of functions and while loop

The interpretation of this code : Think of the first three lines as a block of code , That's to capitalize the arguments entered below , And add up .

Here's an infinite loop , When the input q Will stop . The first three lines give the full name , And then print

 Write a project called make_album() Function of , It creates a dictionary of music albums .
# This function should take the singer's name and album's name , And return a dictionary containing these two items of information . Use this function to create three dictionaries representing different albums ,
# And print each returned value , To verify that the dictionary correctly stores the album information . To the function make_album() Add an optional parameter ,
# In order to store the number of songs included in the album . If the number of songs is specified when calling this function , Add this value to the dictionary representing the album . Call this
# function , And specify the number of songs the album contains in at least one call .
def make_album(singer_name,album_name,song_number = ''):
if song_number:
s_a = {'singer_name':singer_name,'album_name':album_name,'song_number' : song_number}
s_a = {'singer_name':singer_name,'album_name':album_name}
return s_a
a = make_album('HanHong','QingZangGaoYuan','5')
b = make_album('AndiLiu','WangQingShui')
c = make_album('LiuHuan','YouAndMe','7')
# 8-8 User albums : In order to complete the exercise 8-7 In the program , Write a while loop , Let the user enter the singer and name of an album .
# After obtaining this information , Use them to call functions make_album() , And print out the created Dictionary . In this while In circulation , Be sure to provide an exit route .
def make_album(singer_name,album_name,song_number = ''):
if song_number:
s_a = {'singer_name':singer_name,'album_name':album_name,'song_number' : song_number}
s_a = {'singer_name':singer_name,'album_name':album_name}
return s_a s_n_inp = ' Please enter the name of the singer :( Input ’quit‘ After exit )'
a_n_inp = ' Please enter the album name :( Input ’quit‘ After exit )'
ac = True
while ac:
a = input(s_n_inp)
b = input(a_n_inp)
if a == 'quit' or b == 'quit' :# I can also use it in the front , Forget to use ......
break# perhaps ac=False It's fine too ..
c = make_album(a,b)

8.4 Delivery list

After passing the list to the function , Function can directly access its contents .

We will greet() Defined as a received list , And store it in names in . This function iterates through the received list , And print a greeting to each of them .

What's wrong : keyword def I forgot to add :

for Indent

8.4.1 Modify the list in the function

It's about step-by-step functions , That is, each function is responsible for a specific task . There are two , This is better than using a function to do the work . And it's like C Language pointer call , This helps to divide more complex tasks into a series of steps .

8.4.2 It is forbidden to modify the list of functions

occasionally , You need to prevent the function from modifying the list . You can pass a copy of the list to a function instead of the original ; Any changes made to this function only affect the copy , It doesn't affect the original at all .

To pass a copy of the list to the function


Slice representation [:] Create a copy of the list .

This section is a bit of a mystery ...

The fans are back , Although passing a copy of the list to the function preserves the contents of the original list , but Unless there's a good reason to send a copy , Otherwise, the original list should still be passed to the function , Because having a function implement a ready-made list avoids taking time and creating copies .

# 8-10 Great magician : Before you finish the exercise 8-9 And in the program , Write a project called make_great() Function of ,
# Modify the list of magicians , Add words to every magician's name “theGreat”. Call function show_magicians() , Make sure the list of magicians has changed .
name_list = ['mag1','mag2','mag3']
name_change = []
def make_great(name_list,name_change):
while name_list:
cur = name_list.pop()
cur = 'thegreat' + cur
name_change.append(cur)# It's right up there name——list and name——change The transfer of def show_magicians(name_change):
for name in name_change:
print(name) # This starts printing make_great(name_list,name_change)
# 8-11 Constant magician : Revise your exercises for completion 8-10 And the program you write , Calling function make_great() when , Pass it a copy of the magician list .
# Because I don't want to modify the original list , Please return to the modified list , And store it in another list . Use these two lists to call show_magicians() ,
# Make sure a list contains the original magician's name , The other list contains the words added “the Great” The name of the magician .
name_list = ['mag1','mag2','mag3']
name_change = []
def make_great(name_list,name_change):
while name_list:
cur = name_list.pop()
cur = 'great' + cur
name_change.append(cur)# It's right up there name——list and name——change The transfer of def show_magicians(name_change):
for name in name_change:
print(name) # This starts printing make_great(name_list[:],name_change)

8.5 Pass any number of arguments

The name of the parameter *cai The asterisk in makes python Create a file called cai Empty tuples of , And encapsulates all the values received in the tuple . Output proof :python Be able to handle calling functions with a value , Can also handle three values to call the case .

8.5.1 Use a combination of positional arguments and any number of arguments

If you want a function to accept different types of arguments , Formal parameters that accept any number of arguments must be placed last in the function definition .python First match location arguments and keyword arguments , Then collect the remaining arguments into the last formal parameter .

8.5.2 Use any number of keyword arguments

occasionally , You need to accept any number of arguments , But I don't know what kind of information is passed to the function . We can write functions that can accept any number of keys - It's worth it --- Accept as much as the call statement provides .

Shape parameter **user It's the other way around first,last All the parameters outside are encapsulated inside , And the code is traversing the key in the dictionary - It's worth it , And put each key - Value pairs are added to the dictionary profile in . Finally, the dictionary returns to the function line call .

# 8-12 Sandwich : Write a function , It accepts a range of ingredients customers want to add to their sandwiches . This function has only one parameter ( It collects all the ingredients provided in the function call ) ,
# And print a message , Give an overview of the sandwiches the customer ordered . Call this function three times , Different numbers of arguments are provided each time .
def sand_make(*ingredients):
print( ' The added ingredients are :')
for i in ingredients:
print('--' + i) sand_make('1','2','3','4')

Any number of arguments ..

# 8-13 User profiles : Copy the previous program, Call in it build_profile() To create a profile about you ;
# When this function is called , Specify your first and last name , And three keys that describe you - It's worth it .
def profile(name,location,**user):
for key,value in user.items():
return profile

Any number of keyword arguments are used .

8.6 Store functions in modules

One of the advantages of functions : They can separate the code block from the main program . By giving the function a descriptive name , It makes the main program easier to understand .

just so so , Store functions in separate files called modules , Then import the module into the main program .

import Statement allows the code in the module to be used in the currently running program file .

8.6.1 Import the entire module

First you need to create the module . The extension of the module is called .py, Contains the code to import into the program .

my notepad++ I can't lead , This section is over , Later use pycharm Make it up

python7、8 More related articles in this chapter

  1. 《Django By Example》 The fifth chapter chinese translate ( Personal learning , Dregs turning )

    Books come from : The original author :Antonio Melé ( translator @ucag notes : Hello everyone , I'm a new translator , ...

  2. ASP.NET MVC with Entity Framework and CSS The second chapter of a series of articles on book translation : Using model classes to create views 、 Controllers and databases

    In this chapter , We're going straight into the project , And add some basic model classes for products and categories . We will be in Entity Framework In code first mode , Use these model classes to create a database . We'll also learn how to create database context classes in the code ...

  3. 《Django By Example》 Chapter four chinese translate ( Personal learning , Dregs turning )

    Books come from : The original author :Antonio Melé ( translator's note : Happy new year to you all , This time it brings <D ...

  4. 《Django By Example》 The third chapter chinese translate ( Personal learning , Dregs turning )

    Books come from : The original author :Antonio Melé ( translator's note : Chapter three scalding out of the oven , Please do not make complaints about the text ...

  5. 《Django By Example》 Chapter two chinese translate ( Personal learning , Dregs turning )

    Books come from : The original author :Antonio Melé ( translator's note : After translating the first chapter , Find the speed of translating chapter two ...

  6. 《Django By Example》 Chapter one chinese translate ( Personal learning , Dregs turning )

    Books come from : The original author :Antonio Melé ( translator's note : I am currently working in an Internet company in Hangzhou , ...

  7. ASP.NET MVC with Entity Framework and CSS The first chapter of a Book Translation Series : Create basic MVC Web Site

    In this chapter , We will learn how to use the base frame to quickly build and run a simple Microsoft ASP.NET MVC Web Site . Before we jump right into learning and coding , Let's first learn something about ASP.NET MVC and Entity ...

  8. ASP.NET Core Chinese document Chapter four MVC(4.2) Routing of controller operations

    original text :Routing to Controller Actions author :Ryan Nowak.Rick Anderson translate : Lou Yu (Lyrics) proofreading : What town sunseeker . Yao a yong (Dr.Yao) ASP.NE ...

  9. [Hadoop in Action] The first 7 Chapter The rulebook

    Passing custom parameters to a task Get information about the mission to be determined Generate multiple outputs Interact with relational databases Sort the output globally   1. Pass job customized parameters to the task         Writing Mapper and Reducer when , I usually want some places to match ...

  10. MyBatis3.2 From introduction to mastery of chapter one

    Chapter one . introduction mybatis It's a persistence layer framework , yes apache Top projects under .mybatis Trusteeship goolecode Next , And then to github Next .( Baidu Encyclopedia has an explanation ) Two . summary mybatis Let the program focus on ...

Random recommendation

  1. 【 turn 】Description Resource Path Location Type Java compiler level&amp;n

    Reprinted address : Right click on the project Properties->Project Facets, On the Pr ...

  2. append,appendTo and prepend #1daae2

    1.append(content)                                                                                   ...

  3. SQL Operation statement

    SQL Server T-SQL Advanced query Advanced queries are most frequently used in databases , It's also the most widely used . Ø Basic common query --select select * from student; --all Query all ...

  4. SOCKet Programming brief introduction

    “ Everything is Socket!” It's a little exaggerated , But the truth is, too , Today's network programming is almost all used socket. —— Thanks for practical programming and open source project research . We understand the value of information exchange , How do processes communicate with each other in the network , For example, we open and browse everyday ...

  5. json date convert

    function getDateTime(jsondate) { var date = new Date(parseInt(jsondate.replace("/Date(", & ...

  6. XML The saving node of learning

    XmlDocumnet WriteTo Method explain : preservation xmldocument Object node to xmlwriter( namely xml File write stream ) example : public static void WriteXml( X ...

  7. SSH It uses jQuery Of ajax

    I'm really excited today ! In my SSH The project used jQuery The asynchronous transfer of is successful , After more than a day of fighting , accomplished ! My project requirements are javascript To me controller( namely :action) Transmission of form Forms ...

  8. Python The decorator of the entry function

    Contents of this chapter : Decorator : One . Why use decorators Two . What is a decorator 3、 ... and . No reference decorator Four . Decorator grammar sugar 5、 ... and . Authentication decorator implementation 6、 ... and . Overlay multiple decorators 7、 ... and . Ornament with ginseng ======================== ...

  9. LeetCode(34)-Palindrome Number

    subject : Determine whether an integer is a palindrome. Do this without extra space. Ideas : Find whether an integer is a palindrome tree . Negative numbers are not , ...

  10. Use mvc + entityframework + sqlServer Build a simple code first project

    step : 1. Create a mvc project 1.1 The structure of the project is as follows 2 adopt vs install EntityFramework frame install-package entityframework 3. ...