http://www.skillbrew.com /SkillbrewTalent brewed by the industry itself Variables Pavan Verma @YinYangPavan Python Programming Essentials
© SkillBrew http://skillbrew.com What is a variable 2 >>> print 100 100 >>> counter = 100 >>> print counter 100
© SkillBrew http://skillbrew.com What is a variable (2) 3 • A variable is a memory location that stores a value • The value of a variable can change. That’s why it’s called a variable! • A variable is the basic unit of storing data in a computer program 100counter Somewhere in memory
© SkillBrew http://skillbrew.com What is a variable (3) 4 >>> name = 'Henry Ford' >>> print name Henry Ford • Variables can store values of different types • In this slide, name is a variable of type ‘string’ • In previous slide, counter is a variable of type ‘int’
© SkillBrew http://skillbrew.com Multiple variable assignments in one statement 5 >>> length = height = breadth = 2 >>> length 2 >>> height 2 >>> breadth 2 2length 2breadth 2height
© SkillBrew http://skillbrew.com Multiple variable assignments in one statement 6 >>> x, y = 2, 3 >>> x 2 >>> y 3 2 3y x
© SkillBrew http://skillbrew.com Standard data types Standard Data Types Number String List Tuple Dictionary 7
© SkillBrew http://skillbrew.com Standard data types (2) >>> length = 10 #integer >>> length 10 >>> motive = 'to learn Python' #string >>> motive 'to learn Python' 8
© SkillBrew http://skillbrew.com Standard data types (3) >>> colors = ['brown', 'black', 'orange'] #list >>> colors ['brown', 'black', 'orange'] >>> logs = ('skillbrew.com', 500) #tuple >>> logs ('skillbrew.com', 500) 9
© SkillBrew http://skillbrew.com Standard data types (4) >>> contacts = {'Monty': 123445, 'Guido': 67788} #dictionary >>> contacts {'Monty': 123445, 'Guido': 67788} 10
© SkillBrew http://skillbrew.com type function >>> var = "foo" >>> type(var) <type 'str'> >>> type(8) <type 'int'> >>> type(9.0) <type 'float'> 11
© SkillBrew http://skillbrew.com type function >>> type([1, 2, 3]) <type 'list'> >>> type((1, 2, 3)) <type 'tuple'> >>> type({'1': 'one'}) <type 'dict'> 12
© SkillBrew http://skillbrew.com Python is a dynamically typed language  Variable type is determined at runtime  A variable is bound only to an object and the object can be of any type  If a name is assigned to an object of one type it may later be used to an object of different type 13 Variable Object Type is of
© SkillBrew http://skillbrew.com Python is a dynamically typed language (2) 14 >>> x = 10 >>> x 10 >>> type(x) <type 'int'> >>> x = 'foo' >>> x 'foo' >>> type(x) <type 'str'> >>> x = ['one', 2, 'three'] >>> type(x) <type 'list'>
© SkillBrew http://skillbrew.com Dynamically typed vs Statically typed  The way we used variable in previous slide won’t work in statically typed languages like C, C++, Java  In a statically typed language, a variable is bound to: • an object – at runtime • a type – at compile time 15 Variable Object Type is of Type must match
© SkillBrew http://skillbrew.com Statically Typed (C/C++/Java) int x; char *y; x = 10; printf(“%d”, x) y = “Hello World” printf(“%s”, y) Dynamically Typed – Python x = 10 print x x = “Hello World” print x 16 Dynamically typed vs Statically typed (2)
© SkillBrew http://skillbrew.com Statically Typed (C/C++/Java)  Need to declare variable type before using it  Cannot change variable type at runtime  Variable can hold only one type of value throughout its lifetime Dynamically Typed – Python  Do not need to declare variable type  Can change variable type at runtime  Variable can hold different types of value through its lifetime 17 Dynamically typed vs Statically typed (3)
© SkillBrew http://skillbrew.com Python is a strongly typed language >>> 10 + "10" TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> 10 + int("10") 20 18 In a weakly typed language (eg. perl), variables can be implicitly coerced to unrelated types Not so in Python! Type conversion must be done explicitly.
© SkillBrew http://skillbrew.com Variable naming rules  Variable names must begin with a letter [a-zA- Z] or an underscore (_)  Other characters can be letters[a-zA-Z], numbers [0-9] or _  Variable names are case sensitive  There are some reserved keywords that cannot be used as variable names 19
© SkillBrew http://skillbrew.com Variable naming rules (2) 20 length Length myLength _x get_index num12 1var
© SkillBrew http://skillbrew.com Variable naming rules (3) >>> 1var = 10 SyntaxError: invalid syntax >>> var1 = 10 >>> v1VAR = 10 >>> myVar = 10 >>> _var = 10 >>> Var = 10 21
© SkillBrew http://skillbrew.com Variable naming rules (4) >>> myvar = 20 >>> myVar 10 >>> myvar 20 >>> myVar == myvar False 22
© SkillBrew http://skillbrew.com Accessing non-existent name  Cannot access names before declaring it 23 >>> y Traceback (most recent call last): File "<pyshell#46>", line 1, in <module> y NameError: name 'y' is not defined
© SkillBrew http://skillbrew.com Reserved keywords and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try 24
© SkillBrew http://skillbrew.com Cannot use reserved keywords as variable names >>> and = 1 SyntaxError: invalid syntax >>> if = 1 SyntaxError: invalid syntax >>> 25
© SkillBrew http://skillbrew.com Summary  What is a variable  Different types of variable assignments  Brief introduction to standard data types  type function  Python is a dynamically typed language  Dynamically types versus statically types languages  Python is a strongly typed language  Variable naming rules  Reserved keywords 26
© SkillBrew http://skillbrew.com Resources  Python official tutorial http://docs.python.org/2/tutorial/introduction.html  Blog post on python and Java comparison http://pythonconquerstheuniverse.wordpress.com/2009/10/03/pyt hon-java-a-side-by-side-comparison/  Python guide at tutorialspoint.com http://www.tutorialspoint.com/Python/Python_quick_guide.html  Python type function http://docs.Python.org/2/library/functions.html#type  Blog post on static vs dynamic languages http://Pythonconquerstheuniverse.wordpress.com/2009/10/03/stat ic-vs-dynamic-typing-of-programming-languages/ 27
28

Python Programming Essentials - M5 - Variables

  • 1.
    http://www.skillbrew.com /SkillbrewTalent brewed bythe industry itself Variables Pavan Verma @YinYangPavan Python Programming Essentials
  • 2.
    © SkillBrew http://skillbrew.com Whatis a variable 2 >>> print 100 100 >>> counter = 100 >>> print counter 100
  • 3.
    © SkillBrew http://skillbrew.com Whatis a variable (2) 3 • A variable is a memory location that stores a value • The value of a variable can change. That’s why it’s called a variable! • A variable is the basic unit of storing data in a computer program 100counter Somewhere in memory
  • 4.
    © SkillBrew http://skillbrew.com Whatis a variable (3) 4 >>> name = 'Henry Ford' >>> print name Henry Ford • Variables can store values of different types • In this slide, name is a variable of type ‘string’ • In previous slide, counter is a variable of type ‘int’
  • 5.
    © SkillBrew http://skillbrew.com Multiplevariable assignments in one statement 5 >>> length = height = breadth = 2 >>> length 2 >>> height 2 >>> breadth 2 2length 2breadth 2height
  • 6.
    © SkillBrew http://skillbrew.com Multiplevariable assignments in one statement 6 >>> x, y = 2, 3 >>> x 2 >>> y 3 2 3y x
  • 7.
    © SkillBrew http://skillbrew.com Standarddata types Standard Data Types Number String List Tuple Dictionary 7
  • 8.
    © SkillBrew http://skillbrew.com Standarddata types (2) >>> length = 10 #integer >>> length 10 >>> motive = 'to learn Python' #string >>> motive 'to learn Python' 8
  • 9.
    © SkillBrew http://skillbrew.com Standarddata types (3) >>> colors = ['brown', 'black', 'orange'] #list >>> colors ['brown', 'black', 'orange'] >>> logs = ('skillbrew.com', 500) #tuple >>> logs ('skillbrew.com', 500) 9
  • 10.
    © SkillBrew http://skillbrew.com Standarddata types (4) >>> contacts = {'Monty': 123445, 'Guido': 67788} #dictionary >>> contacts {'Monty': 123445, 'Guido': 67788} 10
  • 11.
    © SkillBrew http://skillbrew.com typefunction >>> var = "foo" >>> type(var) <type 'str'> >>> type(8) <type 'int'> >>> type(9.0) <type 'float'> 11
  • 12.
    © SkillBrew http://skillbrew.com typefunction >>> type([1, 2, 3]) <type 'list'> >>> type((1, 2, 3)) <type 'tuple'> >>> type({'1': 'one'}) <type 'dict'> 12
  • 13.
    © SkillBrew http://skillbrew.com Pythonis a dynamically typed language  Variable type is determined at runtime  A variable is bound only to an object and the object can be of any type  If a name is assigned to an object of one type it may later be used to an object of different type 13 Variable Object Type is of
  • 14.
    © SkillBrew http://skillbrew.com Pythonis a dynamically typed language (2) 14 >>> x = 10 >>> x 10 >>> type(x) <type 'int'> >>> x = 'foo' >>> x 'foo' >>> type(x) <type 'str'> >>> x = ['one', 2, 'three'] >>> type(x) <type 'list'>
  • 15.
    © SkillBrew http://skillbrew.com Dynamicallytyped vs Statically typed  The way we used variable in previous slide won’t work in statically typed languages like C, C++, Java  In a statically typed language, a variable is bound to: • an object – at runtime • a type – at compile time 15 Variable Object Type is of Type must match
  • 16.
    © SkillBrew http://skillbrew.com StaticallyTyped (C/C++/Java) int x; char *y; x = 10; printf(“%d”, x) y = “Hello World” printf(“%s”, y) Dynamically Typed – Python x = 10 print x x = “Hello World” print x 16 Dynamically typed vs Statically typed (2)
  • 17.
    © SkillBrew http://skillbrew.com StaticallyTyped (C/C++/Java)  Need to declare variable type before using it  Cannot change variable type at runtime  Variable can hold only one type of value throughout its lifetime Dynamically Typed – Python  Do not need to declare variable type  Can change variable type at runtime  Variable can hold different types of value through its lifetime 17 Dynamically typed vs Statically typed (3)
  • 18.
    © SkillBrew http://skillbrew.com Pythonis a strongly typed language >>> 10 + "10" TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> 10 + int("10") 20 18 In a weakly typed language (eg. perl), variables can be implicitly coerced to unrelated types Not so in Python! Type conversion must be done explicitly.
  • 19.
    © SkillBrew http://skillbrew.com Variablenaming rules  Variable names must begin with a letter [a-zA- Z] or an underscore (_)  Other characters can be letters[a-zA-Z], numbers [0-9] or _  Variable names are case sensitive  There are some reserved keywords that cannot be used as variable names 19
  • 20.
    © SkillBrew http://skillbrew.com Variablenaming rules (2) 20 length Length myLength _x get_index num12 1var
  • 21.
    © SkillBrew http://skillbrew.com Variablenaming rules (3) >>> 1var = 10 SyntaxError: invalid syntax >>> var1 = 10 >>> v1VAR = 10 >>> myVar = 10 >>> _var = 10 >>> Var = 10 21
  • 22.
    © SkillBrew http://skillbrew.com Variablenaming rules (4) >>> myvar = 20 >>> myVar 10 >>> myvar 20 >>> myVar == myvar False 22
  • 23.
    © SkillBrew http://skillbrew.com Accessingnon-existent name  Cannot access names before declaring it 23 >>> y Traceback (most recent call last): File "<pyshell#46>", line 1, in <module> y NameError: name 'y' is not defined
  • 24.
    © SkillBrew http://skillbrew.com Reservedkeywords and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try 24
  • 25.
    © SkillBrew http://skillbrew.com Cannotuse reserved keywords as variable names >>> and = 1 SyntaxError: invalid syntax >>> if = 1 SyntaxError: invalid syntax >>> 25
  • 26.
    © SkillBrew http://skillbrew.com Summary What is a variable  Different types of variable assignments  Brief introduction to standard data types  type function  Python is a dynamically typed language  Dynamically types versus statically types languages  Python is a strongly typed language  Variable naming rules  Reserved keywords 26
  • 27.
    © SkillBrew http://skillbrew.com Resources Python official tutorial http://docs.python.org/2/tutorial/introduction.html  Blog post on python and Java comparison http://pythonconquerstheuniverse.wordpress.com/2009/10/03/pyt hon-java-a-side-by-side-comparison/  Python guide at tutorialspoint.com http://www.tutorialspoint.com/Python/Python_quick_guide.html  Python type function http://docs.Python.org/2/library/functions.html#type  Blog post on static vs dynamic languages http://Pythonconquerstheuniverse.wordpress.com/2009/10/03/stat ic-vs-dynamic-typing-of-programming-languages/ 27
  • 28.

Editor's Notes

  • #3 Example is from Python shell 100 is a constant Counter is a variable
  • #5 We will talk more about types later in this module
  • #8 There are multiple number types, which we’ll see soon
  • #9 This is just a very brief intro to all data types mentioned in previous slide Things after a # are comments
  • #10 List if a sequence of things Tuple is also a sequence of things Difference between list and tuple: a list is mutable (can be modified) while a tuple is immutable (cannot be modified)
  • #11 Disctionary is a bunch of key-value pairs
  • #12 The ‘type’ function returns the datatype of the variable Type of a variable = the type of data it is storing currently The notion of variable type in Python is different in Python versus C/C++/Java. Python is dynamically typed which means that the variable can hold different types of data during its lifetime. However, C/C++/Java are statically types, which means that the variable can hold only one type of data during its entire lifetime When a constant is passed to the type function, Python internally creates a temporary variables and passes that to the function Float is another of number type
  • #15 x can be assigned any value. There is no type tied to variable x it can be assigned any value we like.
  • #19 An operation like 10 + “10” would work in a weakly typed language like perl, it would do the conversions implicitly Python does not allow this. You have to type conversion yourself.
  • #21 1var : cannot start a variable name with integer
  • #22 1var : cannot start a variable name with integer
  • #23 myVar == myvar : variables are case sensitive
  • #24 On accessing a non existing variable python throws NameError