Skip to main content

Python Basics

Python is a dynamically typed, interpreted language. Python interpreter is written in C-language. Interpreter program reads and performs the Python codes/ instructions. The interpreters interacts with the operating system layer (use network, keyboard, mouse, monitor, hard drive etc.).

Hello Python

It is customary to write our first program that prints some message in the screen:

print("Hello Python!")

Assigning variables

a = 5
b = 3
a + b
a * b
a - b
Good to know

Due to how the numbers are stored in computer memory, floating point algebra sometimes might produce unexpected results. Notice the following discrepancy (floating point addition/ subtraction is not associative):

>>> (1.2 + 1E20) - 1E20
0.0
>>> 1.2 + (1E20 - 1E20)
1.2

String concatenation

greeting = "Hello"
name = "Pranab"
print(greeting + " " + name)

For performance improvement and better readability, consider using join instead of in-place string concatenation.

" ".join([greeting, name])

Loosely typed

As we have seen, we do not need to define the datatype in python. Interestingly, for certain operations, we can even mix types:

my_str = "Rain! "
my_str * 3 # multiplying a str with int

Input

Collecting user input:

age = input("How old are you? ")
type(age)
note

Notice that variable assigned from input is a string, even if a number is entered.

Type conversion

age = int(age)
type(age)

String formatting

"Singapore".upper()
"Singapore".lower()
"das".capitalize()
"pranab das".title()
"ABCDefgh".swapcase()
name = 'Pranab'
age = 34
print("Name: {0}. Age: {1} years.".format(name, age))

You can also format in the following way:

print("Name: {name}. Age: {age} years.".format(name=name, age=age))

Starting from Python 3.6 and above:

print(f"Name: {name}. Age: {age} years.")