Python3 First Steps in Programming
In the previous tutorials, we have learned some basic Python3 syntax knowledge. Now let’s try some examples.
Print a string:
Example
Section titled “Example”Output:
Output a variable value:
Example
Section titled “Example”Output:
Define variables and perform simple mathematical operations:
Example
Section titled “Example”Output:
Define a list and print its elements:
Example
Section titled “Example”Output:
Use a for loop to print numbers 0 to 4:
Example
Section titled “Example”Output:
Output different results based on conditions:
Example
Section titled “Example”Output:
Next, let’s try to write a Fibonacci sequence.
The Fibonacci sequence is a classic mathematical problem where each number is the sum of the two preceding ones.
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The code a, b = b, a+b works by first evaluating the right-hand expression and then simultaneously assigning to the left-hand side, which is equivalent to:
Executing the above program produces the following output:
This example introduces several new features.
The first line contains a compound assignment: variables a and b simultaneously get the new values 0 and 1. The last line uses the same method again. As you can see, the right-hand expression is evaluated before the assignment changes take effect. The evaluation order of the right-hand expression is from left to right.
You can also use a for loop to implement it:
Example
Section titled “Example”end Keyword
Section titled “end Keyword”The end keyword can be used to output results on the same line or add different characters at the end of the output, as shown in the example below:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Executing the above program produces the following output: