Python Basics-Conditional judgment and looping

Source: Internet
Author: User

I. INPUT and OUTPUT

How does python receive user input, use the input function, use Raw_input in Python2, receive a string, output, the first program has been written using print, code into the following:

1 name=input (' Please enter your name: ') #把接收到的值赋给name变量2 print (name) #输出接收到的输入

Input at the time of receiving inputs, you can see the value you entered, if you enter a password like this, do not want to let others see your password, how to do it, you need to use a standard library, Getpass, what is the standard library, is not need you to install, loaded Python on the library, is the standard library, Getpass is a standard library, import in, directly using the Getpass.getpass method can be entered at the time, do not echo, the code is as follows:

1 Import getpass #导入getpass模块        2 password = getpass.getpass (' Please enter your password: ') #接收输入的密码3 print (password)

Two. Conditional judgment

In Python, the conditional judgment uses if else to judge, multi-branch words using if elif ... else, that is, if how to what kind of how, otherwise how to do so.

If the judgment is true or false, that is true and false. The format is as follows:

1 if      so tomorrow with an umbrella 3 else: 4     tomorrow without an umbrella 

Python is indented to represent the code block, so it looks like the code is very organized, such as the above example, if it rains tomorrow, then tomorrow will bring an umbrella, tomorrow with an umbrella is equivalent to the son of if, so you can also think that there is a parent-child relationship, write an example of the actual point, as follows:

1 score = Int (input (' Enter your score: ')) #接收输入, because input receives a string, the INT function is required to cast the type into an integer type 2 if score==100: #如果成绩等于100分的话3     Print (' Little genius, you are fullmark ') 4 Elif score >=90 and score <: #如果成绩大于等于90分小于100分的话5     print (' brother, your score is not low, good ') 6 Elif score > Score <90: #如果成绩大于60分小于90分的话7     print (' brother, this exam is so sloppy ') 8 else: #如果分数小于60分的话9     print ( ' Brother, what are you doing, the effort? '  

Three. Cycle

What is the cycle is to do, the white is for you to repeat the thing, for example, you want to build 1000 folders, a build exhausted you, so you can write a section of code, use the loop to create 1000 for you to save time, Python has two loops, while and for, the difference between the two loops, While loop before, first judge once, if the condition is met, then loop, for loop must have an iterative object, in order to loop, for example, there is an array, it is worth mentioning that in other languages, for loop needs to define a counter variable, and then starting from 0 to add, Until this counter reaches your preset value, and then stops the loop, and when the data is taken from the array by the subscript 0, it is troublesome that the for loop in Python is very simple, looping through an element in an iterative object, how many elements you have in the object, how many times you are looping, For example, an array list,list = [' A ', ' B ', ' C '], in other languages to get to the list of all the values, you have to use the loop to take off the mark this way to fetch the data, you have to write list[x],list[x],list[x] so, In Python there is no need to directly loop on the list of values, the loop inside there are two more important keywords, continue and break,continue mean, jump out of this cycle, continue the next cycle, break means to stop the loop, That is, the code below continue and break is not executed, in the following format:

For loop:

1 #There are two kinds of loops inside Python2 # while3 # for4 #count = 8 #计数器5 #While count<10:6 #print (' Hou ning tell jokes! ')7 #count=count+18 ##循环体9 #Else:Ten #print (' Hou Ning is done. ')

Break, exit the loop, break can only be used in the loop, if you encounter a break in the loop, then immediately exit the loop

1 # count = 0  # counter 2# while count <:3#     print (' Hou Ning tell jokes! ')4#     count = count + 15#     if count==5:  6#          break

The use of continue, the role of continue is to exit this cycle

1 # count = 0  # counter 2# while count <:3#     count = Count + 14#     if count==5:5#         continue  6#     print (' Hou ning tell the joke! '%count)

For loop, inside of break

1 #For I in Range (Ten):2 #print (' Hou ning tell jokes,%s '%i)3 #if i==6:4 # Break5 #For continue usage6 #For I in Range (Ten):7 #if i==7:8 #Continue9 #print (' Hou ning tell jokes,%s '%i)Ten  One #For count in range (1,11): #顾头不顾尾 A #print (count) - #Else: - #print (' Over ... ') the ##for循环对应的else, only executed if the For Normal loop is finished

Four. Formatted output

What is formatted output, that is, your output is formatted into a look, such as login welcome information, are welcome to Login,marry. Each user login is welcome, but each user's user name is the same, you can not write a line of code for a user, which requires the use of formatted output, there are three ways, the first is to use "+" connection, directly the output of the string and the variable is connected to it, and the second is to use a placeholder, There are three commonly used placeholders,%s,%d, and%f,%s are the following values are a string,%d is the following value must be an integer,%f is followed by a decimal, the third is the {} and Fromat methods, these three, the official recommendation is to use the Format method, is not recommended to use the first type, The first use of the Plus, will be in memory to open up a number of memory space, and the latter two is only a piece of memory space, using the following:

1 # name = input (' Please enter your name: ') 2 # sex = input (' Please enter your gender: ') 3 # print (' welcome you ' +name) #第一种用 + connection 4 # print (' welcome you ', name) #第二种用, connect 5 # print (' Welcome you to%s '%name) #一个变量的时候使用占位符 6 # print (' Welcome to%s ', your gender is%s '% (name,sex)) #多个变量的时候使用占位符. This is the inside of a number of formatted content, the front is a string, the following is an integer, a number of variables followed by the value of the time must be added parentheses
 7 #%d for the following variable is an integer 
8 #%f represents the decimal%.2f followed by a few decimals, rounding
9age = Int (input ('Please enter an integer:'))
TenGrade = Float (input ("Please enter your score:"))
One #print (' Input integer is%d, the score entered is%.2f '% (age,grade))
A #print (' Your score is%.2f '%grade)
- Print('your age is {Your_age}, your score is'
- '{Your_grade}'. Format (your_age=age,your_grade=grade))
the #using placeholders is simpler if the parameters are relatively small - #If the parameters are more than the case, the format is more straight in the form of. format

Five. Practice

1 #Random Number Module2Sub_str=random.randint (1,101)#generate a random number of 1-1003  while1:#while the meaning is, let it always be true, that is, the dead loop, below the break to stop the loop4Num=int (Input ('plase Enter a num, 1-100:'))5     ifnum>100orNum<1:#determine if the number entered is between 1-1006         Print('num error,plase enter 1-100.')7         Continue8     Else:9         ifNUM==SUB_STR:#If you guessed it, end the loop.Ten             Print('You win. Game over,the num is%d'%SUB_STR)#If you don't understand this, look at the following 14th, string format output One              Break A         elifNum < sub_str:#If the guess is small, jump out of this cycle, the hint guess small -             Print('The num is small,plase enter other Num.') -             Continue the         Else:#on three kinds of cases, big, small equals, the front two is equal and drizzle, then else is greater than, if guess big, jump out of this cycle, the hint guess big -             Print('The num is too big,plase enter other Num.') -             Continue

Python Basics-Conditional judgment and looping

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.