Module 3: Python Basics
Variables and Data Types (Integers, Floats, Strings, Booleans)
Operators (Arithmetic, Comparison, Logical)
Input and Output
Basic Control Flow (if, else, elif statements)
Introduction to Variables
What is Variable?
Variable is the name which we give to the memory location which holds some data. With a variable we can store the data, access
the data and also manipulate the data.
PS. Variable is a container where you can store a value.
To summarize, a variable is a
Name
Refers to a value
Hold some data
Name of a memory location
Let us consider librarians, how could they store and access ton of books? They just make catalogue of
books based on their genre with their reference location. That is how variables also works.
Properties of a Variable
Type
◦ What type of data you store in the variable?
Each data have a type whether it is number word or something and each variable should
belong to one of the data types. This is called the data type of the variable.
Scope
◦ Who can access these data?
In any programming language, scope refers to the place or limit or boundaries or the part of
the program
within which the variable is accessible.
Value
◦ What do you store in the variable?
Each and every variable in a program holds value of some type which can be accessed or modified during the due
flow of the program.
Location
◦ Where you store the variable?
As already stated, the data is stored in memory location. The variable is the name which we give to that location.
Each memory location has some address associated with it.
Lifetime
◦ Till when the variable will be available?
The lifetime of a variable refers to the time period for which the memory location associated with the variable
stores the data.
How to create a variable in Python?
How to create a variable in Python?
In python, to create a variable we just need to specify
Name of the variable
Assign value to the variable
Syntax to create variable
name_of_the_variable = value
age = 21
How can I look for my variables?
To see your variable use print() function
Syntax to print a variable:
print(name_of_the_variable)
Example
print(name_of_the_variable)
print(age)
What is print() function?
print() is a function that can print the specified message to your computer screen.
Syntax to print a message / text:
print("write your message
here")
PS. Don’t worry we will discuss more about function later in Function Chapter.
Ex. ( Print a message / text )
print("I am John")
◦ What if we want to print some message along with our variable?
Syntax to print message with a variable:
Ex. ( Print text along with a variable)
print("My age is",age)
What is input function?
input() is a function that can accept values from a user (you).
Syntax to submit value of a variable
name_of_the_variable = input("Ask user to enter a value")
1 age = input("Enter your age?\n")
2 print("Your age is",age)
Invalid cases for variables
While defining variables in python,
Variable names should be on the left side.
Value should be on the right side.
Violating this will result in syntax error.
Ex. ( Creating a variable in wrong direction )
17 = age
Cell In[8], line 1
17 = age
^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
Rules for creating a variable
1. must start with letter or underscore
Ex. ( Creating a variable with underscore )
23
2. cannot start with number
Ex. ( Creating a variable starts with number )
1 1dollar = 76
Cell In[10], line 1
1dollar = 76
^
SyntaxError: invalid decimal literal
3. cannot use any special symbol
Ex. ( Creating a variable with special symbol )
1 $dollar = 74
Cell In[11], line 1
$dollar = 74
^
SyntaxError: invalid syntax
4. can’t use space ( instead use underscore )
Ex. ( Creating a variable using space )
1 My Age = 24
Cell In[12], line 1
My Age = 24
^
SyntaxError: invalid syntax
5. are case sensitive
PS. Case sensitive means you can’t use lowercase letters in place of uppercase and vice versa.
Ex. ( Print a variable using wrong case )
age = 21
print(Age)
NameError Traceback (most recent call last)
Cell In[13], line 2
1 age = 21
----> 2 print(Age)
6. cannot be a keyword.
Keywords
What is keyword?
Keywords are special reserved words, that have specific meanings and purposes.
All 33 keywords in python contain only alphabet symbols. All of them are in lower case except
True, False, and None.
To see all the keywords
import keyword
keyword.kwlist
'del',
['False',
'elif',
'None', 'or',
'else',
'True', 'pass',
'except', 'finally', 'for',
'and', 'raise',
'from',
'as', 'return',
'global',
'assert', 'try',
'if',
'async', 'while',
'import',
'await', 'with',
'in',
'break', 'yield']
'is',
'class', 'continue', 'def',
'lambda', 'nonlocal', 'not',
Data Types
All programming languages aim is to create some data then do some actions / operations on the data, i.e. processing
data. The data can be categorized into different types. Categorizing the data is important in order to perform the
operations on it. That classification, which states the type of data stored in the variable is called data type.
What is a data type?
Data Type is type of data that to be stored in a variable, simple as that. Generally based on their creations data types
can be classified into two types:
1. User defined data types: Data types which are created by programmer (you), example is class, module,
array etc.
PS. Don’t worry, We will discuss it more later in OOPS Chapter.
2. Built-in data types
Data types which are already
available in python. Built-in data
types also classified into:
Sequences / Collections
None list
Bool / Booleans tuple
Numeric types set
Int dict
Float str
Complex
None data type
None data type represents an object that does not contain any value. If any object has no value, then we can
assign that object with None type.
Syntax to create None data type variable:
How to know a variable is belongs to specific data type?
Syntax to know data type of a variable:
What is type() function?
type() is an in built or pre-defined function, which is used to check data type of a variable.
Ex 4.1 ( Printing None data type )
1 box = None
2 print("The Box is",box)
3 print(type(box))
The Box is None
<class 'NoneType'>
Bool ( boolean ) data Type
The bool data type represents boolean values in python. bool data type having only two values
those are, True and False. Python internally represents, True as 1(one) and False as 0(zero).
Numeric Data Types
1. int data type
The int data type represents values or numbers without decimal values. In python there is no
limit for int data type. It can store very large values conveniently.
Ex: ( Print integer value )
1 Sid = 16784
2 print("My student id is",Sid)
3 print(type(Sid))
My student id is 16784
<class 'int'>
2. float data type
The float data type represents a number with decimal values.
1 grade = 9.74
2 print("My grade is",grade)
3 print(type(grade))
My grade is 9.74
<class 'float'>
3. complex data type
The complex data type represents the numbers which is written in the form of a+bj or a-bj, here a is representing a
real and b is representing an imaginary part of the number. The suffix small j or upper J after b indicates the
square root of -1. The part "a" and "b" may contain integers or floats.
1 a = 3 + 6j
2 b = 2 - 5.5j
3 c = 2.4 + 7j
4 print(a, b, c)
5 print(type(a))
(3+6j) (2-5.5j) (2.4+7j)
<class 'complex'>
Sequence Data Types
Sequences in python are objects that can store a group of values. The below data types are called sequences.
String
List 1. String Data Type: A string is a group of characters enclosed within single quotes
Tuple ('...'), double quotes ("..."), or triple quotes ('''...''' or """..."""). You choose the type of
Set quotes depending on whether your text contains apostrophes or quotes.
Dictionary
# Using single quotes: # Using double quotes when an apostrophe is # Using triple quotes when the string
text1 = 'My name is John' inside the string: contains both kinds of quotes:
print(text1) text2 = "This is John's book" text3 = '''"John's book is awesome."
print(type(text1)) print(text2) Michael J.'''
print(type(text2)) print(text3)
My name is John print(type(text3))
This is John's book
<class 'str'> "John's book is awesome." Michael J.
<class 'str'>
<class 'str'>
2. List Data Type
Lists store multiple values (which can be of different types) inside square brackets. Lists are mutable, so
you can add or remove elements.
details_list = [1, 'John', 9.5, 'pass', 1]
print(details_list)
print(type(details_list))
[1, 'John', 9.5, 'pass', 1]
<class 'list'>
3. Tuple Data Type
Tuples store multiple values, similar to lists, but they are immutable (unchangeable) once created. Tuples are
defined using parentheses.
details_tuple = (1, 'John', 9.5, 'pass', 1)
print(details_tuple)
print(type(details_tuple))
(1, 'John', 9.5, 'pass', 1)
<class 'tuple'>
4. Set Data Type
Sets store unordered, unique elements. You define a set using curly braces. Note that duplicate
elements are automatically removed.
details_set = {'pass', 1, 9.5, 'John'}
print(details_set)
print(type(details_set))
{'pass', 1, 9.5, 'John'}
<class 'set'>
5. Dictionary Data Type
Dictionaries store data as key-value pairs and are defined using curly braces with colon separators. They are
useful for pairing related values (like an athlete's name with their rank).
race = {2: 'John', 1: 'Mike', 3: 'Dani'}
print(race)
print(type(race))
{2: 'John', 1: 'Mike', 3: 'Dani'}
<class 'dict'>
Operators
What Is an Operator?
An operator is a symbol that tells Python to perform a specific
operation on one or more values (called operands). For example,
in the statement:
a=5+3
The + symbol is an operator
(it adds two numbers).
The numbers 5 and 3 are
operands.
Basic Classifications of Operators
1. Unary Operators
Operate on one operand.
Example: The unary minus (-) changes the sign of a number.
num = 5
print(-num) # Output: -5
2. Binary Operators
Operate on two operands.
Example: The addition operator (+) adds two numbers.
a = 10
b=5
print(a + b) # Output: 15
3. Ternary Operators
Work with three operands. In Python, this is the conditional expression.
Example: Choose one value based on a condition.
a = 10
b = 20
# If a is greater than b, choose a; otherwise, choose b
maximum = a if a > b else b
print(maximum) # Output: 20
Important Types of Operators in Python
2. Arithmetic Operators
1. Assignment Operators
Perform basic math operations.Operators: +, -, *, /, %
Used to assign a value to a variable. (modulus), // (floor division), and ** (exponentiation).
•Example: Example:
x = 10 a=8
b=3
print("x =", x) # Output: x = 10 print("Addition:", a + b) # 11
print("Subtraction:", a - b) # 5
print("Multiplication:", a * b) # 24
print("Division:", a / b) # 2.6666666666666665
print("Floor Division:", a // b) # 2
print("Modulus:", a % b) #2
print("Exponentiation:", a ** b) # 512, because 8^3 = 512
3. Compond Operators
Combine arithmetic and assignment in one step.
Example: The +=operator adds a value and then assigns the result to the variable
balance = 1000
deposit = 500
balance += deposit # Same as: balance = balance + deposit
print("Balance after deposit:", balance) # Output: 1500
.
4. Relational (Comparison) Operators
Compare two values, returning True or False.
Operators: <, >, <=, >=, ==, !=
Example:
a = 10
b = 20
print("Is a less than b?", a < b) # True
print("Is a equal to b?", a == b) # False
print("Is a not equal to b?", a != b) # True
Assignment Python Operators
Below are the operator categories you'll work on. For each, explain what the operator category
is, how it works, and provide a short code example demonstrating it.
1. Identity Operators
2. Logical Operators
3. Bitwise Operators
4. Membership Operators
Input and Output
What it is: The input() function is used to receive data from the user. When the program executes this function, it
pauses and waits for the user to type some text and press Enter.
What it is: The print() function is used to display data on the screen. It shows the output to the user by writing to the
console.
# Ask for the user's name using input() Input: The program displays "Enter your name:" and
name = input("Enter your name: ") waits for the user input.
Output: After the user types their name and presses Enter,
# Use print() to display a greeting with the entered name the program outputs a greeting message that includes the
entered name.
print("Hello,", name + "!")
Basic Control Flow (if, else, elif statements)
What Is Basic Control Flow?
Control flow in Python determines the order in which your code is executed based on
conditions. The primary statements for this are:
if statement: Checks a condition. If it's True, the code block following it runs.
elif statement: Short for "else if." It checks another condition if the previous if (or any
preceding elif) wasn't True.
else statement: Executes a block of code when none of the previous conditions are met.
Example: Checking if a Number is Positive, Negative, or Zero
# Ask the user to input a number.
number = int(input("Enter a number: "))
# Check the number's value.
Explanation
if number > 0:
The program asks for a number and converts it to
print("The number is positive.") an integer.
The if statement checks whether the number is
elif number < 0:
greater than zero.
print("The number is negative.") The elif statement checks if the number is less than
zero.
else:
The else statement catches all other cases in this
print("The number is zero.") example, when the number is exactly zero.