Python Examples That Put the Fun in Understanding Fundamental Syntax

pythonexamplesIf you are interested in web development, you should learn Python programming. This high-level scripting language is also used in desktop GUIs and database access applications. It is based on a mix of object-oriented, procedural and structured programming fundamentals.

Python includes a large library of functions, and along with its user-friendly syntax, it makes code much shorter than that written in C or similar languages. Go through these Python examples to understand its basic syntax.

Learn Python with this Beginner’s Course on Udemy!

Print Statement and Comments:

You can write Python code to display strings, variable values, or the results of mathematical computations to the user. These data types can also be concatenated in a single print statement, separated by commas as follows:

>>> print “Sum of two and two is”, 2+2 #Example of addition in Python

This example includes a comment, starting with a hash. It is not necessary to write a comment on a new line, but any text following the hash will be ignored by the compiler. So the output here will be:

Sum of two and two is 4

Variable Declaration

In Python, there is no need to declare the variable type, since the compiler automatically understands it.

Integer Variables

>>> i = 1

>>> print i, i*5

>>> #the value of i is still unchanged

>>> i = i*5

>>> print “The value of i has multiplied five times. It is now equal to”,  i

The output of this piece of code will be:

1, 5

The value of i has multiplied five times. It is now equal to 5

String Variables

For string variables, simply include the string text in quotes. You can write simple Python code to experiment with variable concatenation, as follows:

>>> string1 = “hello”

>>> string2 = “world”

>>> print string1, string2

>>> string3 = string1 + ” ” + string2

>>> print string3

Both print commands will give the same output:

hello world

Are you an entrepreneur? You can learn Python by building an eCommerce site in this course!

Iterative Loops

You will notice a clear Indentation of four spaces in all Python examples. This not only ensures readability, but is essential to indicate the start and end of loops and nested functions to the compiler.

While Loop

>>> i = 1

>>> while i < 5:

>>>     print i

>>>     i = i + 1

>>> print “you have reached the end of the while loop.”

Because of the indentation, the display screen will show the numbers 1, 2, 3, and 4, then followed by the final sentence printed only once.

If-Else Statement

The format of the If statement in Python is similar to any other programming language. Elif is the shorter name for the Else If condition.

>>> a = 3, b = 2

>>> if a > b:

print a

elif a == b:

print a, b

else:

print b

Here, the output will be 3.

Summary

It is fairly straightforward to learn the Python syntax. This makes it one of the most popular programming languages today.