0% found this document useful (0 votes)
85 views

Lecture 22 - Python Datatypes, Variables, Input Output Statements

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It has a simple syntax and dynamic typing and many data structures. Python code can be executed as soon as it is written due to its interpreter system. Python supports procedural, object-oriented, and functional programming styles.

Uploaded by

Dileep L
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

Lecture 22 - Python Datatypes, Variables, Input Output Statements

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. It has a simple syntax and dynamic typing and many data structures. Python code can be executed as soon as it is written due to its interpreter system. Python supports procedural, object-oriented, and functional programming styles.

Uploaded by

Dileep L
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Python Data types, variables,

Input output statements


Python Introduction

It is a general-purpose interpreted, interactive, object-oriented, and high-level


programming language.

Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.

Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.

Python runs on an interpreter system, meaning that code can be executed as soon as
it is written. This means that prototyping can be very quick.

Python can be treated in a procedural way, an object-oriented way or a functional


way.
Why Python?
Python is Interpreted − Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it.

Python is Interactive − You can actually sit at a Python


prompt and interact with the interpreter directly to write your
programs.

Python is Object-Oriented − Python supports Object-Oriented


style or technique of programming that encapsulates code
within objects.

Python is a Beginner's Language − Python is a great language


for the beginner-level programmers and supports the
development of a wide range of applications from simple text
processing to WWW browsers to games.
Characteristics of Python
It supports functional and structured programming methods as
well as OOP.

It can be used as a scripting language or can be compiled to


byte-code for building large applications.

It provides very high-level dynamic data types and supports


dynamic type checking.

It supports automatic garbage collection.

It can be easily integrated with C, C++, COM, ActiveX,


CORBA, and Java.
Python Data Types
Python Data Types
•Variables can hold values, and every value has a data-type.

•Python is a dynamically typed language; hence we do not need to


define the type of the variable while declaring it.

•The interpreter implicitly binds the value with its type.

•For Example, a = 5 . The variable a holds integer value five and


we did not define its type.

•Python interpreter will automatically interpret variables a as an


integer type.

•Python provides us the type() function, which returns the type of


the variable passed.
Numbers
Number stores numeric values. Numeric Types: int, float, complex

Int - Integer value can be any length such as integers 10, 2, 29, -20, -
150 etc. Python has no restriction on the length of an integer. Its value
belongs to int

Float - Float is used to store floating-point numbers like 1.9, 9.902,


15.2, etc. It is accurate upto 15 decimal points.

complex - A complex number contains an ordered pair, i.e., x + iy


where x and y denote the real and imaginary parts, respectively. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.

Python creates Number objects when a number is assigned to a


variable.
Numbers
Python Script
a=5
print(a) OUTPUT
print("The type of a", type(a)) 5
The type of a <class 'int'>
40.5
b = 40.5 The type of b <class 'float'>
print(b) (1+3j)
print("The type of b", type(b)) The type of c <class 'complex'>

c = 1+3j
print(c)
print("The type of c", type(c))
Numbers

Prefix Interpretation Base


0b (zero + lowercase Binary 2
letter 'b')
0B (zero + uppercase
letter 'B')
0o (zero + lowercase Octal 8
letter 'o')
0O (zero + uppercase
letter 'O')
0x (zero + lowercase Hexadecimal 16
letter 'x')
0X (zero + uppercase
letter 'X')
Numbers
print(10+1)
Output
11

print(123123123123123123123123123123123123123123123123 + 1)
Output
123123123123123123123123123123123123123123123124

The underlying type of


a Python integer, irrespective
of the base used to specify it, is
called int:
Numbers
Just typing the value at the >>> prompt and hitting Enter will display it. print()
function is not mandatory to display the value
String

The string can be defined as the sequence of characters represented


in the quotation marks.

In Python, we can use single, double, or triple quotes to define a


string.
String

Multiline Strings
List
Python Lists are similar to arrays in C.

A list object is an ordered collection of one or more data items


changeable.

The list can contain data of different types.

The items stored in the list are separated with a comma (,) and
enclosed within square brackets [].

We can use slice [:] operators to access the data of the list.

Lists have no fixed size and can be expanded or contracted as


needed.

Items in list can be retrieved using the index.


List
List
Tuple
A tuple is a collection which is ordered and unchangeable.

In Python tuples are written with round brackets.


Set
A set is a collection which is unordered and unindexed.
In Python, sets are written with curly brackets.
Result after First RUN

Result after Second RUN


Dictionary
A dictionary is a collection which is unordered, changeable and
indexed.
In Python dictionaries are written with curly brackets, and they have
keys and values.

Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly
braces.

An empty dictionary without any items is written with just two curly
braces, like this: {}.

Keys are unique within a dictionary while values may not be. The
values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

Pair1: ‘Name’:’Zara’
Key is Name and its value is Zara

Pair 2: 'Age': 7
Key is Age and its value is 7
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets
along with the key to obtain its value.

Following is a simple example −

OUTPUT
Boolean
Booleans represent one of two values: True or False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

When you compare two values, the expression is evaluated and Python returns the
Boolean answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

OUTPUT:
True
False
False
Boolean

Evaluate Values and Variables:

The bool() function allows you to evaluate any value, and


give you True or False in return,
Example
Evaluate a string and a number:
Boolean
Most Values are True

Almost any value is evaluated to True if it has some sort of content.

Any string is True, except empty strings.

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.
Input and Output in Python
Taking Input from the user

Python provides an input() function to accept input from the user.

Syntax:
input('prompt')

where, prompt is a string that is displayed on the string at the time of taking input.

Example:

# Assume the user entered input is AMRITA“ (# represents comments in python)


name = input("Enter your name: ")
print(name)

OUTPUT:
AMRITA
Taking Input from the user
Python Script
OUTPUT

Note: By default input() function takes the user’s input in a string.


So, to take the input in the form of int, you need to use int() along with input
function.
Taking Input from the user

Python Script OUTPUT


Displaying Output
Python provides the print() function to display output to the console.

Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Values
Parameter Description

object(s) Any object, and as many as you like. Will be converted to string before printed

sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default is ' '

end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)

file Optional. An object with a write method. Default is sys.stdout

flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
Displaying Output
Python Script

OUTPUT
Python Comments
Comments can be used to make the code more readable.
Comments starts with a #, and Python will ignore them:

Example:

Multi Line Comments (use triple single quotes or double quotes)


Python Variables
Variables:

Variables are containers for storing data values.

Unlike other programming languages, Python has no command for


declaring a variable.

A variable is created the moment you first assign a value to it.

Python script
x=5
y = "John"
print(x)
print(y)
Output
5
John
Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

Rules for Python variables:

A variable name must start with a letter or the underscore character

A variable name cannot start with a number

A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )

Variable names are case-sensitive (age, Age and AGE are three different
variables)
Variable Names

#Legal variable names:


myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

#Illegal variable names:


2myvar = "John"
my-var = "John"
my var = "John"
Assign Value to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

OUTPUT
Orange
Banana
Cherry
Assigning same value to multiple variables in one
line:

Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

OUTPUT
Orange
Orange
Orange
Output Variables

The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

Example:
x = "awesome"
print("Python is " + x)
Output:
Python is awesome

+ character to add a variable to another variable:


Example
x = "Python is "
y = "awesome"
z= x+y
print(z)
Output:
Python is awesome
Output Variables

x=5
y = "John"
print(x + y)

Output:
TypeError: unsupported operand type(s) for +: 'int'
and 'str'
Python Casting
There may be times when you want to specify a type on to a variable.
This can be done with casting.

Casting in python is done using constructor functions:

•int() - constructs an integer number from an integer literal, a float


literal (by rounding down to the previous whole number), or a string
literal (providing the string represents a whole number)

•float() - constructs a float number from an integer literal, a float


literal or a string literal (providing the string represents a float or an
integer)

•str() - constructs a string from a wide variety of data types, including


strings, integer literals and float literals
Python Casting
Python Operators

Python divides the operators in the following groups:

•Arithmetic operators

•Assignment operators

•Comparison operators

•Logical operators

•Identity operators

•Membership operators

•Bitwise operators
Note:
Floor Division (//) –
The division of operands where the result is the quotient in which the digits after
the decimal point are removed. But if one of the operands is negative, the result
is floored, i.e., rounded away from zero (towards negative infinity) −
9//2 = 4
9.0//2.0 = 4.0,
-11//3 = -4
-11.0//3 = -4.0
•Arithmetic operators
Python Script OUTPUT
Python Assignment Operators
Python Comparison Operators

Python Script

x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Python Identity Operators:

Identity operators are : is and is not

They are used to check if two values (or variables) are


located on the same part of the memory. Two variables
that are equal does not imply that they are identical.
Python Identity Operators
Python Identity Operators

Explanation:
Membership operators are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).

In a dictionary we can only test for presence of key, not the value.
Python Membership Operators
Python Bitwise Operators
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary
Arithmetic operations on strings
+ operator (for concatenation):
When you use + on strings, it will concatenate them together.

print('hello' + 'world')
Output:
helloworld

* Operator (for repetition):


When you multiply a string by an integer, n, the string will be repeated n times:

print('hello' * 3)
Output:
hellohellohello

Note:

If you place two strings next to each other, they will also be concatenated:
print('hello' 'world')
Output:
helloworld
Discussion
What is the maximum possible length of an
identifier?

a) 31 characters
b) 63 characters
c) 79 characters
d) none of the mentioned

Answer: d
Explanation: Identifiers can be of any length.
Which of the following is invalid?

a) _a = 1
b) __a = 1
c) __str__ = 1
d) none of the mentioned

Answer: d
What will be the output of the following program on
execution?

if False:
print ("inside if block")
elif True:
print ("inside elif block")
else:
print ("inside else block")

A. inside if block
B. inside elif block
C. inside else block
D. Error

Ans : B
What will be the output of following Python
code snippet?
str1="012"
num1=2 A. 7
num2=0 B. Infinite Loop
for i in range(4): C. 0
D. Error
num1+=2
for j in range(len(str1)): Ans : C
num2=num2+num1
num3=num2%int(str1)
print(num3)
What is the type of inf ?

a) Boolean
b) Integer
c) Float
d) Complex

Answer: c

Explanation: Infinity is a special case of floating point


numbers. It can be obtained by float(‘inf’
Which of the following is incorrect?

a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964

Answer: d

Explanation: Numbers starting with a 0 are octal


numbers but 9 isn’t allowed in octal numbers.
What will be the output of the following Python code?
i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1

a)1 2 3 4 5 6

b)1 2 3 4 5 6 7

c)Error

d) none of the mentioned

Answer: a
What will be the output of the following Python
code?

for i in range(2.0):
print(i)

Answer: c

Explanation: Object of type float cannot be


interpreted as an integer.
What will be the output of the following Python code?

for i in range(int(2.0)):
print(i)

Answer: b
Explanation: range(int(2.0)) is the same as range(2).

You might also like