Python Language and standard library (chapter I: Making decisions)

Source: Internet
Author: User
Tags for in range

1-making decisions

2-function

3-Classes and objects

4-Organizational procedures

5-Files and directories

Other features of the 6-python language

7-Creating a module

8-Text Processing

Chapter One: Making Decisions

This chapter describes how to create a case where you can repeat the same actions with loops, automatically traversing lists, tuples, and dictionaries.

How to use dictionaries, lists, and tuples to explore the contents of a dictionary.

Use a process-written program to address issues that might be handled within the program.

1.1 Comparison of two values for equality

In Python, if each element in the same position in each sequence is the same, then two sequences are the same. Dictionaries are compared in the same way as sequences.

1.2 Comparison of two values

!=

1.3 Comparing the size of two values

It is worth noting that we can use a special method lower () to avoid the problems caused by two similar words due to different case.

>>>"Pumpkin"= ="Pumpkin"False>> >"Pumpkin". Lower () = ="Pumpkin". Lower () True >>>"pumpkin". Upper ()'pumpkin '

1.4 Reverse the truth and false values

>>> not truefalse>>> is 5False>>> not 0True>>> nottrue error

In this case, any non-0 is True

Results of more than 1.5 comparison operations

and or non-

 and truetrue  and TrueFalse or falsetrue

How to make decisions

>>>if 1>2:           print("No it is not! " )>>>if 2>1:           print("Yes it is! "  is!

Only if the value of the statement between the IF and the colon is true, the indented statement is accessed and evaluated by Python.

In a Python program, when you see a colon, it indicates that Python has entered a relatively separate part of the program from the rest. In this case, indentation becomes important. Python knows that a particular block of code remains independent from the surrounding code by indenting. The number of spaces used is important.

Nesting Tests in Tests

>>>omelet_ingredients = {"Egg": 2,"Mushroom"75A"Pepper": 1,"Cheese": 1,"Milk": 1}>>>fridge_contents+{"Egg": 10,"Mushroom": 20,"Pepper": 3,"Cheese": 2,"Tomato": 4,"Milk": 15}>>>have_ingredients =[False]>>>iffridge_contents["Egg"]>omelet_ingredients["Egg"]: have_ingredients[0]=True Have_ingredients.append ("Egg")>>>Print(have_ingredients) [True,'Egg']

Make a cross-statement

>>>oj_price = 2.50>>>ifoj_price<1.25:           Print("Get One, Im thirsty.")       elifoj_price<=2.00:           Print("ummm........sure,but Ill Drink it slowly.")       Else:           Print("I dont has enough money. Never mind.") I dont has enough money. Never mind.

1.6 Cycles

>>>i = 10>>> while i>0:print("Lift off in:"  )print(i) I= i-1

This is using the while loop

>>> for in range (10,0,-1):print("t_minus:"  )print(i) ... T-minus:tenT-minus:9t-minus:8 ...

For-in Cycle

1.6 Terminating the Loop

Let's take a look at the code

>>>age =0>>> whileTrue:how_old= Input ("Enter your Age:")ifHow_old = ="No":    Print("dont be ashamed of your age!")     BreakNum=Int (how_old) age= age+NumPrint("Your Age is:")Print("That is old!")... Enter Your Age:1Your Age is:1 that isold! Enter Your Age:2your Age is: 3... Enter your age:nodont be ashamed of your age!

In this statement, the while is always true, so it will continue to loop, in order to solve this problem, to give users some information, if no, will break, jump out of the loop.

Continue the cycle with continue

>>> forFoodinch("Pate","Cheese","Rotten Apple","Crackers","Whip Cream","Tomato Soup"):...         ifFood[0:6] = ="Rotten":...             Continue...             Print("hey you can eat%$"% food)

The printing results are:

Because of the use of an If ... Test to determine if the first part of each item in the food list contains the string "rotten", and all "rotten Apple" will be skipped and the rest printed out.

1.7 Handling Errors

Errors typically contain a large amount of information about the cause of the error and failure:

>>>fridge_contents = {"Egg:8","Mushroom": 20,"Pepper": 3,"Cheese": 2,"Tomato": 4,"Milk": 13}>>>iffridge_contents["Orange Juice"]>3:...        Print("lets have some juice!")...

Printing results:

Oh! There is no orange juice in the fridge at present. A way to find out all the keys that appear in the dictionary is described earlier, you can use the keys method of the dictionary, and then search in the returned key list to determine whether a desired key appears.

Using the TRY: statement

A try statement establishes a situation in which a try statement can be followed by a except statement. Each except statement handles an error, which we call an exception. Use except first: Handle a type of error, such as getting a keyerror error while trying to check the refrigerator.

There are multiple types of exceptions, each of which responds to the problem, and may also reflect the condition in which the exception occurred. Because the dictionary has keys and values, Keyerror indicates that Python expects some type of data, which can be a string or an integer value, but it is a different type that does not satisfy the requirement.

For example:

Create an exception and describe the exception:

In the dictionary fridge_contents there is no key "orange juice", Python throws a Keyerror exception, stating that there is no such key, in addition to specifying the name error. Python will use it to refer to a string that contains the error information that Python can provide. We send the value of Keyerror to error by using the AS keyword. In this way, the string is related to a key that has been requested but not present in the dictionary fridge_contents (orange juice).

Sometimes we need to deal with an exception, but we don't want to handle it in other ways, we can ignore it by pass.

Python Language and standard library (chapter I: Making decisions)

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.