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

Chapter 5

The document discusses various data types in Python and PHP including numeric, string, boolean, and conversion between data types. It provides examples of declaring variables of different data types and performing operations on them. It also explains implicit and explicit type conversion between data types in both languages.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chapter 5

The document discusses various data types in Python and PHP including numeric, string, boolean, and conversion between data types. It provides examples of declaring variables of different data types and performing operations on them. It also explains implicit and explicit type conversion between data types in both languages.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

5

DATA STRUCTURES
Data Structures
Data Structure is a collection of data objects characterized by how the objects are accessed. It is an
Abstract Data Type that is implemented in a particular programming language.

Basic Terms
 Interface − Each data structure has an interface. Interface represents the set of operations that a data structure
supports. An interface only provides the list of supported operations, type of parameters they can accept and
return type of these operations.

 Implementation − Implementation provides the internal representation of a data structure. Implementation also
provides the definition of the algorithms used in the operations of the data structure.
Data Type
Data type is a way to classify various types of value which determines
 the values that can be used with the corresponding type of data
 the type of operations that can be performed on the corresponding type of data.

There are two data types :

 Built-in Data Type: Those data types for which a language has built-in support
 Derived Data Type: Those data types which are implementation independent as they can be implemented in
one or the other way are known as derived data types. These data types are normally built by the combination
of primary or built-in data types and associated operations on them.
Python: Numeric Data Type
Integers
You can use an integer represent numeric data, and more specifically, whole numbers from negative infinity to
infinity, like 4, 5, or -1.
Float
"Float" stands for 'floating point number'. You can use it for rational numbers, usually ending with a decimal
figure, such as 1.11 or 3.14.

1 # Floats 1 # Returns the quotient


2 x = 4.0 2 print(x / y)
3 y = 2.0 3 # Returns the remainder
4 # Addition 4 print(x % y)
5 print(x + y) 5 # Absolute value
6 # Subtraction 6 print(abs(x))
7 print(x - y) 7 # x to the power y
8 # Multiplication 8 print(x ** y)
9 print(x * y) 9
Python: Strings
Strings are collections of alphabets, words or other characters. In Python, you can create strings by enclosing a
sequence of characters within a pair of single or double quotes. For example: 'cake', "cookie", etc.
Operation
 The + operation on two or more strings to concatenate
 The * operation to repeat a string a certain number of times:
 Slice operation on strings, which means that you select parts of strings
 Python has many built-in methods or helper functions to manipulate strings. Such as
 Retrieve the length of a string in characters.
 Check if a string contains numbers etc.
Python: Strings

1 #concatenate 1 #length of a string


2 x = 'Cake' 2 str1 = "Cake 4 U"
3 y = 'Cookie' 3 str2 = "404"
4 x + ' & ' + y 4 len(str1)
5 >>>'Cake & Cookie‘ 5 >>>8
6 6
7 #repeat 7 str1.isdigit()
8 x * 2 8 False
9 >>>'CakeCake' 9 str2.isdigit()
>>>True
# Range Slicing
z = y[2:]
print(z)
>>>‘okie‘

#Capitalize strings
str.capitalize('cookie')
>>>'Cookie‘
Python: Boolean
This built-in data type that can take up the values: True and False, which often makes them interchangeable with
the integers 1 and 0. Booleans are useful in conditional and comparison expressions

1 x = 4
2 y = 2
3 x == y
4 >>>False
5 x > y
6 >>True
7 x = 4
8 y = 2
9 z = (x==y)

# Comparison expression (Evaluates to false)


if z: # Conditional on truth/false value of 'z'
print("Cookie")
else: print("No Cookie")
>>>No Cookie
Python: Data Type Conversion
Changing the data type of a variable from one data type to another is called "typecasting". There can be two
kinds of data conversions possible:

Implicit Data Type conversion


This is an automatic data conversion and the compiler handles this for you.
1 # A float
2 x = 4.0
3
4 # An integer
5 y = 2
6
7 # Divide `x` by `y`
8 z = x/y
9
# Check the type of `z`
type(z)
>>>float
Python: Data Type Conversion
Explicit Data Type Conversion
This type of data type conversion is user defined, which means you have to explicitly inform the compiler to
change the data type of certain entities. Note that it might not always be possible to convert a data type to
another. Some built-in data conversion functions that you can use here are: int(), float(), and str().

1 x = 2
2 y = "this"
3 result = (y) + str(x)
4 print(result)
5 >>>this 2
PHP: Numeric Data Type
Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type. They correspond to
simple whole numbers, both positive and negative.
Double
They are decimal numbers. By default, doubles print with the minimum number of decimal places needed

Operations

1 # Double 1 # Returns the quotient


2 $x = 4.0; 2 echo $x / $y;
3 $y = 2.0; 3 # Returns the remainder
4 # Addition 4 echo $x % $y;
5 echo $x + $y; 5 # x to the power y
# Subtraction echo $x ** $y;
echo $x - $y;
# Multiplication
echo $x * $y;
PHP: Strings
Strings are sequences of characters.
1 <?php
2 $variable = "name";
3 $literally = 'My $variable will not print!';
4
5 print($literally);
print "<br>";

$literally = "My $variable will print!";


print($literally);
?>

This will produce following result:


My $variable will not print!
My name will print
PHP: Escape Sequence
These are certain character sequences beginning with backslash (\) and are replaced with special characters.
Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are:
 \n is replaced by the newline character
 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
PHP: Boolean
They have only two possible values either true or false. PHP provides a couple of constants especially
for use as Booleans: TRUE and FALSE.

1 <?php
2 if (TRUE){
3 print “this will always print <br>”;
4 }
5 else {
print “this will never print <br>”;
}
?>
PHP: Boolean
Other data types can be used as Boolean by following these rules:
 If the value is a number; it is false if it is zero else it is “true”.
 If the value is a string; it is false if it is an empty string (has zero characters) or if it is the string "0",
else it is true.
 Values of type NULL are always false.
 If the value is an array, it is false if it contains no other values, and it is true otherwise.
 For an object, containing a value means having a member variable that has been assigned a value.
 Valid resources are true (although some functions that return resources when they are successful will
return FALSE when unsuccessful).
 Don't use double as Booleans.
PHP: Data Type Conversion
When you declare a variable in PHP, you do not specify its type. Its type depends on the value it currently holds.
we verify by using the gettype() function:
1 <?php
2 $val = 'Hello there!'; // assign string
3 echo gettype($val); // string
4 ?>

PHP provides a variety of methods for changing the type of a variable or temporarily changing the type of the
value it holds.
 The settype() Function changes the type of a variable. It is used for strings, integer, float, boolean, array,
object, and null. The variable will retain that type unless you either change the value of the variable to
another type, or use settype() again to assign another type to it.
PHP: Data Type Conversion
1 <?php
2 $val = 24; // integer
3 // set $val type to string
4 settype($val, 'string');
// check type and value of $val
var_dump($val); // string(2) "24"
?>

 The strval() function can be used to convert a value to a string. the strval function returns a converted value but
does not change the type of the variable itself. Related functions are available for converting to other types as
well: intval, floatval, and boolval (for converting to integers, floating point numbers, and booleans).

 Type casting to change the type of a variable. In order to cast a variable (or value) to another type,
specify the desired type in parentheses immediately before the variable you wish to convert. Casting
does not change the type of the variable. It only returns the converted value and makes no lasting
change, just as the conversion functions like strval. In addition to (string), the following casts are also
supported by PHP: (int), (bool), (float), (array), and (object).
Non-Primitive Data Type
Non-primitive types are the sophisticated members of the data structure family. They don't just store a value, but
rather a collection of values in various formats.

In the traditional computer science world, the non-primitive data structures are divided into:
 Arrays
 Lists
 Files

Array been the very basic one will be explained for python and PHP.
Python: Non-Primitive Data Type
Arrays are not popular in Python, unlike PHP. In general, when people talk of arrays in Python, they are actually
referring to lists.
In Python, arrays are supported by the array module and need to be imported before it can be used. The elements
stored in an array are constrained in their data type. The data type is specified during the array creation and
specified using a type code, which is a single character.

1 import array as arr


2 a = arr.array("I",[3,6,9])
3 type(a)
4 array.array

Other Python Types Include


 Tuples
 Dictionary
 Sets
PHP: Non-Primitive Data Type
In PHP, arrays are named and indexed collections of other values. An array is a data structure that stores one or
more similar type of values in a single value.
1 <?php
2 /* First method to create array. */
3 $numbers = array( 3,6,9);
4
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>

Other PHP Types Include


Null
Object
Resource
Python and PHP

Python PHP
Numeric Types Integers, float Integers, Double
Booleans TRUE, FALSE, 0 , 1 True, False, 0, 1, other data
types except double
Strings Single quote (‘..’), double Single quote (‘..’), double
quotes (“..”), triple quotes quotes (“..”)
(‘’’…’’’)
Escape sequences \n , \r , \t , \" , \\ \n , \r , \t , \" , \\ and \$
Determine data type type() gettype()
Changing data type int(), float(), and str() settype(), (string), (int), (bool),
(float), (array), (object), strval,
intval, floatval and boolval
Other types List, Tuples, Dictionary, Sets Array, Null, Object Resource

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy