Skip to content

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:

print("Hello, world!")

Output:

Hello, world!

Output a variable value:

i = 256*256
print('The value of i is:', i)

Output:

The value of i is: 65536

Define variables and perform simple mathematical operations:

x = 3
y = 2
z = x + y
print(z)

Output:

5

Define a list and print its elements:

my_list = ['google', 'runoob', 'taobao']
print(my_list[0]) # Output "google"
print(my_list[1]) # Output "runoob"
print(my_list[2]) # Output "taobao"

Output:

google
runoob
taobao

Use a for loop to print numbers 0 to 4:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

Output different results based on conditions:

x = 6
if x > 10:
    print("x is greater than 10")
else:
    print("x is less than or equal to 10")

Output:

x is less than or equal to 10

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.

#!/usr/bin/python3
 
# Fibonacci series: Fibonacci sequence
# The sum of two elements determines the next number
a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b

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:

n=b
m=a+b
a=n
b=m

Executing the above program produces the following output:

1
1
2
3
5
8

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:

n = 10
a, b = 0, 1
for i in range(n):
    print(b)
    a, b = b, a + b

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:

#!/usr/bin/python3
 
# Fibonacci series: Fibonacci sequence
# The sum of two elements determines the next number
a, b = 0, 1
while b < 1000:
    print(b, end=',')
    a, b = b, a+b

Executing the above program produces the following output:

1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,