360 likes | 635 Views
Introduction to python-getting started. What is python?. An elegant and robust programming language which delivers powerful and general applicable traditional compiled languages with the used of simpler scripting and interpreted languages. Running python: 3 ways
E N D
What is python? • An elegant and robust programming language which delivers powerful and general applicable traditional compiled languages with the used of simpler scripting and interpreted languages. • Running python: • 3 ways • Starting the interpreter interactively , entering one line of Python at a time for execution • Running a script written in Python – this is done by invoking the interpreter on your script application • Run from graphical user interface (GUI) from within an integrated development environment (IDE/IDLE)
Interactive interpreter from the command line • Python can be start coded using an interactive interpreter by starting it from the command line. • This can be done from Unix, DOS etc. • Unix • At the Unix prompt (% or $), the interpreter can be started by invoking the name python (jpython), as in the following $python • Once Python started, the interpreter startup message will indicate the version and platform and be given the interpreter prompt “>>>” to enter Python commands.
Continue.. • Windows/DOS • From a DOS window (either DOS /Windows), the command to start python is same as Unix, the difference is that the prompt is c:\>python • Command-Line Options • Additional options may be provided to the interpreter such as listed below: • -d provide debug output • -o generate optimized bytecode resulting in .pyo files • file Run Python script from given file • - c cmd Run Python script sent in as cmd string • Etc…
As a Script from the Command Line • Unix- a Python script can be executed by invoking the interpreter from the command line as in the following • $ python script.py • Same as Unix
An integrated development environment (IDE) • Need GUI application on your system that supports Python. • Have graphical user interface (GUI), source code editor , trace and debugging facilities. • IDLE is the first Unix IDE for Python. • PythonWin is the first Windows interface for Python and is an IDE with a GUI. • Usually installed in the same directory as Python. • PythonWin features a color editor, a new and improved debugger, interactive shell window, COM (component object extensions and more.
Continue.. • Python extension is .py • IDLE –also available on the Windows platform • In windows, it look similar to Unix • From Windows, IDLE can be found in the Lib\idlelib subdirectory, where Python interpreter is found, c:\Python2x. • To start IDLE from a DOS command window, invoke idle.py • To start IDLE from a Windows environment, just double click on idle.pyw.
Continue.. • Files ending with .pyw will not open a DOS command window to run the script on it instead it is created a shortcut to c:\Python2x\Lib\idlelib\idle.pyw • Other IDEs and execution environment • Open source • IDLE –http://python.org/idle/ • PythonWin +Win32 Extensions-http://startship.python.net/crew/skippy/win32 • Etc……
Writing a simple python program • Prompt in Python “>>>” primary prompt “…” secondary prompt • Primary prompt – interpreter is expecting the next python statement • Secondary prompt – interpreter is waiting for additional input to complete the current statement. • There are two primary ways that Python “does things”: 1. statements 2: expression – functions, equations, etc • A statement is a body of control which involved using keywords.
Continue.. • Statements may/may not lead to a result or output. • Example use print statement to print Hello World >>> print ‘Hello World!’ Output – Hello world • Expressions – do not use keywords. • Example of equations- simple equations that comes together with mathematical operators, can be a functions which are called with parentheses. • They may/may not take input, and they may/may not return a meaningful value.
Program Output, the print statement, and “Hello World!” >>> myString = ‘Hello World!’ >>> print myString Hello World! >>> myString ‘Hello World!’ • In this example, use a string variable, then use print to display its contents. • Given only the name reveals quotation marks around the string. • Why? This is to allow objects other than strings to be displayed in the same manner as this string. • Means that using the name of the variable, you can print/display a printable string representations of any object not just strings.
Continue.. • Python’s print statement, paired with the string format (%), supports string substitution similar to printf() function in C. >>> print “%s is number %d!” % (“python”,1) Pythonis number 1 • %s means to substitute a string while %d indicates an integer should be substituted. • %f is for floating point numbers. • The print statement also allows its output directed to a file. (will look into this matter later)
Continue.. Program input and the raw_input() built-in function. • raw_input – to get user input from the command line. • read from standard input and assigns the string value to the variable you designate. • fucntionint() can be use to convert any numeric input string to an integer representation.
example >>> user=raw_input(‘Enter login name: ‘) Enter login name: root >>> print ‘Your login is :’, user Your login is: root • This example is using text input
Example 2- a numeric string input >>> num=raw_input (‘Now enter a number:’) Now enter a number:1024 >>> print ‘Doubling your number: %d’ %(intnum)*2) Doubling your number :2048 • The int () function converts the string num to an integer so that the mathematical operation can be performed.
comments • Used the symbol (#) (hash or pound ) to indicate comments. • It begin with (#) and continue until the end of line. >>># one comment print ‘Hello world!’ # another comment Hello World! • Special comments called documentation strings or “doc strings” • Unlike regular comments, doc strings can be accessed at runtime and used to automatically generate documentation.
Operators-standard mathematical An operation that raises some given constant (base) to the power of other number (exponent).
Continue.. • Classic division means that if the operands are both integers, it will perform floor division • For floating numbers, it represents true division. • If true division is enabled, then the division operator will always perform that operator, regardless of operand type. • More on this later.
Operator precedence >>> print -2*4 +3**2 1 In this example, 3**2 is calculated first followed by (-2*4).
Standard comparison operators • This operators return a Boolean value indicating the truthfulness of the expression.
example >>> 2 < 4 True >>> 2 == 4 False >>> 2 > 4 False 6.2 <= 6.2 True >>> 6.2 <= 6.20001 True
Conjunction operators • can use these operations to chain together arbitrary expressions and logically combine the Boolean results: • >>> 2 < 4 and 2 == 4 • False • >>> 2 > 4 or 2 < 4 • True • >>> not 6.2 <= 6 • True • >>> 3 < 4 < 5 • True • >>> 3 < 4 < 5 is a short way of saying >>> 3<4 and 4<5
Variables and assignments • Variables in Python is similar to other high level languages. • Variables are simply identifier names with an alphabetic first character , upper or lowercase letters including the underscore (_). • Other alphanumeric or underscore. • Python is case sensitive means that “CASE” is not same as “case”. • Python is dynamically typed means that no pre-declaration of a variable or its type is necessary. • The type (and value) are initialized on assignment. • Assignments are performed using the equal sign.
example >>> counter =0 # the integer >>> miles =1000.0 # the floating point >>> name =‘Bob’ # string >>> counter = counter +1 #an incremental statement for integer >>>kilometers = 1.609*miles #floating point operation and assignment >>> print “%f miles is the same as %f km’ %(miles,kilometers) 1000.000000 miles is the same as 1.609.000000 km In this example, there are 5 variable assignments.
Continue.. • Python also supports augmented assignments – statement that both refer to and assign values to variables. Example n =n *10 shortcut n *= 10 • Python does not support increment/decrement operators like in C : n++ /--n. Because +, -- are also unary operators, Python will interpret --n as -(-n) == n and the same is true for ++n.
numbers • Python support 5 basic numerical types Boolean values are a special case of integer. If put in a numeric context such as addition with other numbers, true is treated as the integer with value 1 and false as value 0. Complex number , number that involve the square root of -1, so called “imaginary” numbers. More on numbers in later chapter
Strings • String in Python are identified as a contiguous set of characters in between quotation marks. • Python allows 8 pairs of single /double quotes. • Triple quotes (three consecutive single/double quotes) can be used to escape special characters. • Subsets of strings can be taken using the index ([ ] ) and slice ([ : ]) operators, which works with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. • The plus (+) sign is the string concatenation operator, and the asterisk (*) is the repetition operator.
example >>> pystr = ’PYTHON’ >>> iscool = ‘is cool!’ >>> pystr[0] ‘P’ >>> pystr[2:5] ‘tho’ # the output start at 2 up to 4 not include the character at end. >>> iscool[:2] 'is‘ >>> pystr + iscool ‘PYTHON is cool!' >>> pystr*2 ‘PYTHONPYTHON' >>> iscool[-1] '!‘ Counting forward Counting backward More on string in coming chapter
Lists and tuples • Lists and tuples can be though of as generic “ arrays” with which to hold an arbitrary number of arbitrary Python objects • The items are ordered and accessed via index offsets, similar to array except that lists and tuples can store different types of objects. • Lists are enclosed in brackets ([ ]) and their elements and size can be changed. • Tuples are enclosed in parentheses (()) and cannot be updated. • Tuples can be thought of for now as “read-only” lists. • Subsets can be taken with the slice operator ([] and [ : ] in the same manner as string.
examples >>> alist =[1,2,3,4] >>> alist [1, 2, 3, 4] >>> alist[0] 1 >>> alist[2:] [3, 4] >>> alist[:3] [1, 2, 3] >>> alist[1]=5 >>> alist [1, 5, 3, 4]
examples >>> atuple=('robots',77,93,'try') >>> atuple ('robots', 77, 93, 'try') >>> atuple[:3] ('robots', 77, 93) >>> atuple[1]=5 # not allowed to change the element in tuple Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> atuple[1]=5 TypeError: 'tuple' object does not support item assignment
Code blocks • Code blocks are identified by indentation rather than using symbols like {} • Indentation clearly identifies which block of code a statement belongs to. if statement if expression : if _suite • If the expression is non-zero or true, thenthe statementif_suiteis executed, otherwise execution continues on the first statement after. • Suite is the term used in python to refer to a sub-block of code and can consists of single or multiple statements. Example: >>> if x < .0: print '"x must be at least 10!'
Continue.. • Python also support an else statement that is used with if : if expression: if_suite else: else_suite • Python has an “else-if” spelled as elif : if expression1: if_suite elseif expression2: elif_suite else: else_suite
While loop whileexpression: while_suite • The statement while_suite is executed continuously in a loop until the expression becomes zero or false. • Execution then continues on the first succeeding statement. counter =0 while counter <3: print 'loop #%d'% (counter) counter +=1 loop #0 loop #1 loop #2
For loop • Python’s for takes an iterable (such as sequence or iterator) and traverses each element once. >>> print 'i like to use the internet for:' i like to use the internet for: >>> for item in ['e-mail','net-surfing','homework','chat']: print item e-mail net-surfing homework chat • More on if and loops in coming chapter