Python - Variable Types. John R. Woodward

Similar documents
Python memento TI-Smart Grids

COLLEGE OF ENGINEERING, NASHIK-4

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

S206E Lecture 19, 5/24/2016, Python an overview

What is Python? Developed by Guido van Rossum in the early1990s Named after Monty Python Available on eniac Available for download from

Introduction to Python

Level 3 Computing Year 2 Lecturer: Phil Smith

UNIVERSITÀ DI PADOVA. < 2014 March >

Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

Variable and Data Type I

Variable and Data Type I

Financial Accounting Tutorial

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Advanced Algorithms and Computational Models (module A)

This is an introductory tutorial, which covers the basics of Jython and explains how to handle its various modules and sub-modules.

GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING Question Bank

Introduction to Bioinformatics

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Variable and Data Type 2

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Senthil Kumaran S

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Python Intro GIS Week 1. Jake K. Carr

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Variables, expressions and statements

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Introduction to Python

CS Advanced Unix Tools & Scripting

>>> * *(25**0.16) *10*(25**0.16)

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Compiler principles, PS1

a name refers to an object side effect of assigning composite objects

Variables, Constants, and Data Types

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Objectives. In this chapter, you will:

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Python Review IPRE

CSCE 110 Programming I

Python in 10 (50) minutes

Collections. Lists, Tuples, Sets, Dictionaries

6. Data Types and Dynamic Typing (Cont.)

The current topic: Python. Announcements. Python. Python

Topic 2: Introduction to Programming

Programming in Python

Introduction to Java & Fundamental Data Types

Python: common syntax

Script language: Python Data structures

Python for Non-programmers

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Introduction to Python

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Full file at

Python Input, output and variables

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Swift. Introducing swift. Thomas Woodfin

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Data Structures. Lists, Tuples, Sets, Dictionaries

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Chapter 2. Lexical Elements & Operators

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Slicing. Open pizza_slicer.py

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Ceng 111 Fall 2015 Week 8a

Artificial Intelligence A Primer for the Labs

egrapher Language Reference Manual

Webinar Series. Introduction To Python For Data Analysis March 19, With Interactive Brokers

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Python Review IPRE

Python and Bioinformatics. Pierre Parutto

Advanced Python. Executive Summary, Session 1

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

Chapter 2: Basic Elements of C++

CS Summer 2013

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

1/11/2010 Topic 2: Introduction to Programming 1 1

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

Here n is a variable name. The value of that variable is 176.

3 The Building Blocks: Data Types, Literals, and Variables

Visual C# Instructor s Manual Table of Contents

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

MUTABLE LISTS AND DICTIONARIES 4

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Visualize ComplexCities

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Contents. Lezione 3. Reference sources. Contents

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Transcription:

Python - Variable Types John R. Woodward

Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 2. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. 3. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables 1. Python variables do not have to be explicitly declared to reserve memory space. 2. The declaration happens automatically when you assign a value to a variable. 3. The equal sign (=) is used to assign values to variables. (= read as is assigned the value ) 4. The operand to the left of the = operator is the name of the variable 5. The operand to the right of the = operator is the value stored in the variable. For example:

For example #!/usr/bin/python counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print counter print miles print name

output 1. Here, 100, 1000.0 and "John" are the values assigned to counter, miles and name variables, respectively. 2. running this program, this will produce : 100 1000.0 John

Multiple Assignment 1. Python allows you to assign a single value to several variables simultaneously. For example: 2. a = b = c = 1 3. Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example: 4. a, b, c = 1, 2, "john 5. Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one string object with the value "john" is assigned to the variable c. 6. a, b, c = 1, "john # WHAT HAPPENS HERE

Standard Data Types 1. The data stored in memory can be of many types. 2. For example, a person's age is stored as a numeric value 3. address is stored as alphanumeric characters. 4. Python has various standard types that are used to define the operations possible on them and the storage method for each of them. 5. Python has five standard data types: Numbers, String, List, Tuple, Dictionary

Python Numbers 1 1. Number data types store numeric values. 2. They are immutable data types which means that changing the value of a number data type results in a newly allocated object. 3. Number objects are created when you assign a value to them. For example: var1 = 1 var2 = 10

Python Numbers 2 1. You can also delete the reference to a number object by using the del statement. 2. The syntax of the del statement is: 3. del var1[,var2[,var3[...,varn]]]] 4. You can delete a single object or multiple objects by using the del statement. For example: del var1[,var2[,var3[...,varn]]]]

Python supports four different 1. int (signed integers) numerical types 2. long (long integers [can also be represented in octal and hexadecimal]) 3. float (floating point real values) 4. complex (complex numbers)

Here are some examples of numbers: int long float complex 10 51924361L 0.0 3.14j 100-0x19323L 15.20 45.j -786 0122L -21.9 9.322e-36j 080 0xDEFABCECBDAEC BFBAEl 32.3+e18.876j -0490 535633629843L -90. -.6545+0J -0x260-052318172735L -32.54e100 3e+26J 0x69-4721885298529L 70.2-E12 4.53e-7j

Strings 1. Strings in Python are identified as a contiguous set of characters in between quotation marks. 2. Python allows for either pairs of single or double quotes. 3. Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the string 4. and working their way from -1 at the end. 5. The plus (+) sign is the string concatenation operator and the asterisk ( * ) is the repetition operator.

For example: str = 'Hello World!' 1. print str # Prints complete string 2. print str[0] the string # Prints first character of 3. print str[2:5] from 3rd to 5th # Prints characters starting 4. print str[2:] 3rd character # Prints string starting from 5. print str * 2 # Prints string two times 6. print str + "TEST" # Prints concatenated string

This will produce the following result: 1. Hello World! 2. H 3. llo 4. llo World! 5. Hello World!Hello World! 6. Hello World!TEST

Lists 1. Lists are the most versatile of Python's compound data types. 2. A list contains items separated by commas and enclosed within square brackets ([]). 3. To some extent, lists are similar to arrays in C. 4. One difference between them is that all the items belonging to a list can be of different data type. 5. The values stored in a list can be accessed using the slice operator ([ ] and [ : ]) with indexes starting at 0 in the beginning of the list 6. and working their way to end -1. 7. The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator.

For example: list = [ 'abcd', 786, 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list #Prints complete list print list[0] #Prints first element of the list print list[1:3] #Prints elements starting from 2nd till 3rd print list[2:] #Prints elements starting from 3rd element print tinylist * 2 #Prints list two times print list + tinylist # Prints concatenated lists

output 1. ['abcd', 786, 2.23, 'john', 70.2] 2. abcd 3. [786, 2.23] 4. [2.23, 'john', 70.2] 5. [123, 'john', 123, 'john'] 6. ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Tuples 1. A tuple is another sequence data type that is similar to the list. 2. A tuple consists of a number of values separated by commas. 3. Unlike lists, however, tuples are enclosed within parentheses (). 4. The main differences between lists and tuples are: 5. Lists are enclosed in brackets ([ ]) and their elements and size can be changed. 6. tuples are enclosed in parentheses ( ( ) ) and cannot be changed. Tuples can be thought of as readonly lists.

For example tuple = ( 'abcd', 786, 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple # Prints complete list print tuple[0] # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints list two times print tuple + tinytuple # Prints concatenated lists

This will produce the following result: ('abcd', 786, 2.23, 'john', 70.2) abcd (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Cannot change a tuple 1. Following is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists: 2. tuple=('abcd', 786, 2.23, 'john', 70.2 ) 3. list=['abcd', 786, 2.23, 'john', 70.2 ] 4. tuple[2] = 1000 5. # Invalid syntax with tuple WHAT message? 6. list[2] = 1000 7. # Valid syntax with list

Dictionary LOOK UP TABLE 1. Think of the key to the value 2. Python's dictionaries are kind of hash table type. 3. They work like associative arrays or hashes found in Perl and consist of key-value pairs. 4. A dictionary key can be almost any Python type, but are usually numbers or strings. 5. Values, on the other hand, can be any arbitrary Python object. 6. Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed using square braces ( [] ).

For example: dict = {} KEY VALUE dict['one'] = "This is one" one dict[2] = "This is two" Tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # Prints value for 'one' key print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values This is one 2 This is two

output This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john ] Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered. (note: there are ordered dictionaries)

Data Type Conversion 1. Sometimes, you may need to perform conversions between the built-in types. 2. To convert between types, you simply use the type name as a function. 3. There are several built-in functions to perform conversion from one data type to another. 4. These functions return a new object representing the converted value.

Int long x = int("100",2) #Converts x to an integer. base specifies the base if x is a string. print x print type(x) x = long("100",10 ) print x print type(x) #Converts x to a long integer. base specifies the base if x is a string.

Output Int long 4 <type 'int'> 100 <type 'long'>

Float, Complex print float("-32.54e100") print float("-32.54e-100") print float("7.2e12") #Converts x to a floating-point number. print complex(2,3) #Creates a complex number.

output -3.254e+101-3.254e-99 7.2e+12 (2+3j)

str x = 9 print x print type(x) x = str(x) print x print type(x) #Converts object x to a string representation. 9 <type 'int'> 9 <type 'str'>

eval x = eval("1+2") print x print type(x) #Evaluates a string and returns an object. OUTPUT is as follows 3 <type 'int'> This will evaluate a string as if it were Python code. Why is it DANGEROUS

tuple print tuple("123") #Converts to a tuple. ('1', '2', '3')

list print list("123") #Converts to a list. ['1', '2', '3']

set print set("123") #Converts s to a set. set(['1', '3', '2'])

dict print dict(sape=4139, guido=4127, jack=4098) #Creates a dictionary. must be a sequence of (key,value) tuples. {'sape': 4139, 'jack': 4098, 'guido': 4127}