How Python defines variables, dictionaries, len() functions, if, else, for, and the application of indentation

Python learning notes

How Python defines variables, dictionaries, len() functions, if, else, for, and the application of indentation

I was a little excited to share my blog for the first time. I have done civil engineering project management for ten years, because of code attraction and interests. Teach yourself python in your spare time, while reading, recording and sharing. Today is the tenth day of self-study. You are welcome to criticize and correct. PS is old and easy to spray. Ha ha.

No more nonsense, simple and rough code

Objective overview: define the key value pair dictionary, traverse the dictionary and print the corresponding information.

#coding:utf-8
favorite_languages={           #Define the dictionary of key value pairs for the variable "favorite_language".
    'jen':['python','ruby'],
    'sarah':['C'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }

for name,languages in favorite_languages.items():#The variables "name" and "languages" are defined here
    if len(languages)<2:       #len(* *) function indicates the number of variables "* *"; Then the variable "languages" will be recognized.
        print("\n"+name.title()+"'s favorite language is: ")
        
    else:
        print("\n"+name.title()+"'s favorite languages are: ")

    for language in languages:
        print("\t" + language.title())

Let's take a look at the debugging output:

Jen's favorite languages are:
        Python
        Ruby

Sarah's favorite language is:
        C

Edward's favorite languages are:
        Ruby
        Go

Phil's favorite languages are:
        Python
        Haskell
Press any key to continue . . .

The above code reflects the two ways of defining variables, defines the key value pair dictionary, len() function, for statement and if else statement.
#1. How to define a variable: variable = * * *, or define a key value pair in for. The variable name corresponds to the key value pair in the dictionary.
exp. favorite_ In languages = {}, {} represents the set of key value pairs‘ A ': [' b '], a is the key, b is the value;': ' Indicates correspondence; [] represents a set of values within; The key and value are respectively identified with ''.
Exp. in the for statement, the variables name and language are defined in another way instead of "=". When python identifies them, an important information is "," so name is the key, languages is the value, and "name, languages" forms a key value pair representation in the for statement.
#2. Len() function. When () is null, len() counts the total number of characters by default; When len () needs to count the total number of a certain value, you can write the name (variable) of the value into (). At this time, the variables in () need to be defined.
exp. in this example, the variable languages has been defined in the for statement, so not defined will not appear.

Next, let's look at how to use for to traverse the key value pair dictionary without the if statement.

#coding:utf-8
favorite_languages={           #Define the dictionary of key value pairs for the variable "favorite_language".
    'jen':['python','ruby'],
    'sarah':['C'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }

for name,languages in favorite_languages.items():#The variables "name" and "languages" are defined here

    print("\n"+name.title()+"'s favorite languages are: ")

    for language in languages:
        print("\t" + language.title())

Take a look at the debugging output effect:

Jen's favorite languages are:
        Python
        Ruby

Sarah's favorite languages are:
        C

Edward's favorite languages are:
        Ruby
        Go

Phil's favorite languages are:
        Python
        Haskell
Press any key to continue . . .

The printing effect is almost the same, but it is not difficult to find that Sarah's output is not accurate enough. She has only one favorite language.

Next, let's take a look at the contrast effect when the indentation of the last for statement in the code line changes.

#coding:utf-8
favorite_languages={           #Define the dictionary of key value pairs for the variable "favorite_language".
    'jen':['python','ruby'],
    'sarah':['C'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }

for name,languages in favorite_languages.items():#The variables "name" and "languages" are defined here

    print("\n"+name.title()+"'s favorite languages are: ")

for language in languages:
    
    print("\t" + language.title())

Debugging output:

Jen's favorite languages are:

Sarah's favorite languages are:

Edward's favorite languages are:

Phil's favorite languages are:
        Python
        Haskell
Press any key to continue . . .

From the change of the indentation of the for statement, the difference is very huge. Then it can be concluded that when the indentation changes, its corresponding logical relationship changes.
#1. Indentation, which represents the running level and order in python. The first for statement has no indentation and represents a large or overall traversal loop. When the second for statement is indented to be equivalent to the first print (), the for statement follows the overall or large traversal loop; When the second for statement is not indented, the for statement at this time cannot participate in the overall or large traversal cycle. It is only printed after the overall traversal cycle is completed.

----------------------Draw a thick bar--------------------
Talk about if, elif, else
When I first came into contact with if sentences, my dry heart always felt moist, like finding the feeling of love more than ten years ago.
if you love me (condition):
Kiss me
else:
rolling
-----------=------------
if you love me (condition):
Kiss me
elif (you love him):
Kiss him
else:
rolling
------------=------------
if you love me (condition):
Kiss me
elif (you don't love me):
OK
-----------=------------
To sum up, we can see that the first if else structure is fierce and absolute. If you don't like it, you can walk away quietly and don't have to climb continuously (the content of if is limited, and else has more options, so it's hard to imagine. ps system security is easy to go wrong, and it's possible that any other kind of potential will be summarized into else in addition to the if contained in the code).
. . . . . . . . The second if elif else structure, love me, kiss me, no problem. Love him, kiss him, it seems that there is nothing wrong. This structure contains another known option besides me, and there are other unknown options. ps is the same as the first one above, and all other situations except these two methods (if elif) are summarized into else)
. . . . . . . . In the third if elif structure, this kind of conversation is easier and sounds more comfortable: if you love me, kiss me. If you don't love me, you can. (in this case, I only accept two cases, and I won't accept and intervene in other cases. In system security, I accept all the conditions I judge. In other cases, sorry, goodbye)

----------------------One more cut to the point----------------------------

Looking back, let's deal with the problem that Sarah's output is not accurate enough.
In favor_ Languages = {} the key value is the favorite of some people in the dictionary_ Languages are one kind and there are two kinds, so we need to judge them when outputting, and then output more accurate messages.
For the judgment of one or two, we have the function len().
What kind of message should we output when it is a kind of message; When there are two, which message do we output. We have a judgment statement if.
Add len (Languages) < 2 to judge that you like a language. Otherwise, there are two. (here, because we only have two situations to judge.)
Upper Code:

#coding:utf-8
favorite_languages={           #Define the dictionary of key value pairs for the variable "favorite_language".
    'jen':['python','ruby'],
    'sarah':['C'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
    }

for name,languages in favorite_languages.items():#The variables "name" and "languages" are defined here
    if len(languages)<2:       #len(* *) function indicates the number of variables "* *"; Then the variable "languages" will be recognized.
        print("\n"+name.title()+"'s favorite language is: ")
        
    else:
        print("\n"+name.title()+"'s favorite languages are: ")

    for language in languages:
        print("\t" + language.title())

Debug output: (that's what we saw at the beginning)

Jen's favorite languages are:
        Python
        Ruby

Sarah's favorite language is:
        C

Edward's favorite languages are:
        Ruby
        Go

Phil's favorite languages are:
        Python
        Haskell
Press any key to continue . . .

Ha ha, it should be over when I write this. The above is my learning record and sharing. Thank you for your patience in reading.
See You~

I want to add a solemn explanation: the book I studied is "Introduction to Python programming to practice" written by Eric Matthes. Part of the code comes from this book, and the rest is original.

Tags: Python

Posted by MNSarahG on Wed, 13 Apr 2022 23:34:10 +0930