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:
- Input
- Output
print("Hello Python!")
Hello Python!
Assigning variables
- Input
- Output
a = 5
b = 3
a + b
8
- Input
- Output
a * b
15
- Input
- Output
a - b
2
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
- Input
- Output
greeting = "Hello"
name = "Pranab"
print(greeting + " " + name)
Hello Pranab
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:
- Input
- Output
my_str = "Rain! "
my_str * 3 # multiplying a str with int
'Rain! Rain! Rain! '
Input
Collecting user input:
- Input
- Output
age = input("How old are you? ")
type(age)
How old are you? 34
<class 'str'>
Notice that variable assigned from input
is a string, even if a number is
entered.
Type conversion
- Input
- Output
age = int(age)
type(age)
<class 'int'>
String formatting
- Input
- Output
"Singapore".upper()
'SINGAPORE'
- Input
- Output
"Singapore".lower()
'singapore'
- Input
- Output
"das".capitalize()
'Das'
- Input
- Output
"pranab das".title()
'Pranab Das'
- Input
- Output
"ABCDefgh".swapcase()
'abcdEFGH'
- Input
- Output
name = 'Pranab'
age = 34
print("Name: {0}. Age: {1} years.".format(name, age))
Name: Pranab. Age: 34 years.
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.")