Module2 Myown
Module2 Myown
KANNIGA DEVI
BCSE 101E- Computer Programming: ASSOCIATE PROFESSOR
Python SCHOOL OF COMPUTER SCIENCE
Module -2 AND ENGINEERING
VIT CHENNAI
Syllabus
Introduction to python – Interactive and Script Mode – Indentation – Comments – Variables – Reserved
Words – Data Types – Operators and their precedence – Expressions – Built-in Functions – Importing from
Packages.
• interpretation
• compilation
• examples: Python
Compilation approach
• uses a program called compiler
Python is primarily an interpreted language. The Python interpreter is called “CPython” and it's written in the C
programming language. This is the default implementation for Python.
Interpreted Language
•Execution: Python code is executed line by line by an interpreter at runtime. The Python interpreter reads the code,
interprets it, and executes it directly.
•Flexibility: This allows for greater flexibility and ease of testing, as you can run and test portions of the code
interactively without needing to compile the entire program.
Compilation in Python
Although Python is generally considered an interpreted language, there is an intermediate compilation step:
•Bytecode Compilation: When you run a Python program, the Python interpreter first compiles the source code (.py
files) into bytecode (.pyc files). This bytecode is a lower-level, platform-independent representation of the source
code.
•Execution: The bytecode is then interpreted by the Python Virtual Machine (PVM), which is the actual interpreter
that executes the bytecode.
Each mode serves different purposes and is suitable for different tasks.
• Script mode :
Script mode is used to run Python programs that are saved in files with a .py extension.
Use Case: This mode is ideal for writing larger, more complex programs that you want to save,
modify, and run multiple times.
Eg: use some IDE like VScode (after installing python extension in VScode)
• Use Case: This mode is useful for learning Python, trying out new ideas, and performing quick
calculations or operations.
Now
set t we are
o
pyth practic
o n☺ e
☺☺
if 3 > 1:
print(“Three is greater than one")
No Indentation
raises syntax
error
• Must begin with a letter or _ • Upper case and lower case letters
are different
• ‘abc123’ and ‘_abc123’ are ok
• ‘123abc’ is not allowed • ‘abc123’ is not ‘ Abc123’
Identifier names should start with a letter (a-z, A-Z) or an underscore (_), followed by letters,
digits (0-9), or underscores.
Operations
• Once a variable is created, we can store, retrieve, or modify the value
associated with the variable name.
Name Value
x = 5.16 5.16
x 5.16
Python variables are dynamically typed, which means you don't need to declare their type
explicitly.
Instead, the type is determined based on the value assigned to the variable.
Variable Types:
You can use the type() function to check the type of a variable.
print(type(x)) # Output: <class 'str'>
print(type(y)) # Output: <class 'float'>
print(type(name)) # Output: <class 'str'>
print(type(is_valid)) # Output: <class 'bool'>
● Integers: Python supports integer data types. They are often called int and are positive or negative or
whole numbers without decimal points. They are represented by class int.
● Float: Python support floating-point data type. They are often called float .They represent real
numbers and are written with a decimal point separating the integral and fractional part. They are
represented by class float
● In python, strings are arrays of one or more characters, represented in single or double quotes.
● They are represented by class str.
The boolean data type is either True or False. In Python, boolean variables are defined by the True and
False keywords. The output <class 'bool'> indicates the variable is a boolean data type.
Note: The built in function type(variable) returns the class of the datatype.
Type
s of v
are s ariables
throu pecified
Output: gh wr
a
class pper
es
Conversion of datatypes
Example 2 Example : String to integer
Conversion of datatypes
Explicit Type Conversion
Syntax
• In Explicit Type Conversion, users convert the data type of an
object to required data type. <required_datatype>(expression)
• We use the predefined functions like int(), float(), str(), etc to
perform explicit type conversion.
• This type of conversion is also called typecasting because the
user casts (changes) the data type of the objects.
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str)) Example 3 : String to Integer
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str)) What is the output of this
num_sum = num_int + num_str programme
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
Conversion of datatypes
Key Points to Remember
1.Type Conversion is the conversion of object
from one data type to another data type.
Output of Example 3
2.Implicit Type Conversion is automatically
performed by the Python interpreter.
Data type of num_int: <class 'int'>
3.Python avoids the loss of data in Implicit
Data type of num_str before Type Casting: <class 'str'>
Type Conversion.
Data type of num_str after Type Casting: <class 'int'>
4.Explicit Type Conversion is also called Type
Sum of num_int and num_str: 579
Casting, the data types of objects are
Data type of the sum: <class 'int'>
converted using predefined functions by the
user.
5.In Type Casting, loss of data may occur as
we enforce the object to a specific data type.
Type conversion
made simpler
Example:
# Implicit type conversion
x = 10 # int
y = 3.14 # float
x = 10
y = float(x) # Convert int to float
s = str(x) # Convert int to string
Simple Output
Example : integer to float
Syntax
print("Python is fun.")
print(*objects, sep=' ', end='\n', file=sys.stdout) a = 5 # Two objects are passed
Purpose of each parameter print("a =", a)
b = a # Three objects are passed
• objects - object to the printed. * indicates that there print('a =', a, '= b')
may be more than one object
• sep - objects are separated by sep. Default value: ' ' a=5
• end - end is printed at last print("a =", a, sep='00000', end='\n\n\n')
• file - must be an object with write(string) method. If print("a =", a, sep='0', end='')
omitted it, sys.stdout will be used which prints objects
on the screen sourceFile = open('python.txt', 'w')
print('Pretty cool, huh!', file = sourceFile)
sourceFile.close()
Simple Input
Syntax Example
num=input('Enter a number')
input([prompt]) num1=input('Enter second number')
print(num+num1)
• Here, we can see that the entered value 10
and 20 is a string, not a number. To convert Enter a number10
this into a number we can Enter second number20
use int() or float() functions 1020
num=input('Enter a number')
• Here, we converted both num and num1 to num1=input('Enter second number')
integer and the result we get is integer print(int(num)+int(num1))
Enter a number10
Enter second number20
30
Simple Input
• eval()
It evaluates the expression given as a
string and returns integer
Example
The input() function reads a line from the input (usually from the user via the keyboard) and returns it
as a string.
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!") # here, + is a concatenation operator
Output
The print() function can take multiple arguments, and by default, it adds a space between arguments
and ends with a newline.
Example:
print("Hello, World!")
You can also customize the separator and end characters using the sep and end parameters.
print("Hello", "World", sep="-", end="!")
# Output: Hello-World!
Input
str.format():
name = "Alice"
age = 30
print("Hello, {}! You are {} years old.".format(name, age))
Operators and their precedence
output:
7
Output:
S
co nc tr i ng
a ten
a ti o n
Example:
a = 10
b=3
print(a / b) # Output: 3.3333333333333335
print(a // b) # Output: 3
* With strings
performs
repetition
Output:
•Equals:
•Not Equals:
•Less than:
•Greater than:
•and
returns True
because 7 is greater
than 2 AND 7 is less
Example: than 12
a=7
print(a > 2 and a < 12)
Example:
a=7
print(not(a > 4 and a < 12))
•and - &
Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is
12
z = x & y; # 12 = 0000 1100
print ("Value of z is ", z)
•or - |
Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0
value of z is 61
z = x | y; # 61 = 0011 1101
print ("Value of z is ", z)
•not - ~
•It is unary and has the effect of inverting all the bits
Example:
x = 60 # 60 = 0011 1100
z=0
value of z is
195
z = ~x ; # 195 = 1100 0011
print ("Value of z is ", z)
•XOR - ^
• Sets each bit to 1 if only one of two bits is 1
Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is
49
z = x ^ y; # 49 = 0011 0001
print ("Value of z is ", z)
Example:
x = 60 # 60 = 0011 1100
z=0 value of z is 240
Example:
x = 60 # 60 = 0011 1100
z=0
value of z is 15
z = x >> 2; # 15 = 0000 1111
print ("Value of z is ", z)
Eg:
a=4
a += 5
a -= 5
For example, in 3 + 4 - 2, Python will first add 3 + 4 to get 7 and then subtract 2 to yield 5.
For example, in the expression 3 ** 2 ** 1, Python first calculates 2 ** 1 to get 2 and then computes 3
** 2 to give 9.
It is a combination of values, variables, and operators that the interpreter can evaluate to a single value.
x=2+3
Types:
Arithmetic expression
Logical Expression
Bitwise expression
Assignment expression
Relational or Comparison expression
Compound expression
Types:
Types:
Compound expression
Arithmetic expression
a = 10
a = 10
b=5
b=5
c=2
result1 = a + b # Addition
result1 = (a + b) * c # Parentheses ensure addition is done first
print(result1) # Output: 30
These are the pre-defined function in Python that allows using the basic properties of string and
numbers in your rules. Here listed a few:
Function Description
abs() Returns the absolute value of a number
bool() Returns the boolean value of the specified object
len() Returns the length of an object
max() Returns the largest item in an iterable
min() Returns the smallest item in an iterable
pow() Returns the value of x to the power of y
print() Prints to the standard output device
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
Some examples:
result = abs(-10)
result = max(1, 2, 3)
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It
generates arithmetic progressions. It returns a sequence of numbers that starts at 0 and increments by 1
(by default) and stops before a specified number.
Example:
Generate a sequence of numbers from 0 to 6:
n = range(7)
for x in n:
print(x) Prints
0,1,2,3,4,5,6
Example:
Generate a sequence of numbers from 3 to 6:
n = range(3, 6)
for x in n:
print(x) Prints 2,3,4,5
Example:
Generate a sequence of numbers from 2 to 8,
increment by 2:
n = range(2, 9,2)
for x in n: Prints 2,4,6,8
print(x)
Example:
Generate a sequence of numbers from 5 to 1,
decrement by 1:
n = range(5, 0,-1)
for x in n: Prints 5,4,3,2,1
print(x)
Example:
Generate a sequence of numbers from -1 to -5,
decrement by 1:
n = range(-1, -6,-1)
for x in n: Prints -1,-2,-3,-4,-5
print(x)
To iterate over the indices of a sequence, you can combine range() and len() as follows:
Output:
Accessing all
elements of list
# 1. Basic Import
import <module-name>
import math
print(math.sqrt(16)) # Output: 4.0
------------
import numpy as np
print(np.array([1, 2, 3])) # Output: [1 2 3]
1. Basic calculator
2. Simple interest calculation
3. Area of a rectangle
4. perimeter of a rectangle
5. Temperature conversion
6. Quadratic equation solver
7. BMI calculator
8. Sum of Natural Numbers
9. Discount Calculation
10. Salary Calculation with Tax Deduction
# Combining data types, operators, expressions, built-in functions, and importing from packages
import math