01-python-variables-types-and-basic-io
August 30, 2023
[4]: # Welcome to the 'Python Programming Language'!
# This unit is an introduction to the most basic concepts and features of the␣
↪Python programming language
# It covers : Variables, the basic Data Types, basic mathematical operations
# In addition, this unit also covers basic i/o operations
# such as interactive input, print, and file I/O
!pip install pyppeteer
!pyppeteer-install
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pyppeteer in c:\users\divyanshu.laptop-
lrgnn2bq\appdata\roaming\python\python311\site-packages (1.0.2)
Requirement already satisfied: appdirs<2.0.0,>=1.4.3 in
c:\users\divyanshu.laptop-lrgnn2bq\appdata\roaming\python\python311\site-
packages (from pyppeteer) (1.4.4)
Requirement already satisfied: certifi>=2021 in c:\users\divyanshu.laptop-
lrgnn2bq\appdata\roaming\python\python311\site-packages (from pyppeteer)
(2023.7.22)
Requirement already satisfied: importlib-metadata>=1.4 in
c:\users\divyanshu.laptop-lrgnn2bq\appdata\roaming\python\python311\site-
packages (from pyppeteer) (6.8.0)
Requirement already satisfied: pyee<9.0.0,>=8.1.0 in c:\users\divyanshu.laptop-
lrgnn2bq\appdata\roaming\python\python311\site-packages (from pyppeteer) (8.2.2)
Requirement already satisfied: tqdm<5.0.0,>=4.42.1 in c:\users\divyanshu.laptop-
lrgnn2bq\appdata\roaming\python\python311\site-packages (from pyppeteer)
(4.66.1)
Requirement already satisfied: urllib3<2.0.0,>=1.25.8 in
c:\users\divyanshu.laptop-lrgnn2bq\appdata\roaming\python\python311\site-
packages (from pyppeteer) (1.26.16)
Requirement already satisfied: websockets<11.0,>=10.0 in
c:\users\divyanshu.laptop-lrgnn2bq\appdata\roaming\python\python311\site-
packages (from pyppeteer) (10.4)
Requirement already satisfied: zipp>=0.5 in c:\users\divyanshu.laptop-
lrgnn2bq\appdata\roaming\python\python311\site-packages (from importlib-
metadata>=1.4->pyppeteer) (3.16.2)
Requirement already satisfied: colorama in c:\users\divyanshu.laptop-
1
lrgnn2bq\appdata\roaming\python\python311\site-packages (from
tqdm<5.0.0,>=4.42.1->pyppeteer) (0.4.6)
chromium is already installed.
[ ]: # BTW, in a Python program any sequence after a '#' is a comment (like this␣
↪line)
# and it is ignored during program execution!!
''' Talking about comments ... multiple line comments can be written within␣
↪triple quotes
as shown here
'''
[ ]: # What is a variable?
# Variables in Python (... or, in any programming language) are 'containers',␣
↪that are used to store data.
# Variables are given names, which are known as identifiers.
# So, what, really, are variables, and what are identifiers?
# In Python an identifier can consist of:
# Upper and lowercase letters of the alphabet, underscores, and digits 0 to 9.
# BTW, do you know What is a 'random variable'?
[ ]: # Examples of variables / identifiers
# Variables can be of various 'types' as enumerated below and further explained␣
↪later
v1 = "the first variable of this course!" # string
v2 = 2023.8 # float
v3 = True # boolean
v4 = [1,2,3,4,5] # list
v5 = (1,2,3,4,5) # tuple
v6 = {"name": "Aditi", "age": 25} # dictionary
v7 = {1,2,3,4,5} # set
v8 = 3 # int i.e. integer
v9 = 0b1010 # binary ... essentially an int
v10 = 0o17 # octal ... essentially an int
v11 = 0x1F # hexadecimal ... essentially an␣
↪int
v12 = None # None
[ ]: # Introducing the simplest way to print the value of a variable ... and also␣
↪your introduction to a 'function'!
# A function is a reusable piece of code that can be repeatedly called to␣
↪perform a specific task
2
# In the following statements, we are calling, or 'invoking' the 'print'␣
↪function
# More about 'defining' functions in later modules ... till then we just use␣
↪them
print(v1, v2, v3, v4, v5, v6)
print(v7, v8, v9, v10, v11, v12)
[ ]: ### Data Types in Python
# Python supports various built-in data types, such as int, float, str, bool,␣
↪complex, list, tuple, set, and dict.
# They can also be classified into the following categories:
# Numeric types, Sequence types, Set types, Mapping types, Boolean types,␣
↪Binary type and None type
# There are also user-defined data types that can be a combination of built-in␣
↪data types ...
# In this exercise we are only interested in the built-in data types
[ ]: # Lets print out the 'type' of every variable defined above
print(type(v1), type(v2), type(v3), type(v4), type(v5), type(v6))
print(type(v7), type(v8), type(v9), type(v10), type(v11), type(v12))
[ ]: # More about Variables names or identifiers: they are case-sensitive
# By convention, they follow 'snake_case' notation
# What is snake_case?
# Which are the other popular variable naming conventions ( used in other␣
↪languages?)
# Python is dynamically typed, so you don't need to specify the data type␣
↪explicitly.
# It is inferred from the specified value of the variable
[ ]: # Let's create some more variables of the simpler data types, with more␣
↪meaningful identifiers
age = 25 # An integer variable
height = 5.11 # A float variable
name = "Aditi" # A string variable
is_student = True # A boolean variable
complex_num = 3 + 4j # A complex variable
a_general_variable = "Initialized to string" # We will change the type of␣
↪this variable later, to illustrate dynamic typing
[ ]: # Informative printing ...
print("Name:", name)
print("Age:", age)
3
print("Height:", height)
print("Is Student:", is_student)
print("Complex Number:", complex_num)
print("A general variable: its value is", a_general_variable, "and its type is:
↪", type(a_general_variable))
[ ]: # A more convenient and concide way to print
# Notice the use of 'f' before the string to be printed ...
# also notice the variable names embedded in the string but enclosed in brace␣
↪brackets,
print(f"Name: {name}, Age: {age}, Height: {height}, Is Student: {is_student},␣
↪Complex Number: {complex_num}")
[ ]: # Still better?
print(f" Name: {name}\n Age: {age}\n Height: {height}\n Is Student:␣
↪{is_student}\n Complex Number: {complex_num}")
[ ]: # Q: Using f-strings, is it possible to format the output in a more customized␣
↪way?
# For example, specify the total width, justification, and number of␣
↪significant digits of a 'float' number
# Q: Look up the old style output formatting methods also ... old code in␣
↪Python would have them
[ ]: # Variable re-assignment. Such operations may result in changing the variable␣
↪type
name = "Ajay" # Changing the value of the 'name' variable
print("Updated Name:", name)
a_general_variable = 10 # This also results in changing the variable type
print(f"New value of \'General Variable\': {a_general_variable}, and its new␣
↪type is: {type(a_general_variable)}")
[ ]: # Notice the use of 'escape' character '\' in the above statement. What is it?␣
↪Why is it needed?
# Q: Which other such escape characters and escape sequences are pre-defined,␣
↪and when are they used?
[ ]: # Q: Is it possible to create variables without assigning any value to them? If␣
↪so, how?
# Q: Is it possible to fix the type of a variable, ie. once defined the type␣
↪cannot be changed?
# Q: Is it possible to define a 'constant'?
# Q: Is it possible to prevent the value of variable from being changed? That␣
↪is, make a variable immutable?
4
[ ]: # Conversion functions are available to convert one data type to another.
# Typically, from a string to int, float, etc
# This is required usually while interactively inputting data ... coming up␣
↪later
a = int("1")
b = float("1.1")
c = str(3)
d = bool(5)
print(a,b,c,d)
[ ]: # In Python everything is an 'object', derived from a 'class'
# We will right now just get used to these terms, and understand how to use␣
↪objects
# In a later session we will understand how to define a class and create␣
↪objects of that class
# If you are using Jupyter Notebook, type 'a.' followed by TAB to get a list of␣
↪functions available for 'a'
# In VSC, type 'a.' to get all the operations available on 'a'
[ ]: # Python provides a function to 'delete' a variable from the current␣
↪'namespace' i.e. memory
i_exist = True
print(i_exist)
[ ]: del(i_exist)
# print(i_exist) # at this point the variable does not exist, hence␣
↪executing this line raises an error
[ ]: # Python allows multiple variables to be created /assigned at once
v1, v2, v3 = 1, "two", 3.3
print(v1, v2, v3)
# This method is usually used to return multiple outputs from a 'function'.␣
↪More on that later ...
[ ]: # Operating with variables in Python
# Python allows you to operate with / on variables using various 'operations'
# Expressions can be built using variables and operations
# Let's look at some examples of operations and their types
# In the blocks that follow, print out the value of the variable after each␣
↪operation to check the result
# If you are clueless about what something like '+=' means, refer the following␣
↪link
5
# https://docs.python.org/3/reference/simple_stmts.
↪html#augmented-assignment-statements
[ ]: # Assignment operations
a = 10 # Assignment
a += 5 # Addition assignment
a -= 5 # Subtraction assignment
a *= 5 # Multiplication assignment
a /= 5 # Division assignment
a %= 5 # Modulo assignment
a //= 5 # Floor division assignment
a **= 5 # Exponentiation assignment
[ ]: # Arithmetic operations
a = 10 + 5 # Addition
b = 10 - 5 # Subtraction
c = 10 * 5 # Multiplication
d = 10 / 5 # Division
e = 10 // 5 # Floor Division
f = 10 % 5 # Modulo/Remainder
g = 10 ** 5 # Exponentiation
[ ]: # Boolean, or comparison operations
a = 10 == 5 # Equal to
b = 10 != 5 # Not equal to
c = 10 > 5 # Greater than
d = 10 < 5 # Less than
e = 10 >= 5 # Greater than or equal to
f = 10 <= 5 # Less than or equal to
[ ]: # Logical operations
a = True and False # Logical AND
b = True or False # Logical OR
c = not True # Logical NOT
[ ]: # Bitwise operations
a = 10 & 5 # Bitwise AND
b = 10 | 5 # Bitwise OR
c = 10 ^ 5 # Bitwise XOR
d = ~10 # Bitwise NOT
e = 10 << 2 # Left shift
f = 10 >> 2 # Right shift
[ ]: # Q: What is the difference between the x = x + 1 and x += 1 ?
[ ]: # We will now look at the basic methods to handle input / output
6
# That is, assign values to variables from an external source (e.g. the user␣
↪using a keyboards)
# and store the value of a variable in an external sink (e.g. a file)
[ ]: # Basic input / output in Python
# Values can be interactively assigned using the keyboard while initializing␣
↪variables
# using the input() function ... Python display the supplied prompt, and waits␣
↪for a value to be specified
# After you type the following statement, you will find a prompt on the screen,␣
↪somewhere. Don't get lost!
a_new_variable = input("Enter the value of the new variable: ")
print("The value of the new variable is:", a_new_variable, "and its type is:",␣
↪type(a_new_variable))
a_new_int = int(input("Enter a whole number: "))
print(f"The value of the whole number is: {a_new_int}, and its type is:␣
↪{type(a_new_int)}")
[ ]: # Variable values can be written out into a file using the following code
# Write the variables to a text file
with open("variables.txt", "w") as file:
file.write(str(age) + "\n")
file.write(str(height) + "\n")
file.write(name + "\n")
file.write(str(is_student) + "\n")
[ ]: # Define new variable to read their values from the file
#rd_age, rd_height, rd_name, rd_is_student = None, None, None, None
# Read the variables back from the text file
with open("variables.txt", "r") as file:
rd_age = int(file.readline().strip())
rd_height = float(file.readline().strip())
rd_name = file.readline().strip()
rd_is_student = bool(file.readline().strip())
# Print the variables
print("age =", rd_age)
print("height =", rd_height)
print("name =", rd_name)
print("is_student= ", rd_is_student)
7
[ ]: # That's it in this unit. More types, built-in functions, and more Python␣
↪features in the next unit !
# In the meantime, go through the following links to learn more ...
# https://docs.python.org/3.11/tutorial/appetite.html
# https://www.python.org/about/gettingstarted/