• No results found

Data Types

N/A
N/A
Protected

Academic year: 2022

Share "Data Types"

Copied!
25
0
0

Loading.... (view fulltext now)

Full text

(1)

Data Types Variables

Simple Input/output

(2)

Data Types

Consider this sentence: “In February 2020, the basic salary of Mr. Sahil was Rs. 50000 and HRA 1000.”

In real life, there is no need to consider what kind of data we’re using.

In programming language, It is required to keep in mind

Type of data.

Operations on data.

Example:

The division of an integer by an integer is valid.

The division of a string by any string is not valid.

2

(3)

Data Types

Data Type

It consists of a set of values and a set of operations that can be performed on those values.

Everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes

Literal/Value

A literal in a program is used to mention a data value.

3

(4)

Data Types

Numeric data type – Integer, Floating point Number, Complex Numbers

The data having numeric value.

Integers

Can be defined directly or using int class ( int() ).

Contains whole numbers

Float

Can be defined directly or using float class ( float() )

Consists of real number.

It is specified by a decimal point.

Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation.

Complex Numbers

Can be defined directly or using complex class ( complex() )

Complex numbers are represented as (real part) + (imaginary part)j.

(5)

Variables

❑ A variables is a named location in memory that can hold a value of a given type.

❑ Each variable has address.

❑ The i n t e r p r e t e r a l l o c a t e s memory based on the data type of a variable .

❑ Rules to define variable names

Can only contain letters, numbers, and underscores

Can’t start with a number

Can be arbitrarily long

Can't be keywords

❑ Good variable names consists of

Descriptive names

Consistent

Follow the traditions of the language

Keep the length in check

(6)

Identifier

❑ All variables are identifier.

❑ An identifier is a user-defined name to identify

❑ Variable

❑ Function

❑ Class

❑ Module

❑ Other objects.

❑ The rules to define identifiers are same as for

variables.

(7)

CREATING VARIABLES

Variables must be created first

❑ There is no need to declare variables explicitly.

❑ Use assignment operator (=) to create a variable and assign a value to it

❑ The operand to the left of = operator is the name of the variable and the value on the right of = operator is the operand which is stored in the variable.

❑ Example

x = 10

y = 20.5

name = “Sarah”

(8)

Variable: Identity and Type

The identity of an object is an integer, which is guaranteed to be unique and constant for this object during its lifetime.

Two objects with non-overlapping lifetimes may have the same id() value.

id() : Returns identity (decimal integer) of a variable/object/constant.

type() : Returns type of variable/object/constant.

hex() : Returns hexadecimal equivalent (string) of a number.

• Example

type (name)

type(“Sarah”) type(10)

type(x) type(y) type(20.5)

• Example x = 10;

id(x);

hex(id(x)) bin(id(x))) oct(id(x)))

dir(__builtins__)

(9)

Keywords

Keywords are reserved words

35 keywords

Can’t be used as variable or identifier names.

All keywords contain lowercase letters only.

To check the list of keywords, try following two commands

import keyword

print(keyword.kwlist)

'False', ‘None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', ‘yield'

(10)

Exercise

Write a program to find the type of different variables.

Int

Float

String

Complex

Write a simple program to find the total number of built-in functions, objects and exceptions supported by Python.

dir(__builtins__) ----Built-in functions, exceptions, and other objects

Write a simple program to find the total number of keywords supported by Python.

(11)

Operators and Operands

• The operators are special symbols that represent computations like addition and multiplication.

• The values/literals/variables the operators are applied to are known as operands.

• There are unary and binary operators .

• Ternary operator is realized using if expression.

• Example

• Negation operator is an unary operator (a = -6).

• Addition is binary operator (b = 4 + 7).

(12)

Operators

Python Operation

Arithmetic Operator

Algebraic Expression

Python Expression

Order of Evaluation

Exponentiation

** x

y

x ** y

Right -> left Division

/ x  y x / y

Left -> right Integer Division

// x  y x // y

Left -> right Modulus

% x mod y x % y

Left -> right Multiplication

* xy x * y

Left -> right Addition

+ x + y x + y

Left -> right Subtraction

- x – y x – y

Left -> right Negation

- -x -x

right -> left

(13)

Classic and True Division

Classic Division (Floor Division)

When presented with integer operands, classic division truncates the decimal place, returning an integer.

When given a pair of floating-point operands, it returns the actual floating-point quotient (aka true division).

Example

>>> 1 / 2 returns 0 (Floor Division or truncated integer)

>>> 1.0 / 2.0 returns 0.5 (real quotient or true division) True Division

• True division is where the result is always the real floating-point quotient, regardless of operand type.

• This is the default division operation in any Python 3.x release.

• >>> 1 / 2 # returns real quotient 0.5

• >>> 1.0 / 2.0 # returns real quotient 0.5

(14)

Arithmetic Expression and Precedence Rules

• A combination of operands (values, variables) and operators.

• Expressions provide an easy way to perform operations on data values to produce other data values.

• Legal expression – (2 + 3 -4)*3**3 – 4*5**6

• Illegal expression

– (2 ++ 3 // 4)*3***3

• Be careful of the order of evaluation!

• PEDMAS Law

– Do what is in parentheses first!

– Unary negation is evaluated next – ** and associativity is right to left – *, /, % and associativity is left to right – +, - and associativity is left to right

– Example- (2 + 3 - 4)*3**3

(15)

Data Types: Strings

• A string is a sequence of characters enclosed in single (‘), double(“) and (“‘) quotation marks.

Can be defined directly or using string class ( str() ).

• A string is a collection of one or more characters enclosed in a single quote, double-quote or triple quote.

• The string literal must starts and ends with same type of quotation marks.

• In python there is no character data type, a character is a string of length one.

• ‘Hello’, “Hello”, “‘Hello’’’, ‘3.7’, “100”

• “” ; ‘’ ; “‘’’’- Empty string

• len() – Can used to compute the length of the string

(16)

Escape Sequences with Strings

• An escape sequence is a special sequence of

characters that provide more functionality in order to display the text.

\’ Single quote, prints one single quote

\’’ Double quote, prints one double quote

\n Newline, moves the cursor to the beginning of next line

\t Horizontal tab, Moves cursor forward one tab stop

(17)

String Operators

Concatenation

String concatenation means to join two or more strings into a single string.

The plus sign (+) is the string concatenation operator.

Example-

a = “Hello, ” + “how ” + “are ” + “you”.

“Hello” + “how” + “are” + “you” (Interpreter mode)

print (“Hello” + “how” + “are” + “you”)

print (“Hello”, “how”, “are”, “you”)

Repetition operator

Strings can be repeated; multiple copies of the same string concatenated together

The multiplication sign (*) is the string repetition operator.

Example:

❑ print(“Hello, Python is amazing” * 3)

(18)

Exercise

Machine learning (ML) is the ‘scientific study’ of algorithms and

“statistical models” that computer systems use to effectively perform a specific task without using explicit instructions, relying on models and inference instead. It is seen as a subset of “artificial intelligence”.

Write a program to print above paragraph using single print

statement.

(19)

Simple Input /Output

(20)

25

Getting User Input

• How do we get user input?

– What function do we use?

– What types does it use? Strings? Integers?

– What do we do with the input?

• Use the Python function input()

• The input function only reads the string.

• Example

name = input(“Please, enter your name ”) name = input(“”)

(21)

Converting Values (String to Integers)

• String values can be converted to integers using the int() function – Example

Z = int(“10”)

Z = int(“10.5”) — What?

• The int() function returns an error if string is not the sequence of digits (without decimal point).

First read the string using input function and convert it into integer using the int() function

• Example

y = input(“Enter your score: ”) Z = int( y )

OR

Z = int( input( “Enter your score: “))

(22)

Converting Values (String to Float)

String values can be converted to float using the float() function

– Example

z = float(“55.5”)

z = float (“50”)

The float() function returns an error if string is not the sequence of digits with single decimal point.

First read the string using input function and convert it into float using the float() function

Example

y = input(“Enter your weight: ”) Z = float( y )

OR

z = float( input( “Enter your weight: “))

(23)

Exercise

• Write a program to read five integers from user and find the average.

• Write a program to read five real numbers

from user and find the average.

(24)

Lines & Indentation

• No braces to indicate blocks of code for class/function definitions/flow control.

• The line indentation is used to identify the block of code. The line indentation is rigidly enforced.

• The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount i.e.

All the continuous lines indented with same number of spaces would form a block.

Valid Code x =10

if x%2 == 2:

print ( x, ”is even number”) else:

print ( x, ”is odd number”) Invalid Code

x =10

if x%2 == 2:

print ( x, ”is even number”) else:

print ( x, ”is odd number”)

(25)

Multiple Statements on a single Line

• The semicolon ( ; ) allows multiple statements on the single line given.

• Neither statement starts a new code block.

• print(“Guido van Russum created python language”); print(“Python is simple language”)

Thank You

References

Related documents

It was assumed that as the Harappan script had affinity to the Proto-Manding writing (Libyco-Berber) and the Mand- ing language, it could be read by giving these signs the

g.t ; ½/ D .¾ C ½/e .¾ C ½/ t : (8) This means that the age distribution of an exponen- tially growing population of objects with (identical) exponential age distributions

SOCIO-ECONOMIC DEVELOPMENT SERVICES For the Multifarious Development of Society at large, Old, Youth, School Dropouts, Housewives and Children of Financially Downtrodden

Knowledge Management : The Information – Processing Paradigm 1.The process of collecting, organizing, classifying and dissemination of information to make it purposeful to those

World liquids consumption for energy in the industrial sector, which was projected to increase by 1.1 percent per year from 2005 to 2030 in the IEO2008 reference case, increases by

This report provides some important advances in our understanding of how the concept of planetary boundaries can be operationalised in Europe by (1) demonstrating how European

• The vertical vernier scale is used to set the depth (d) along the pitch circle from the top surface of the tooth at which the width (w) has to be measured. • The horizontal

The scan line algorithm which is based on the platform of calculating the coordinate of the line in the image and then finding the non background pixels in those lines and