Data Types in Computer Programming
Data types in computer programming are crucial for storing and manipulating information efficiently. Programs define different data types such as numbers, characters/strings, and collections to handle diverse data. Python supports primitive, simple, numerical, string, logical, and None data types, each serving specific purposes. From integers, floating-point numbers, and complex numbers to strings and boolean values, understanding these data types is fundamental in software development.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Data and Data Types Computer programs are written to store and manipulate information, or data Depending on the kind of information different data types are defined Ex: numbers, characters/strings, collections Professor John Carelli Kutztown University Computer Science Department
Primitive Data Types in Python Python has built-it support for storing and manipulating different types of information Referred to as primitive data types Two broad categories: Simple values contain one piece of information Data Structures contain a collection of data elements Professor John Carelli Kutztown University Computer Science Department
Simple Data Types Python has built-in support for the following simple data types Numbers Strings one or more characters alphabetic, numbers, symbols, Logical: True or False NoneType Professor John Carelli Kutztown University Computer Science Department
Numerical Data Integers - represent whole numbers round numbers - no fractions or decimals positive, negative, or zero Floating point numbers Fractional numbers (i.e. those with decimal points) Can be represented in either decimal or scientific notation Decimal notation: 3.14159 Scientific notation: 2.75e3 (mantissa and exponent) same as 2.73x103 Complex numbers (contain a real and imaginary part) imaginary part has j suffix: 1+2.0j Professor John Carelli Kutztown University Computer Science Department
Strings Python recognizes alphanumeric characters enclosed in quotes as a string Can use either single, double (or even triple quotes!) Examples: A (a single character) John Hello World! Professor John Carelli Kutztown University Computer Science Department
Logical Data Represents conditional values Supports only two values: True or False Note: True and False are not strings no quotes! Sometimes referred to as Boolean data Named for George Boole English mathematician (mid 1800 s) developed Boolean Algebra Used in decision making statements More on this later . Professor John Carelli Kutztown University Computer Science Department
NoneType Special data type Used as a default function return type i.e. when no explicit return value is defined Only one value: None Professor John Carelli Kutztown University Computer Science Department
Variables Variables are used to store information A variable is a named memory location that contains the stored information Name is selected by the programmer see next slide for naming rules Professor John Carelli Kutztown University Computer Science Department
Valid variable names May only contain letters, numbers, and underscore (_) Good: name, x, abc123, last_name Bad: last-name Cannot begin with a number Bad: 1letter Are case-sensitive Name is not the same as name Cannot be Python Keywords Keywords are words reserved for use by a programming language Professor John Carelli Kutztown University Computer Science Department
Variable creation via assignment Variables are created (or updated) automatically whenever an assignment operation is performed Assignment uses the = operator Syntax: variable = value variable : a valid variable name value : the value to be stored Python automatically infers the data type for the variable based on the value being stored Number (int or float) vs. String vs. Boolean Professor John Carelli Kutztown University Computer Science Department
Assignment examples Using a fixed literal value x= 2 PI= 3.14159 name= Sam Using another variable x= y Using the result of an expression twoPI= 2.0*PI Using a function return value name = input( Enter your name: ) Professor John Carelli Kutztown University Computer Science Department
Literals Literal is a term used to describe an explicit, fixed data value. As opposed to a value that is the result of a computation (like z=x+y;) Any variable can be assigned a literal value Using the assignment (=) operator The variable then has that data type integer assignment i= 10 j= 0 k= -23 10, 0 and -23 are literals Professor John Carelli Kutztown University Computer Science Department
Floating point Literals Scientific Notation Two parts Mantissa the decimal number before the e Exponent the characteristic (exponent) is the integer after the e Floating point data x= 3.14159 // fixed notation y= 3.2e5 // scientific notation z= -15e-10 // neg value, neg exponent Numerical values above are floating point literals number= mantissa x 10characteristic Professor John Carelli Kutztown University Computer Science Department
String Literals Hello World! Strings can be enclosed in single, double, or even triple quotes Allows for strings with embedded quotes Triple quotes preserve new line characters Often used in comments and in strings intended to span multiple lines of output Pennsylvania A Sam s club this is a triple quoted string with embedded newline characters triple double quotes! Examples of String Literals Professor John Carelli Kutztown University Computer Science Department
Escape Characters Use a backslash character \ to modify the interpretation of the character immediately following in a string \ and \ treat the quotes as literal characters in a string \n is used to embed a new line character in a string For example: Sam\ s club Will treat the second as a literal apostrophe, not the end of the string msg= Hello\nworld Puts a new line between the words This would get printed on 2 lines, like this Hello world Professor John Carelli Kutztown University Computer Science Department
Constants Sometimes we want to define a variable whose value is fixed, i.e. cannot be changed Some languages, like C++, have a mechanism for enforcing this Python does not... however ... Example Constants PI= 3.1415926 SALES_TAX= 0.06 Convention for constants Use all uppercase letters Separate words with underbars Note: value can still be changed, but users understand not to Professor John Carelli Kutztown University Computer Science Department
Built-in Data Structures In addition to built in support for simple (single valued) data types, Python supports the following data structures for storing multiple values list tuple dict (short for dictionary) set Professor John Carelli Kutztown University Computer Science Department
Lists A list is an ordered collection of data elements Like an array in C/C++ Created using a comma separated list of elements in brackets Examples: [ 1, 3, 5, 7, 9 ] [ PA , NJ , NY ] Professor John Carelli Kutztown University Computer Science Department
Storing a list in a variable The list can be stored in a variable with an assignment The variable contains a list object Use empty brackets [] to create an empty list Examples: odd_ints = [ 1, 3, 5, 7, 9 ] states = [ "PA", "NJ", "NY" ] empty = [] Professor John Carelli Kutztown University Computer Science Department
Accessing items in a list Individual objects in the list are accessed, and modified if desired, using the bracket notation with numerical (integer) index Subscript numbering starts at zero Ends at N-1 where N is the number of elements in the list Examples: states = [ "PA", "NJ", "NY" ] print(states[1]) states[2]= DE # will output: NJ # will change NY to DE Professor John Carelli Kutztown University Computer Science Department
Negative indexing Negative index accesses values from the end of the list [-1] is the last element, [-2] is the second to last, etc Examples: states = [ "PA", "NJ", "NY" ] print(states[-1]) states[-2]= DE # states[0] and states[-3] both refer to PA # will output: NY # will change NJ to DE Professor John Carelli Kutztown University Computer Science Department
Slicing Slicing creates a new list by extracting a portion of an existing list Use bracket notation to identify what to extract Original list is unaffected Extraction rules: Syntax: listname[ begin : end : step ] Start at the begin index If begin is missing, use 0 Stop at index (end 1) !!! If end is missing, use the list length Skip items If stepis missing, use 1 (don t skip anything) lst= [1, 2, 3, 4, 5] # result: [2, 3, 4] lst[1:4] # result: [1, 2, 3] lst[:3] # result: [3, 4, 5] lst[2:] # result: [1, 3, 5] lst[::2] Professor John Carelli Kutztown University Computer Science Department
More list properties numa= [ 1, 2, 5, ] numb= [ -8, 4, -2 ] Object stored in a list do not all have to be the same type: lst= [1, 'a', True] # this is valid! Lists can be concatenated with + Produces a new list Lists are mutable (they can be modified) List size (number of elements) can be retrieved with the global len() function # this will print 1 print(numa[0]) # this will set numb[1] to 7 numb[1]= numa[1] + numb[1] # this will create a new list num # containing: [ 1, 2, 5, -8, 6, -2 ] num= numa + numb # this will return 6 len(num) Professor John Carelli Kutztown University Computer Science Department
Some List methods Lists are objects, so they have methods count Return the number of times a given element appears in the list. insert Inserts a new element at a given index. The list gets larger. append Adds a new element to the END of the list. index Used to return the lowest index an element appears at. If the element doesn't exist, an error is returned. remove Remove the first occurrence of the given element. Error if element isn't found. Reduces the list length by one. reverse Physically reverses the elements in the list. sort Sorts the elements in ascending order. Professor John Carelli Kutztown University Computer Science Department
Tuples A tuple is like a list, with an important difference Tuples are immutable Once created, they can t be modified! Tuple are generally created using parenthesis no brackets However, the parenthesis can be omitted Examples: States = ("Pennsylvania", "New Jersey", "New York") numbers = 10, 20, 30, 40, 50 Professor John Carelli Kutztown University Computer Science Department
More on tuples As with lists, individual items are accessed using an index number: Use [] start at zero and end at size-1 Tuples also support slicing (same rules as lists) >>> states=("PA","NJ","NY") >>> states ('PA', 'NJ', 'NY') >>> states[0] 'PA' >>> states[2] 'NY' >>> len(states) 3 Also: len() function will return the size Can t change the values in a tuple states[3]= FL # wrong!!! Professor John Carelli Kutztown University Computer Science Department
Tuple methods Tuples are objects, so they have methods, but they are fewer and more limited than list methods (since tuples are immutable) count Get the number of times an element appears in the tuple. index Used to return the lowest index an element appears at. If the element doesn't exist, an error is returned. Overall, tuples are less complex than lists Professor John Carelli Kutztown University Computer Science Department
Dictionaries Dictionaries store arbitrary keyword/value pairs i.e., maps, associative arrays, hashes, Dictionaries are mutable, items can be added and removed (using del()) As of Python 3.6, dictionary are ordered as inserted (unordered previously) Created with curly braces and comma separated key:value pairs numbers = { 'one': 1, 'two': 2, 'three': 3 } empty= dict() # create an empty dictionary Values are accessed using square brackets and the key Two= numbers['two'] Dictionaries are objects with methods Professor John Carelli Kutztown University Computer Science Department
Sets Sets are objects that store unordered collections of unique items unordered w/r to the order in which they are added Sets are defined by a comma separated list of values in curly braces primes = {2, 3, 5, 7} odds = {1, 3, 5, 7, 9} Sets support mathematical set operations >>> primes | odds {1, 2, 3, 5, 7, 9} >>> primes.union(odds) {1, 2, 3, 5, 7, 9} Professor John Carelli Kutztown University Computer Science Department