Python Tutorial
Python is one of the most popular programming languages. It’s
simple to use, packed with features and supported by a wide
range of libraries and frameworks. Its clean syntax makes it
beginner-friendly.
A high-level language, used in data science, automation, AI,
web development and more.
Known for its readability, which means code is easier to write,
understand and maintain.
Backed by strong library support, we don’t have to build
everything from scratch.
Basic Code Example
The following is a simple program that displays the message
“Hello, World!” on the screen.
# Python Program to Print Hello World!
print("Hello World!")
Output
Hello World!
To understand working of this code, refer to our article Python
Introduction.
Why Learn Python?
Requires fewer lines of code compared to other programming
languages like Java.
1|Page
Provides Libraries / Frameworks like Django, Flask and many
more for Web Development, and Pandas, Tensorflow, Scikit-
learn and many more for, AI/ML, Data Science and Data
Analysis
Cross-platform, works on Windows, Mac and Linux without
major changes.
Used by top tech companies like Google, Netflix and NASA.
Many Python coding job opportunities in Software
Development, Data Science and AI/ML.
Basics
The basics of Python programming, including installing Python,
writing first program, understanding comments and working with
variables, keywords and operators.
Python Introduction
Python was created in 1991 with a focus on code readability and
its ability to express concepts in fewer lines of code.
Variable types are determined automatically at runtime,
simplifying code writing.
Supports multiple programming paradigms, including object-
oriented, functional and procedural programming.
Understanding Hello World Program in Python
The following is a simple program that displays the message
“Hello, World!” on the screen.
# This is a comment. It will not be executed.
print("Hello, World!")
Output
2|Page
Hello, World!
How does this work:
print() is a built-in Python function that instructs the computer
to display text on the screen.
"Hello, World!" is a string, which is a sequence of text. In
Python, strings are enclosed in quotes (either single ' or
double ").
Anything after a # symbol is a comment. Python ignores
comments, but they are useful for explaining code to human
readers.
We can also write multi-line comments using triple quotes:
"""
This is a multi-line comment.
It can be used to describe larger sections of code.
"""
Indentation in Python
In Python, Indentation is used to define blocks of code. It tells the
Python interpreter that a group of statements belongs to a
specific block. All statements with the same level of indentation
are considered part of the same block. Indentation is achieved
using whitespace (spaces or tabs) at the beginning of each line.
The most common convention is to use 4 spaces or a tab, per
level of indentation.
3|Page
print("I have no Indentation ")
print("I have tab Indentation ")
Output:
ERROR!
Traceback (most recent call last):
File "<[Link]>", line 2
print("I have tab Indentation ")
IndentationError: unexpected indent
Explanation:
first print statement has no indentation, so it is correctly
executed.
second print statement has tab indentation, but it doesn't
belong to a new block of code. Python expects the indentation
level to be consistent within the same block. This
inconsistency causes an IndentationError.
Input and Output in Python
Understanding input and output operations is fundamental to
Python programming. With the print() function, we can display
output in various formats, while the input() function enables
interaction with users by gathering input during program
execution.
Taking input in Python
Python's input() function is used to take user input. By default, it
returns the user input in form of a string.
Example:
name = input("Enter your name: ")
4|Page
print("Hello,", name, "! Welcome!")
Output
Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!
The code prompts the user to input their name, stores it in the
variable "name" and then prints a greeting message addressing
the user by their entered name.
To learn more about taking input, please refer: Taking Input in
Python
Printing Output using print() in Python
At its core, printing output in Python is straightforward, thanks to
the print() function. This function allows us to display text,
variables and expressions on the console. Let's begin with the
basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within
double quotes. When executed, this statement will output the
text to the console.
print("Hello, World!")
Output
Hello, World!
Printing Variables
We can use the print() function to print single and multiple
variables. We can print multiple variables by separating them
with commas.
Example:
5|Page
s = "Brad"
print(s)
s = "Anjelina"
age = 25
city = "New York"
print(s, age, city)
Output
Brad
Anjelina 25 New York
Take Multiple Input in Python
We are taking multiple input from the user in a single line,
splitting the values entered by the user into separate variables
for each value using the split() method. Then, it prints the values
with corresponding labels, either two or three, based on the
number of inputs provided by the user.
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
Output
6|Page
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15
Change the Type of Input in Python
By default input() function helps in taking user input as string. If
any user wants to take input as int or float, we just need
to typecast it.
Print Names in Python
The code prompts the user to input a string (the color of a rose),
assigns it to the variable color and then prints the inputted color.
color = input("What color is rose?: ")
print(color)
Output
What color is rose?: Red
Red
Print Numbers in Python
The code prompts the user to input an integer representing the
number of roses, converts the input to an integer using
typecasting and then prints the integer value.
n = int(input("How many roses?: "))
print(n)
Output
7|Page
How many roses?: 88
88
Print Float or Decimal Number in Python
The code prompts the user to input the price of each rose as a
floating-point number, converts the input to a float using
typecasting and then prints the price.
price = float(input("Price of each rose?: "))
print(price)
Output
Price of each rose?: 50.3050.3
50.3050.3
Find DataType of Input in Python
In the given example, we are printing the type of variable x. We
will determine the type of an object in Python.
a = "Hello World"
b = 10
c = 11.22
d = ("Geeks", "for", "Geeks")
e = ["Geeks", "for", "Geeks"]
f = {"Geeks": 1, "for":2, "Geeks":3}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
8|Page
print(type(f))
Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>
<class 'dict'>
Python Variables
In Python, variables are used to store data that can be
referenced and manipulated during program execution. A
variable is essentially a name that is assigned to a value.
Unlike Java and many other languages, Python variables do
not require explicit declaration of type.
The type of the variable is inferred based on the value
assigned.
x=5
name = "Samantha"
print(x)
print(name)
Output:
5
Samantha
9|Page
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming
rules:
Variable names can only contain letters, digits and
underscores (_).
A variable name cannot start with a digit.
Variable names are case-sensitive like myVar and myvar are
different.
Avoid using Python keywords like if, else, for as variable
names.
Valid :
age = 21
_colour = "lilac"
total_score = 90
Invalid :
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
Assigning Values to Variables
Basic Assignment
Variables in Python are assigned values using the = operator.
x=5
y = 3.14
z = "Hi"
10 | P a g e
Dynamic Typing
Python variables are dynamically typed, meaning the same
variable can hold different types of values during execution.
x = 10
x = "Now a string"
Multiple Assignments
Python allows multiple variables to be assigned values in a single
line.
Assigning the Same Value
Python allows assigning the same value to multiple variables in a
single line, which can be useful for initializing variables with the
same value.
a = b = c = 100
print(a, b, c)
Output:
100 100 100
Assigning Different Values
We can assign different values to multiple variables
simultaneously, making the code concise and easier to read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)
Output:
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one
data type into another. Python provides several built-in functions
11 | P a g e
to facilitate casting, including int(), float() and str() among
others.
Basic Casting Functions
int(): Converts compatible values to an integer.
float(): Transforms values into floating-point numbers.
str(): Converts any data type into a string.
s = "10"
n = int(s)
cnt = 5
f = float(cnt)
age = 25
s2 = str(age)
print(n)
print(f)
print(s2)
Output:
10
5.0
25
Getting the Type of Variable
In Python, we can determine the type of a variable using the
type() function. This built-in function returns the type of the
object passed to it.
n = 42
f = 3.14
12 | P a g e
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True
print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
Object Reference in Python
Let us assign a variable x to value 5.
x=5
When x = 5 is executed, Python creates an object to represent
the value 5 and makes x reference this object.
Now, let's assign another variable y to the variable x.
y=x
13 | P a g e
Python encounters the first statement, it creates an object for
the value 5 and makes x reference it. The second statement
creates y and references the same object as x, not x itself.
This is called a Shared Reference, where multiple variables
reference the same object.
Now, if we write
x = 'Geeks'
Python creates a new object for the value "Geeks" and
makes x reference this new object.
The variable y remains unchanged, still referencing the original
object 5.
If we now assign a new value to y:
y = "Computer"
Python creates yet another object for "Computer" and
updates y to reference it.
The original object 5 no longer has any references and
becomes eligible for garbage collection.
Python variables hold references to objects, not the actual
objects themselves.
Reassigning a variable does not affect other variables
referencing the same object unless explicitly updated.
Delete a Variable Using del Keyword
14 | P a g e
We can remove a variable from the namespace using
the del keyword. This deletes the variable and frees up the
memory it was using.
x = 10
print(x)
del x
# Trying to print x after deletion will raise an error
# print(x) # Uncommenting this line will raise NameError: name
'x' is not defined
del x removes the variable x from memory.
After deletion, trying to access the variable x results in a
NameError indicating that the variable no longer exists.
Practical Examples
1. Swapping Two Variables
Using multiple assignments, we can swap the values of two
variables without needing a temporary variable.
a, b = 5, 10
a, b = b, a
print(a, b)
Output:
10 5
2. Counting Characters in a String
Assign the results of multiple operations on a string to variables
in one line.
word = "Python"
length = len(word)
15 | P a g e
print("Length of the word:", length)
Output:
Length of the word: 6
16 | P a g e