This is the third day of my participation in Gwen Challenge.

Hello, Hello, I am gray little ape, a super bug writing program ape!

Recently found that many started learning programming friend suffer from programming more difficult, and there are a lot of friend want to learn programming but suffer from does not have the resources, so for all of you here today blasting technology related to liver Python introductory, Python or suffer from introduction to programming for first contact friends, collect carefully! I believe it will help you learn Python!

This article continues to update, welcome friends to collect attention!

Don’t say much to open liver directly!

The name and type of the data – variables and types

Preliminary Study on data types

Before we begin this section, you need to understand that we are now learning to write programs. So what do you need to know before you write a program?

The main function of a program is to process data. There are many kinds of data. The words, numbers, pictures, videos, page styles that we see on our phones and computers are all data. These data are processed by the program and displayed on the screen.

Although there are many different kinds of data, and some of them seem complex, they are actually represented by some very basic data forms (or combinations) when programming. What are some of these basic data forms? There are commonly used numbers and characters, as well as other forms such as arrays and byte sequences.

Using numbers and characters as examples, I’ll show you how they are represented in code.

For numbers, they are written in code just as they would be written on a computer:

123
Copy the code

3.14159
Copy the code

In Python code, characters must be enclosed in either single or double quotation marks:

'How are you? 'Copy the code

'hi! 'Copy the code

These different data representation (writing) forms correspond to different types of data, and different types of data have different functions or functions.

We call the types of data in our code data types, that is, the types of data.

The data type

All data in the code is typed.

The data types for numbers are integer and floating point. Integer indicates an integer number, for example, 0, -59,100. Floating point represents decimal numbers, such as -3.5, 0.25, and 0.0.

The data type of a character is called a string, and a string is a string of characters. It can contain characters in any language, such as’ hem, ha, hey ‘, ‘Good, Good Study’. Of course strings can have only one character, such as ‘a’.

There is a type for “yes” or “no” called the Boolean type. Its value is called a Boolean and can only be True or False. It’s like a true or false answer question in an exam. You can only get a “yes” or “no” answer.

And then there’s a very special type: None, which means nothing. It just takes on a value of None.

Note: In order not to increase your memory burden, here are only the five basic data types, we slowly grasp the following.

Here’s a question for you. Is 1000 the same thing as ‘1000’ in code? The answer is different, one is a number, one is a string, different data types.

The numerical computation

In the case of integers and floating-points, since they are both used to represent numbers, it makes sense that they can do numeric operations, such as addition, subtraction, multiplication, and division.

Let’s go into Python interpreter interaction mode and try out these numerical operations by typing code:

  • add

    33 + 725Copy the code

    > > > 33 + 725 758

  • subtraction

    12 to 24Copy the code

    > > > 12-24-12

  • The multiplication

    8 * 12.5Copy the code

    > > > 8 * 12.5 100.0

  • division

    A thirdCopy the code

    > > > 0.3333333333333333 by one-third

  • In addition to more than

    10% 3Copy the code

    > > > 10% 3 to 1

As you can see, the addition (+), subtraction (-), multiplication (*), division (/), and division remainder (%) of a numeric value can be evaluated. These operations are also common in many programming languages, and Python also has built-in power operations (**) and division (//) :

  • To the power

    2 * * 3Copy the code

    > > > 2 * * 3 8

  • aliquot

    9 / / 2Copy the code

    > > > 9 / / 2, 4

This is probably the simplest use of Python — as a calculator!

Note: usually we in order to beautiful, the operation symbol above the left and right of each plus a space, such as 12-24, 2 ** 3.

We’ll add whitespace in later code examples.

Comparison operations

In addition to numeric operations, integer and floating point types can do comparison operations, that is, compare the size of two values. The result of the comparison is a Boolean value. Such as:

2 > 3
Copy the code

>>> 2 > 3

False

2 < = 3Copy the code

>>> 2 <= 3

True

2 = = 3Copy the code

>>> 2 == 3

False

Comparison operators can be greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), equal to (==), not equal to (! =). This is similar to the comparison operation in mathematics, but the difference is that “equal” and “not equal”, especially that “equal” is represented by two equal signs ==.

Variables and assignments

So now that we’ve looked at numerical calculations, let’s figure out how many seconds there are in a week, how many seconds there are in a year.

First of all, it’s not hard to figure out that there are 60 * 60 * 24 seconds in a day. We can temporarily record this result in some way for future use. In what way? We can use variables.

A variable is simply a name that the programmer gives to some data in the code, and using the name later in the programming process is equivalent to using the data behind it. To put it simply, we can think of variables as temporary containers that hold data in code.

The act of creating a variable is called defining a variable. Here’s how to define a variable:

seconds_per_day = 60 * 60 * 24
Copy the code

Here we call it seconds_per_day and give it the result of 60 * 60 * 24 with the symbol =. The name seconds_per_day is our variable, and its value (the data behind it) is the actual result of 60 * 60 * 24. That is, we store the number of seconds of the day 60 * 60 * 24 in the seconds_per_day variable.

The equal sign (=) means assignment in code, assigning the value to the right of = to the variable to the left of =. Note that assignment is denoted by the equals sign =, while “equals” is denoted by == (two consecutive equals signs).

Seconds_per_day = seconds_per_day

>>> seconds_per_day

86400

Back to the “how many seconds are there in a week” question. With the seconds_per_day variable representing the number of seconds in a day, we can write our program like this:

seconds_per_day * 7
Copy the code

>>> seconds_per_day * 7

604800

Multiply the number of seconds in a day by seven (days) and the result is 604,800, no problem at all.

Here is the complete coherent code:

seconds_per_day = 60 * 60 * 24
seconds_per_day * 7
Copy the code

Benefits of variables

You might say, “Why don’t you just count 60 * 60 * 24 * 7 seconds in a week without using variables?” Yes, sometimes you can do without variables. One advantage of using variables is that you can temporarily store an intermediate result so that you can reuse it later.

Seconds_per_day = “how many seconds are there in a year”

seconds_per_day * 365
Copy the code

>>> seconds_per_day * 365

31536000

In addition to variables, you can improve the readability of your program by properly naming variables. For example, if we write 60 * 60 * 24 in code, it will be difficult for others (including your future self) to immediately understand what this means when they read it. Seconds_per_day = 60 * 60 * 24 Oh, the number of seconds in a day.

Update variables with assignments

The variable in the previous content is assigned at the time of the definition. In fact, the variable can be repeatedly assigned new values after the definition, so that the data in the variable is updated. Such as:

>>> day = 1

>>> day

1

>>> day = 2

>>> day

2

>>> day = 3

>>> day

3

The relationship between variables and data types

Variables are used to hold data, and data types are used to indicate the type of data.

Seconds_per_day = 60 * 60 * 24 we used seconds_per_day = 60 * 60 * 24 to define the variable seconds_per_day and assign it the value 60 * 60 * 24. Seconds_per_day is said to be an integer because it holds an integer value.

conclusion

The data type

The basic Python data types mentioned in this section are:

type

said

Value of the sample

integer

The integer

– 59100.

floating-point

The decimal

3.5, 0.01

string

The text

‘Hum, ha, hey’, ‘Good Good Study’

The Boolean

Is right and what is wrong

True, False

None type

Nothing at all

None

There’s more to Python than that, and we’ll cover that later, and the types in tables will be applied later.

The numerical computation

The symbols for numerical operations are:

symbol

meaning

The sample

+

add

1 + 1

-

subtraction

2-3

*

The multiplication

4 * 5

/

division

6/7

%

Take more than

8% of 9

支那

To the power

2 times 3. 2 to the third.

//

aliquot

5 / / 4

The numerical comparison

The symbols for numerical comparison are:

symbol

meaning

>

Is greater than

<

Less than

> =

Greater than or equal to

< =

Less than or equal to

= =

Is equal to the

! =

Is not equal to

It may seem like a lot, but it’s not really a memory load. Numerical operations and numerical comparisons are roughly the same concepts and symbols as in mathematics, only slightly different.

Variables and assignments

We define variables and assignments in the following form:

Variable name = data valueCopy the code

Multilingual comparison:

The purpose of this section is to give you an idea of how the basic features of the language described in this section are expressed in other languages. You can see how they know each other.

Unlike dynamically typed Python, statically typed languages also have length, which is the size of the data a type can hold. The type of a variable must be declared before it is defined. Take the integer type as an example. In Java, integers are divided into byte (1 byte), short (2 bytes), int (4 bytes), and long (8 bytes) based on their length. Floating point types are divided into float (4 bytes) and double (8 bytes). Other languages have something similar. Integers in C/C++ are “unsigned” (e.g., unsigned int for an unsigned int, which means 0 and positive numbers, not negative numbers).

Java defines variables and initializes them:

int yearDays = 365
Copy the code

C/C++ defines variables and initializes them:

int yearDays = 365 
Copy the code

The combination of C and C++ is called C/C++ because C++ is basically a much more powerful superset of C, and while C++ is not strictly 100% compatible with C, it is nearly.

The Go language defines variables and initializes them:

var yearDays int = 365
Copy the code

Variable definitions in Go require the keyword var and the data type (int in this case) after the variable name. Or we could write it another way:

yearDays := 365
Copy the code

This can omit not only the keyword var but also the data type, which can be derived directly from the compiler.

After a variable is defined in each of the above languages, it can be reassigned with the following statement:

yearDays = 366
Copy the code

How is a string of data stored — lists and strings

One problem with data types in the previous section is that most of the data types we’ve introduced are used to represent individual data. For example, an integer variable can only hold one integer. Another example is Boolean. A Boolean variable can hold only one Boolean value. The same is true for floating-point and None. If there is a set of data at the moment, how can it be saved and used in the program?

For example, when I have only one phone number, I can use integers and store them in variables:

tel = 13011110000
Copy the code

But if you have ten phone numbers, how do you represent and use them?

13011110000

18022221111

13433332222

13344443333

17855554444

13866665555

15177776666

13388887777

18799998888

17800009999

You might say, “Then use ten variables,” like this:

tel01 = 13011110000
tel02 = 18022221111
...
tel10 = 17800009999
Copy the code

Or “put them together with a comma and put them in a string” :

tels = '13011110000180222111134333222133444333178555444138666555151777666133888777187999888178000999, 'Copy the code

Yes, that seems to solve the problem. But the drawbacks of both approaches are also obvious. The first way to use multiple variables will be very tedious in the case of a large amount of data. The second way to use strings is inconvenient if we need to manipulate some of the data in them.

At this point we can choose to use lists.

List

A list is a data type used to hold bulk data. It is built into Python, along with data types such as integers and Booles.

The way you write a list

A list is written as [data item 1, data item 2…, data item N], with square brackets representing the list. Each data item is separated by a comma in square brackets.

The previous string of phone numbers can be saved like this:

tels = [13011110000, 18022221111, 13433332222, 13344443333, 17855554444, 13866665555, 15177776666, 13388887777, 18799998888, 17800009999]
Copy the code

Extension: For ease of reading, we can also write this list as multiple lines:

tels = [ 13011110000, 18022221111, 13433332222, 13344443333, 17855554444, 13866665555, 15177776666, 13388887777, 18799998888, 17800009999]Copy the code

One line per data item, isn’t that better?

When we type this multi-line code in the interpreter’s interactive mode, we see that the prompt for the first line is >>>, and for each line after that the prompt becomes… , until multiple lines of input are completed and then it changes back to >>>. Such as:

>>> Tels = [… 13011110000,… 1802222111111,… 13433332222…] >>>

The data in the list can be of any type. Such as integers, strings, and Booleans:

[100, 'about', True]
Copy the code

List index

Each data item in the list is in order. The first data item is numbered 0, followed by 1, 2… N, this position number is called an Index in programming terminology. Note that in Python indexes are counted from 0, which is the first position.

The symbol [] can be used to obtain the data item corresponding to an index. Such as:

> > > fruits = [‘ apple ‘, ‘banana’, ‘cherry’, ‘durian] > > > fruits [0]’ apple ‘> > > fruits [2]’ cherry ‘

Fruits has 4 items, so the maximum index is 3. What if we force a larger index to fetch data? Try this:

Fruits [4] Traceback (most recent call last): File “”, line 1, in IndexError: list index out of range

The list index is out of range.

Extension: This is a typical Python error. There are three lines (or many lines), the first two describing the error location (such as a line in a file), followed by an error description indicating that this is an IndexError, The value is List index out of range.

If you encounter an error while writing code, you can use this method to try to analyze the error message yourself.

In addition to retrieving a value by index, you can also change the value of an item in a list by index. This is done by assigning:

fruits[0] = 'pear'
Copy the code

> > > fruits [0] ‘apple’

Fruits [0] = ‘fruit’ >>> fruits[0]

List length

The number of items in a list is called the length of the list.

To get the length of the list, you can use len(). Like this:

len(fruits)
Copy the code

>>> len(fruits)

4

>>> len([1, 2, 3, 4, 5, 6, 7])

7

Len () is a built-in function in Python. The concept of functions will be introduced in a later section.

Add data to the list

In previous use, the data in the list was determined at the beginning and remained the same length. But in many cases, we need to add data to the list at any time.

To add data to the end of the list you can use the.append() thing, which is written like this:

List.append (new data)Copy the code

Look at an example. You first create an empty list, name its variable fruits, and then add content to it with.append().

>>> fruits = []

>>> fruits

[]

>>> fruits. Fruit (‘ fruit ‘) >>> fruits [‘ fruit ‘]

> > > fruits. Append (‘ lemon ‘) > > > fruits [‘ pear ‘, ‘lemon’]

Extension: Append () is a list method. What “methods” are will be covered later in the Object-oriented section. For the moment, think of methods as a built-in function of a data type, like append() as a built-in function of a list.

String (String)

Strings can also hold bulk data, except that the data items are only characters.

We introduced strings in the previous section, and strings are data types used to represent text. A string consists of single or double quotation marks and several characters wrapped within them, for example:

"Who first saw the moon by the river, river moon, he shine at the beginning of the year."Copy the code

String index

Formally, we can see that the characters in a string are also ordered. Strings are ordered sequences of characters, so they also have indexes. You can also retrieve one of the characters based on the index. Indexes are used in the same way as lists:

'good good study'[3]
Copy the code

>>> ‘Good good study’ [3] ‘D’

You can also store strings in variables and use indexes on variables. The result is the same:

words = 'good good study'
words[3]
Copy the code

>>> Words = ‘good good study’ >>> Words [3] ‘D’

It is important to note that strings cannot be indexed like lists. Because string values are Immutable, we cannot modify a character in place.

>>> Words = ‘good good study’ >>> Words [3] = ‘b ‘Traceback (most recent call last): File “”, line 1, in TypeError: ‘STR’ object does not support item Assignment

TypeError: ‘STR’ object does not support item Assignment ‘STR’ object does not support item Assignment ‘TypeError:’ STR ‘object does not support item Assignment’

String length

The number of characters in a string is the length of the string (all whitespace including Spaces).

We get the length of the string in the same way as the list, using len() :

len('good good study')
Copy the code

>>> Len (‘ Good good study ‘) 15

conclusion

If we want to store and represent bulk data, we can use the List type in Python. A list is an ordered sequence that can hold any type of item. You can get and modify one of the items by Index, get the length of the list by len(), or append items to the end of the list by.append().

If the data is text, it can be represented as a String. The string type is an ordered sequence of characters, which can be retrieved at a position by index or length by len().

Lists and strings have a lot more functionality in Python, which I’ll cover later when I talk about “Data structures.”

Multilingual comparison:

Arrays are the most basic structure for storing and representing bulk data, and they are also the building blocks for constructing strings, collections, and containers.

Instead of an array, Python has a more advanced data structure called a list, which covers the power of arrays and provides more and more power.

In Java, arrays are represented by type [] :

// define array int numbers[]; Int numbers[] = {1, 2, 3};Copy the code

C/C++ defines arrays:

// Define array int numbers[3]; Int numbers[] = {1, 2, 3};Copy the code

The Go language defines arrays:

Var numbers = [3]int {1, 2, 3} var numbers = [3]int {1, 2, 3}Copy the code

There is more than one way — branches and loops

In the previous chapters we learned about data types, variables, assignments, numerical operations, and used that knowledge to write programs that could do something as simple as “count the number of seconds in a year.” In a program like this, the execution flow is completely fixed, with each step determined in advance and the runtime descending step by step in a linear fashion.

However, in many cases, the function of the program will be complex, and a single execution process cannot meet the requirements. The program may need to make judgment on some conditions when running, and then choose to execute different processes. This is where branch and loop statements come in.

Input (), print(), and int() functions

Before we start learning about branches and loops, let’s learn about three functions in order for our program to interact with us. As for what a function is, let’s think of it for the moment as a functional component of a program, which will be covered in more detail in the next section.

The input () function

If you want to interact with your program from the command line, use the input() function.

The input() function can output a prompt text at this point in code execution and then wait for our input. After typing and pressing the Enter key, the program reads the input and continues. The input read can be assigned to a variable for later use. It is written as follows:

Input read = input(' prompt text ')Copy the code

>>> age = input(‘ please input your age: ‘) Please input your age: 30 >>> age ’30’

This line of code displays “Please enter your age:” on the command line, waits for input, reads the input and assigns it to the age variable.

Input () returns the result as a string, such as ’30’. If we need an integer, we can use the int() function for the conversion.

The int () function

The int() function converts a string to an integer. Written as follows:

Int (string or floating point)Copy the code

Convert string type ‘1000’ to integer type 1000:

> > > int (1000 ‘1000’)

Convert floating point 3.14 to an integer:

> > > int (3.14). 3

The print () function

The print() function prints the specified content to the command line. It is written as follows:

Print (' What to print ')Copy the code

> > > print (” Hello World! “Hello World! >>> Print (‘ Your age is’, 20) Your age is 20

The output content is enclosed in parentheses. Multiple items are separated by commas, and each item is displayed separated by Spaces.

Input (), print() examples

We can combine input() with print(). For example, the following two lines of code will prompt “Please enter your age:” in the command line, and then wait for input. After manually entering the age, press the Enter key, and “your age is X” will be displayed.

Age = input(' Please input your age: ') print(' Your age is ', age)Copy the code

Save the code to a file named age.py and run:

➜ ~ python3 age.py Please enter your age: 18 Your age is 18

branch

The previous example was simple, taking input and displaying it. Now the difficulty level is up. Based on the previous code, if the entered age is less than 18, then at the end of the display an encouragement – “study hard, day day up”. How to do that?

If statement

If you want to say “If…” Or “When…” In this case, an if statement is required. It is written as:

If condition: code blockCopy the code

Its execution rule is that if the “condition” is met, the “code block” under if is executed, and if the “condition” is not met, it is not executed.

Condition satisfied means that the result of the condition is a Boolean valueTrue, or a non-zero number, or a non-empty string, or a non-empty list.

A code block is a piece of code (which can be one or more lines) nested under an if as a whole in indentation. According to the usual specification, indentation is represented by four Spaces.

Going back to our previous requirement, “when younger than 18” can be implemented with the if statement. The complete code is as follows:

Print (' Your age is ', age) if age < 18: print(' your age is ', age) if age < 18: print(' your age is ', age) Print (' Study hard, make progress every day ')Copy the code

Save it in a file and run it:

➜ ~ python3 age.py please enter your age: 17 Your age is 17 study hard and make progress day by day

➜ ~ python3 age.py Please enter your age: 30 Your age is 30

As you can see, when the input age is less than 18, the program outputs “study hard and make progress every day” at the end, but when the input age is older than 18, it does not.

Else statements

On the basis of the above, if the input age is 18 or older, the output “the revolution has not yet succeeded, comrades still need to work hard”. How do you do that?

We can use an else statement immediately after the if statement, and when the if condition is not met, the else block is executed directly. It is written as follows:

If condition: code block 1 else: code block 2Copy the code

If the conditions are met, code block 1 is executed; if not, code block 2 is executed. Therefore, the previous requirements can be realized as follows:

Age = int(input(' please input your age: ')) print(' please input your age: ') print(' please input your age: ') else: print(' Please input your age: ')Copy the code

Let’s see:

➜ ~ python3 age.py Please enter your age: 18 Your age is 18 the revolution has not been successful, comrades need to work

➜ ~ python3 age.py please enter your age: 17 Your age is 17 study hard and make progress day by day

Elif statement

We can see that if and else express “if… or else…” The conditions of such binary opposition are either/or. But sometimes we also need to say “if… or… or… otherwise…” Such a choice between multiple conditions.

For example, the table below shows ages and their corresponding life stages.

age

Life stage

0 to 6 years old

childhood

7 to 17

The young

18 to 40 years old

youth

41-65

middle-aged

After the 65 – year – old

The elderly

When we enter an age in the program, we output the corresponding life stage. How do you do that? Let’s first describe the code logic in Chinese (this kind of natural language description of the code logic, also called pseudo-code) :

If age is less than or equal to 6: Output childhood if age is between 7 and 17: output juvenile if age is between 18 and 40: output youth if age is between 41 and 65: output middle age otherwise: output old ageCopy the code

As you can see, we need to make multiple conditional judgments in turn. And to do that, we’re going to use the elif statement, which is literally short for else if.

Elif is placed between if and else, and can have any:

If condition 1: code block 1 ELIF condition 2: code block 2 else code block 3Copy the code

The previous output of life stage requirements according to age can be implemented as follows:

Age = int(input(' input ')) if age <= 6: print(' juvenile ') elif 7 <= age <=17: print(' juvenile ') elif 18 <= age <= 40: print(' juvenile ') elif 18 <= age <= 40: print(' juvenile ') elif 18 <= age <= 40: Print (' aged ') elif 41 <= age <= 65: print(' aged ') else: print(' aged ')Copy the code

➜ ~ python3 age.py Please enter age: 3 childhood ➜ ~ python3 age.py Please enter age: 17 juvenile ➜ ~ python3 age.py Please enter age: 30 youth ➜ ~ python3 age.py Please enter age: 65 Middle-aged ➜ ~ python3 age.py Please enter age: 100 old

Summary of branch statements

As mentioned above, if can be used with elif and else. When the code is executed, it will verify and judge successively from the first condition. If one of the conditions is met, the corresponding code block will be executed. At this time, the subsequent conditions will directly skip verification.

In an if-elif-else combination, elif can occur any number of times and else can occur 0 or 1 times.

The while loop

The if statement described earlier selects whether to execute or not execute a block of code based on conditions. Another important scenario is to determine whether a block of code should be executed repeatedly based on conditions, known as loops.

We can use a while statement in Python to execute a loop as follows:

While condition: code blockCopy the code

Its execution process is to start from the while condition, determine whether the condition is satisfied, if so, execute the code block, and then return to the while condition again, determine whether the condition is satisfied… The cycle repeats until the condition is not satisfied.

As you can see, if the conditions here are always met and fixed, then the loop will continue indefinitely, which is called an infinite loop. In general, we rarely use an infinite loop deliberately, but rather let the condition change, at some point in the loop the condition is not satisfied and then exits the loop.

Circular sample

For example, how do you print “you’re great” 100 times?

Obviously we can use loops to save code by designing the loop condition so that it ends exactly 100 times.

Count = 0 while count < 100: print(' you're cool ') count = count + 1Copy the code

Use a counter, count, to keep the number of loops, execute the loop when count is less than 100, and increment count by one each time the block executes. We try to simulate this process in the brain, using the brain to Debug.

Write the code to loop.py and run it:

➜ ~ python3 loop.py You’re good, you’re good, you’re good…

The program will print 100 lines of “You’re great,” as expected.

Extension: count = count + 1 can be shortened to count += 1

And, or, the opposite of the condition

Conditions in if and while statements can be expressed in combinations of statements.

And the key words

To express cases where more than one condition is met, use the and keyword. When the and keyword is used, the result is True if all juxtapositions are met. The result is False if at least one condition is not met. Such as:

>>> 1 and ‘ABC’ == ‘ABC’ and True True >>> 1 and 0! = 0 False

We can use the and keyword in an if statement like this:

If condition 1 and condition 2 and condition N: code blockCopy the code

The if statement above is executed only if all conditions are met.

For example, we assume that a man who is older than 30 and male is called uncle. “Older than 30” and “male” are two judgment conditions that need to be met at the same time. In this case, the and keyword can be used to express. Such as:

If age > 30 and sex == 'male': print(' male')Copy the code

The or keyword

To express situations where at least one of the conditions is sufficient, use the or keyword. When the or keyword is used, the result is True if at least one of the juxtaposed conditions is met. The result is False if all are not satisfied.

The or keyword can be used in an if statement like this:

If condition 1 or condition 2 or condition N: code blockCopy the code

As long as any one (or more) of the above if conditions are met, the code block is executed.

Not a keyword

The not keyword inverts a Boolean value. Such as:

>>> not True

False

>>>

>>> not 1 > 0

False

When used on conditions in if and while statements, the result of the condition is reversed.

The not keyword can be used in an if statement like this:

If NOT condition: code blockCopy the code

The above if statement executes the code block if the condition is not met, but not if the condition is, because the not keyword inverts the result.

The for loop

The while loop was introduced earlier, but there is another way to loop in Python — the for loop.

The for loop is more used to scan each item in a list, string, or other data structure from beginning to end, which is called traversal or iteration.

The for loop is written as:

For item in sequence: code blockCopy the code

This is done by repeatedly executing the for item in sequence statement and its code block, the value of the item being replaced by each data item of the sequence, until all items of the sequence have been iterated.

For example, if we have a list [‘apple’, ‘banana’, ‘cherry’, ‘durian’] and we want to print each of its list items in turn, we can use a for loop.

fruit_list = ['apple', 'banana', 'cherry', 'durian']

for fruit in fruit_list:
    print(fruit)
Copy the code

Write the code to for.py and execute:

➜ ~ python3 for.py

apple

banana

cherry

durian

As you can see,

  1. On the first cycle,fruitThe value ofapple
  2. On the second cycle,fruitThe value ofbanana
  3. On the third cycle,fruitThe value ofcherry
  4. On the fourth cycle,fruitThe value ofdurian

Fruit is automatically given a new value each time the loop is iterated until all the items in the fruit_list are iterated and the loop exits.

conclusion

The input() function outputs a text prompt at this point in the program, and then stands there waiting for our input. After entering the input, press enter, and the program reads the input and executes down. Written as follows:

Age = input(' Please enter your age: ')Copy the code

The print() function prints content to the command line in parentheses, separated by commas. Written as follows:

Print (' Your age is ', 20)Copy the code

The int() function converts a string to an integer. Written as follows:

Int (string or floating point)Copy the code

If, elIF, and else are used together to select the corresponding execution path according to the condition. Written as follows:

If condition 1: code block 1 elIF condition 2: code block 2 Else: code block 3Copy the code

The while statement uses an execution loop to determine whether a block of code should be executed repeatedly based on conditions. Written as follows:

While condition: code blockCopy the code

A for loop is typically used to perform traversal operations. Written as follows:

For item in sequence: code blockCopy the code

Multilingual comparison:

Branch statements in Java:

If (condition 1) {block 1} else if (condition 2) {block 2} else {block 3}Copy the code

Branch statements in C/C++

If (condition 1) {block 1} else if (condition 2) {block 2} else {block 3}Copy the code

Branch statements in Go:

If condition 1 {block 1} else if condition 2 {block 2} else {block 3}Copy the code

Loops in Java:

for (int i=0; i < 100; For (int number: numbers) {for (int number: numbers) {Copy the code

Loops in C/C++ :

for (int i=0; i < 100; I++) {code block}Copy the code

Loops in Go:

for i := 0; a < 100; // for each form for index, item := range numbers {block}Copy the code

If you have any questions or don’t understand, you are welcome to comment and leave a message!

We will continue to update you with Python introduction and advanced technology sharing!

Think useful small friends remember to like attention yo!

Grey ape accompany you to progress together!