Python Tutorial (18) - First Steps in Programming

Time: Column:Python views:296

In the previous tutorials, we have already learned some basic syntax of Python3. Now, let's try some examples.

Print a String:

Example

print("Hello, world!")

Output:

Hello, world!


Print Variable Value:

Example

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

Output:

The value of i is: 65536


Define Variables and Perform Simple Arithmetic Operations:

Example

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

Output:

5


Define a List and Print Its Elements:

Example

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

Output:

google
runoob
taobao


Use a for Loop to Print Numbers from 0 to 4:

Example

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

Output:

0
1
2
3
4


Output Different Results Based on a Condition:

Example

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


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+)

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

In this code, the line a, b = b, a + b calculates the values on the right-hand side first, then assigns them simultaneously to a and b. This is equivalent to:

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

Output:

1
1
2
3
5
8

This example introduces several new features. The first line contains a compound assignment: the variables a and b simultaneously receive the new values 0 and 1. In the last line, the same method is used again. The expression on the right-hand side is evaluated before the assignment takes place, and the evaluation follows a left-to-right order.


You Can Also Implement This with a for Loop:

Example

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


end Keyword

The end keyword can be used to print results on the same line or add different characters at the end of the output, as shown below:

Example (Python 3.0+)

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

Output:

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