Getting Started with Python (11) conditional judgment and looping

Source: Internet
Author: User

Getting Started with Python (11) conditional judgment and cyclic condition judgment

Computers can do a lot of automated tasks, because it can make their own conditions to judge.

For example, enter the age of the user, print different content according to age, in the Python program, with the if statement implementation:

20if age >= 18:    print ‘your age is‘, age print ‘adult‘

According to the indentation rules of Python, if the if statement is judged True , the indented two lines of the print statement are executed, otherwise, nothing is done.

It is also possible to if add a else statement, meaning that if the if judgment is False , do not execute if the content, go to put the else executed:

3if age >= 18:    print ‘your age is‘, age print ‘adult‘else: print ‘your age is‘, age print ‘teenager‘

Be careful not to write a colon less : .

Of course, the above judgment is very sketchy, can be used to elif do more detailed judgment:

3if age >= 18:    print ‘adult‘elif age >= 6: print ‘teenager‘else: print ‘kid‘

elifis else if the abbreviation, can have more than one elif , so if the complete form of the statement is:

<条件判断1>:    <执行1>elif <条件判断2>: <执行2>elif <条件判断3>: <执行3>else: <执行4>

ifStatement execution has a characteristic, it is to judge from the top, if in a certain judgment True , the corresponding statement of the judgment is executed, ignore the remaining elif and else , so, please test and explain why the following program printed teenager :

20if age >= 6:    print ‘teenager‘elif age >= 18: print ‘adult‘else: print ‘kid‘

ifThe judging conditions can also be abbreviated, such as writing:

if x:    print ‘True‘

As long as a non- x 0 value, a non-empty string, a non-empty list, etc., it is judged True , otherwise False .

Cycle

There are two types of Python loops, one is the for...in loop, and each of the elements in the list or tuple is iterated in turn to see an example:

names = [‘Michael‘, ‘Bob‘, ‘Tracy‘]for name in names: print name

Executing this code will print names each element in turn:

MichaelBobTracy

So the for x in ... loop is to take each element into the variable and x then execute the indented block of the statement.

For example, if we want to calculate the sum of 1-10 integers, we can use a sum variable to accumulate:

0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + xprint sum

If you want to calculate the sum of 1-100 integers, writing from 1 to 100 is a bit difficult, but fortunately Python provides a range () function that generates a sequence of integers, such as range (5), which generates a sequence that is less than 0, starting from 5:

range(5)[0, 1, 2, 3, 4]

Range (101) can generate a sequence of 0-100 integers, calculated as follows:

0for x in range(101):    sum = sum + xprint sum

Please run the above code on your own, to see if the result is 5050 of the students ' mental arithmetic.

The second loop is the while loop, which, as long as the condition is satisfied, loops continuously, exiting the loop when the condition is not satisfied. For example, we want to calculate the sum of all the odd numbers within 100, which can be implemented with a while loop:

0n = 99while n > 0:    sum = sum + n    n = n - 2print sum

The loop internal variable is n continuously self-reducing until -1 it becomes, and the while condition is no longer satisfied, and the loop exits.

Another discussion on Raw_input

Finally see a problematic condition to judge. Many students will raw_input() read the user's input, so that they can input, the program runs more interesting:

birth = raw_input(‘birth: ‘)if birth < 2000:    print ‘00前‘else: print ‘00后‘

Input 1982 , and the results show 00后 that this simple judgment of Python can be mistaken?

Of course it's not a Python problem, print it out in Python's interactive command line birth :

>>> birth‘1982‘>>> ‘1982‘ < 2000False>>> 1982 < 2000True

Reason to find out! The original raw_input() read from the content is always returned as a string, the string and integer comparison will not get the expected results, you must first int() convert the string to the integer type we want:

birth = int(raw_input(‘birth: ‘))

Run again to get the right results. But what if I enter abc it? And you get an error message:

call last):  ...ValueError: invalid literal for int() with base 10: ‘abc‘

Originally int() found a string is not a valid number when the error, the program exited.

How do I check and capture the program run-time errors? The subsequent errors and debugs will be covered.

Summary

Conditional judgment allows the computer to make its own choices, and Python's if...elif...else is flexible.

Loops are an effective way to make a computer do repetitive tasks, and sometimes, if the code is written with a problem, it causes the program to fall into a "dead loop", that is, to cycle forever. You can then either Ctrl+C exit the program or force the end of the Python process.

Please try to write a dead loop program.

Getting Started with Python (11) conditional judgment and looping

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.