Data Types Variables
Simple Input/output
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
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
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.
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
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.
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”
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__)
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'
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.
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).
Operators
Python Operation
Arithmetic Operator
Algebraic Expression
Python Expression
Order of Evaluation
Exponentiation
** x
yx ** 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 -> leftClassic 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
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
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
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
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)
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.
Simple Input /Output
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(“”)
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: “))
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: “))
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.
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”)
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”)