Your SlideShare is downloading. ×
  • Like
  • Save
Python & Perl: Lecture 03
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Python & Perl: Lecture 03

  • 1,347 views
Published

1) Python Built-In Objects …

1) Python Built-In Objects
2) Numbers
3) Numeric Operations
4) Modules
5) User Input
6) Strings

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,347
On SlideShare
0
From Embeds
0
Number of Embeds
17

Actions

Shares
Downloads
0
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Python & Perl Lecture 03 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  • 2. Outline ● Python Built-In Objects ● Numbers ● Numeric Operations ● Modules ● User Input ● Stringswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 3. Python Built-In Objects ● Numbers ● Strings ● Lists ● Dictionaries ● Fileswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 4. Numberswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 5. Plain Integers ● Plain integers are represented as C long and are in the range [-sys.maxint-1, sys.maxint] ● In Python 2.7.2 on 64-bit Windows 7: – >>> sys.maxint – 2147483647 – >>> -sys.maxint – 1 – -2147483648 ● In Python 2.6.6 on 64-bit Ubuntu 10.10: – >>> sys.maxint – 9223372036854775807 – >>> -sys.maxint -1 – -9223372036854775808www.youtube.com/vkedco www.vkedco.blogspot.com
  • 6. Long Integers ● Long integer literals have L or l at the end ● Long integers have unlimited precision ● To get a long integer, add 1 to sys.maxint >>> import sys >>> sys.maxint + 1 2147483648Lwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 7. IMPORT SYS: Glimpse Forward ● Start the interactive interpreter and type: – >>> print sys.maxint ERROR ● Now type: – >>> import sys – >>> print sys.maxint ● import is similar to C/C++ #includewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 8. Long Integers ● When you use long integers, the only limitation is the size of your memory ● Plain integers convert to long integers automatically after Python 2.2 ● Operations on long integers tend to be slower than on plain integers ● Plain integers and long integers can be mixedwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 9. Hexadecimal Integers ● Hexadecimal is a positional number system with a base of 16 ● Hexadecimal system uses 16 distinct symbols: 0-9, A, B, C, D, E, F ● 0-9 represent themselves ● A, B, C, D, E, F represent 10, 11, 12, 13, 14, 15, respectively 3 2 1 ● 2AF3 = (2 x 16 ) + (10 x 16 ) + (15 x 16 ) + (3 x 160) = 10,995www.youtube.com/vkedco www.vkedco.blogspot.com
  • 10. Hexadecimal Integers ● Primary use of hexadecimal notation is a human-friendly representation of byte-coded values in electronics – >>> hex(10995) – 0x2af3 – >>> 0x2af3 – 10995 ● Hexadecimal notation is used to represent memory address – >>> def f(x): return x + 1 – >>> f – <function f at 0x7f1287bb45f0>www.youtube.com/vkedco www.vkedco.blogspot.com
  • 11. Octal Integers ● Octal is a position number system with a base 8 and uses the digits 0 through 7 2 1 0 ● 112 = 1 x 8 + 1 x 8 + 2 x 8 = 74 ● In Python: – >>> oct(74) 0112 – >>> 0112 74www.youtube.com/vkedco www.vkedco.blogspot.com
  • 12. Floating Point Numbers ● Floats are implemented as the C double ● Python documentation: “All bets on their precision are off unless you happen to know the machine you are working with” ● They have an embedded decimal point (1.0 or 3.14159) or an optional signed exponent preceded by e or E – >>> 1.0e2 – 100.0 – >>> 1.0e-2 – 0.01www.youtube.com/vkedco www.vkedco.blogspot.com
  • 13. Complex Numbers ● Python can represent  −1 ● Complex numbers have the real and imaginary parts, both of which are represented as double ● Appending j or J to a number makes it a complex number with the zero real part – >>> 1j – 1j – >>> 5+4j – (5+4j) – >>> 1.4-3j – (1.3999999999999999-3j)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 14. Complex Numbers ● If z is a complex number, then you can use z.real and z.imag to extract the real and imaginary parts – >>> z = 5 + 4j – >>> z.real – 5.0 – >>> z.imag – 4.0 – >>> y = 5 + 10j – z + y – 10 + 14jwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 15. Numeric Operationswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 16. Numeric Operators ● x + y ### sum of x and y ● x – y ### difference of x and y ● x * y ### product of x and y ● x / y ### quotient of x and y ● x // y ### floored quotient of x and y ● x % y ### remainder (modulus) of x / y ● -x ### negated x ● x ** y ### x to the power of ywww.youtube.com/vkedco www.vkedco.blogspot.com
  • 17. Integer Division ● >>> 10/7 ● 1 ● >>> 10.0/7 ● 1.4285714285714286 ● >>> 10 // 7 ● 1 ● >>> 10.0 // 7 ● 1.0www.youtube.com/vkedco www.vkedco.blogspot.com
  • 18. IMPORT FROM __FUTURE__ ● In Python 3.X, x/y changed to true division ● For example, 3/2 evaluates to 1.5, not to 1 ● You can do this type of division in Python 2.6 and Python 2.7 >>> from __future__ import division >>> 3/2 1.5 ● __future__ (double underscores on both sides) is a module with future enhancements that can be tested in current versionswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 19. Built-in Number Functions ● abs(x) ### absolute value (magnitude) of x ● int(x) ### convert x to plain integer ● long(x) ### convert x to long integer ● float(x) ### convert x to float ● complex(r,i) ### make a complex number with r ### as real and i as imaginary ● c.conjugate() ### conjugate of complex number c ● divmod(x,y) ### pair (x//y, x%y) ● pow(x,y) ### x to the power of ywww.youtube.com/vkedco www.vkedco.blogspot.com
  • 20. Built-in Number Functions ● abs(x) –if x is complex, returns its magnitude ● int(x), long(x), float(x) – x can be string, integer, or float – x cannot be complex ● divmod(x,y) – depricated with complex numberswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 21. User Inputwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 22. User Input ● There are two user input functions in Python: – input([prompt]) – raw_input([prompt]) ● Similarities – Both take an optional prompt – Both read user input ● Differences – input() reads an input string as a Python expression and evaluates it – raw_input() returns the input as a stringwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 23. input() vs. raw_input() >>> x = input("type in value for x: ") type in value for x: 1 >>> x 1 >>> x = raw_input("type in value for x: ") type in value for x: 1 >>> x 1www.youtube.com/vkedco www.vkedco.blogspot.com
  • 24. input() vs. raw_input() >>> x = input("type in value for x: ") type in value for x: 1 + Traceback (most recent call last): File "<pyshell#37>", line 1, in <module> x = input("type in value for x: ") File "<string>", line 1 1 + ^ SyntaxError: unexpected EOF while parsing >>> x = raw_input("type in value for x: ") type in value for x: 1 + >>> x 1 + www.youtube.com/vkedco www.vkedco.blogspot.com
  • 25. User Input: Official Documentation input() “is not safe from user errors! It expects a valid Python expression; if the input is not syntactically valid, a SynaxError will be raised. Other exceptions may be raised if there is an error during evaluation... Consider using raw_input() function for general input from users.” http://docs.python.org/library/functions.html#inputwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 26. User Input Summary ● Be careful of using input() because of its evaluation capability ● Sometimes input() is exactly what you need for expert use ● The raw_input() function is the preferred way of getting input from the user ● Windows tip: raw_input(), when placed on the last line in the file, keeps the window from closing if the script prints text and exitswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 27. Moduleswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 28. Modules ● A module is a .py file that contains Python definitions and statements ● A module can contain executable statements and function definitions ● A module can import other modules ● Convention: put all the import statements at the beginning of a modulewww.youtube.com/vkedco www.vkedco.blogspot.com
  • 29. Modules● For efficiency, each module is imported only once per interpreter session● If you change some modules, restart the interpreter and import them again● If you are debugging a specific module, you can use reload(modulename) in the interpreter www.vkedco.blogspot.com
  • 30. Modules ● There are three ways to import functionalities from modules: – import <module> – from <module> import <name> – from <module> import <name 1>, …, <name n>www.youtube.com/vkedco www.vkedco.blogspot.com
  • 31. IMPORT <MODULE> ● Imports all functions, classes, variables defined in <module> – >>> import math – >>> math.sqrt(2.0) – 1.4142135623730951 – >>> math.pi – 3.141592653589793 – >>> math.sin(math.pi/2)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 32. FROM <MODULE> IMPORT <NAME> ● Imports a specific function, variable, class defined in <module> – >>> def sqrt(x): return 0 – >>> from math import sqrt – >>> sqrt(2.0) – 1.4142135623730951 – >>> math.sqrt(2) – NameError: name math is not defined – >>> from math import pi – >>> pi – 3.141592653589793www.youtube.com/vkedco www.vkedco.blogspot.com
  • 33. FROM <MODULE> IMPORT <NAME 1>, …, <NAME 2> ● Imports specific functions, variables, classes defined in <module> – >>> from math import sqrt, pi – >>> sqrt(pi) – 1.7724538509055159www.youtube.com/vkedco www.vkedco.blogspot.com
  • 34. Math Modules ● Python has two math modules math and cmath that you can import: >>> import math >>> import cmath ● math contains functions for integers and floats (see http://docs.python.org/library/math.html) ● cmath contains functions for complex numbers (see http://docs.python.org/library/cmath.html)www.youtube.com/vkedco www.vkedco.blogspot.com
  • 35. Stringswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 36. Strings ● String literals in Python can be written in double or single quotes: – >>> “Hello, Python!” – >>> Hello, Python! ● One type of quote can be embedded in the other type of quote without escaping: – >>> “Hello, Python!” – >>> Hello, “Python!”www.youtube.com/vkedco www.vkedco.blogspot.com
  • 37. Strings ● If you want to embed the (single or double quote) into the same type of quote, you have to escape – >>> “Hello, ”World!”” – >>> Hello, World! ● Both statements below will result in an error: – >>> “Hello, “World!”” – >>> Hello, World!www.youtube.com/vkedco www.vkedco.blogspot.com
  • 38. String Concatenation ● String literals are automatically contatenated when separated by space: – >>> “hello ” “world” “hello world” – >>> hello world hello world ● String variables are not concatenated: – >>> h = hello – >>> w = world – >>> h w ERRORwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 39. String Concatenation ● If you want to concatenate string variables, use + (it will also work on string literals): – >>> “hello ” + “world” hello world – >>> h = hello – >>> w = world – >>> h + w hello worldwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 40. Strings and Numbers ● Some languages automatically convert other types to strings when they are concatenated with strings ● Python has no such auto-conversion: – >>> x = 15 – >>> "x = " + x TypeError: cannot concatenate str and int objectswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 41. str() and repr() ● There are two built-in string conversion functions ● str([object]) – returns a string containing a printable representation of the object –one can think of the returned string as the users string view of the object ● repr([object]) – returns a string containing a printable representation of the object – one can think of the returned string as Pythons string view of the objectwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 42. str() and repr() ● >>> str(5) 5 ● >>> repr(5) 5 ● >>> str(Hello, Python!) "Hello, Python!" ● >>> repr(Hello, Python!) "Hello, Python!"www.youtube.com/vkedco www.vkedco.blogspot.com
  • 43. Backticks and repr() ● Using backticks around a variable is equivalent to calling repr() – >>> x = 15 – >>> "x = " + repr(x) x = 15 – >>> "x = " + `x` x = 15 – >>> "x = " + `15` x = 15www.youtube.com/vkedco www.vkedco.blogspot.com
  • 44. Multi-line Strings ● Multi-line (long) strings can start and end with three single quote marks (): Disputational knowledge wants customers. It has no soul. Robust and energetic before a responsive crowd, it slumps when no one is there. Jelaluddin Rumi, “The Sheikh Who Played with Children,” Translated by Coleman Barkswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 45. Multi-line Strings ● Multi-line (long) strings start and end with three double quote marks (“): """ Knowledge that is acquired is not like this. Those who love it worry if audiences like it or not. Its a bait for popularity. """ Jelaluddin Rumi, “The Sheikh Who Played with Children,” Translated by Coleman Barkswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 46. Unicode Strings ● To make a string Unicode, prefix the string literal with a u – >>> ustr = uhello ● If you want to reference specific Unicode character, you have to know its hexadecimal number ● You have to be careful: while Python claims to support Unicode, your particular IDE may not support itwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 47. Raw Strings ● If you need to preserve backslashes in your strings, escape them: – >>> path = "C:My Dirtable.txt" ● You can make the string raw, which turns the escape mechanism off: – >>> path = r"C:My Dirtable.txt" ● Raw strings cannot end in : – >>> path = r”C:My DocumentsMy Python Programs” ERROR ● The can be concatenated: – >>> path = r”C:My DocumentsMy Python Programs” + “” – C:My DocumentsMy Python Programswww.youtube.com/vkedco www.vkedco.blogspot.com
  • 48. ASCII to Unicode ● If you have a variable that contains an ASCII string, you can convert it to Unicode with the built-in unicode() function – >>> ascii_str = my string – >>> unicode_str = unicode(ascii_str) – >>> unicode_str – umy string – >>> repr(x) – "my string" – >>> repr(y) – "umy string”www.youtube.com/vkedco www.vkedco.blogspot.com
  • 49. Strings ● Strings are immutable sequences, i.e., they do not support item assignment: – >>> str = rock violin – >>> str[0] r – >>> str[0] = s Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> str[0] = s TypeError: str object does not support item assignmentwww.youtube.com/vkedco www.vkedco.blogspot.com
  • 50. Reading & References ● www.python.org. ● http://en.wikipedia.org/wiki/Hexadecimal ● http://en.wikipedia.org/wiki/Octal ● M. L. Hetland. Beginning Python From Novice to Profession- al, 2nd Ed., APRESS.www.youtube.com/vkedco www.vkedco.blogspot.com