Python3 First Steps in Programming
In the previous tutorials we learned some basic Python3 syntax; next let's try some examples.
Print a string:
Example
(
"Hello, world!"
)
The output is:
Hello, world!
Output a variable's value:
Example
i
=
256
256
(
'The value of i is:'
,
i
)
The output is:
i 的值为: 65536
Define variables and perform simple math operations
Example
x
=
3
y
=
2
z
=
x + y
(
z
)
The output is:
5
Define a list and print out its elements:
Example
my_list
=
[
'google'
,
'runoob'
,
'taobao'
]
(
my_list
[
0
]
)
Output "google"
(
my_list
[
1
]
)
Output "runoob"
(
my_list
[
2
]
)
Output "taobao"
The output is:
google
runoob
taobao
Use a for loop to print the numbers 0 through 4:
Example
for
i
in
range
(
5
)
:
(
i
)
The output is:
0
1
2
3
4
Output different results based on conditions:
Example
x
=
6
if
x
10
:
(
"x is greater than 10"
)
else
:
(
"x is less than or equal to 10"
)
The output is:
x 小于或等于 10
Next let's try writing a Fibonacci series.
The Fibonacci series is a classic mathematical problem in which each number is the sum of the two preceding ones.
Example (Python 3.0+)
#!/usr/bin/python3
Fibonacci series: the Fibonacci sequence
The sum of the two elements determines the next number
a
,
b
=
0
,
1
while
b
<
10
:
(
b
)
a
,
b
=
b
,
a
b
In the code a, b = b, a+b the right-hand expression is evaluated first and then assigned to the left-hand side simultaneously, which is equivalent to:
n=b
m=a+b
a=n
b=m
Running the above program, the output is:
1
1
2
3
5
8
This example introduces several new features.
The first line contains a multiple 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 expression on the right is evaluated before the assignment takes place. Right-hand expressions are evaluated from left to right.
It can also be implemented using a for loop:
Example
n
=
10
a
,
b
=
0
,
1
for
i
in
range
(
n
)
:
(
b
)
a
,
b
=
b
,
a + b
The end keyword
The end keyword can be used to output results on the same line, or to add a different character at the end of the output, as shown below:
Example (Python 3.0+)
#!/usr/bin/python3
Fibonacci series: the Fibonacci sequence
The sum of the two elements determines the next number
a
,
b
=
0
,
1
while
b
<
1000
:
(
b
,
end
=
'
,
'
)
a
,
b
=
b
,
a
b
Running the above program, the output is:
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,