Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

ARDUINO CLUB Session 1: C & An Introduction to Linux.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Variables and I/O. Types Strings –Enclosed in quotation marks –“Hello, World!” Integers –4, 3, 5, 65 Floats –4.5, 0.7 What about “56”?
Introduction to Python
JavaScript, Fourth Edition
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
Guide To UNIX Using Linux Third Edition
Chapter 2: Introduction to C++.
ASP.NET Programming with C# and SQL Server First Edition
JavaScript, Third Edition
Guide To UNIX Using Linux Third Edition
Fundamentals of Python: From First Programs Through Data Structures
Python Programming Fundamentals
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Fundamentals of Python: First Programs
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
2440: 211 Interactive Web Programming Expressions & Operators.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Chapter 2: Using Data.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
VBScript Language. What is VBScript Based on the Visual Basic family of languages Supports object oriented features Interpreted Loosely Typed Implicitly.
Introduction to Programming with RAPTOR
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
I NTRODUCTION TO PYTHON - GETTING STARTED. W HAT IS PYTHON ? An elegant and robust programming language which delivers powerful and general applicable.
Variables, Expressions and Statements
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
By Mr. Muhammad Pervez Akhtar
Controlling Program Flow with Decision Structures.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Python 1 SIGCS 1 Intro to Python March 7, 2012 Presented by Pamela A Moore & Zenia C Bahorski 1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
G. Pullaiah College of Engineering and Technology
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
Chapter 6 JavaScript: Introduction to Scripting
Python Variable Types.
Introduction to Python
Variables, Expressions, and IO
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Arithmetic operations, decisions and looping
Introduction to Python
Chapter 8 JavaScript: Control Statements, Part 2
Lecture 2 Python Programming & Data Types
An Introduction to Python
T. Jumana Abu Shmais – AOU - Riyadh
Lecture 2 Python Programming & Data Types
Python Primer 1: Types and Operators
Chapter 2: Introduction to C++.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Introduction to python-getting started CMPD 124 INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING TECHNIQUES

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 –  PythonWin +Win32 Extensions-  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) Python is 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. fucntion int() 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 Operators-symbolOperators-name +Addition -Subtraction *Multiplication /Division(classic division) %Modulus //For floor division (rounds down to the nearest whole number) **Exponentiation 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 ** Unary +/- % // / * +/_ >>> 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. Operators (symbol) < <= > >= == != <>

example >>> 2 < 4 True >>> 2 == 4 False >>> 2 > 4 False 6.2 <= 6.2 True >>> 6.2 <= True

Conjunction operators Operators and or not 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 >> 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 = # 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) miles is the same as 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 int0101, 84, -247, 0x80,017,-982 long L,DECADEDEBEEF boolTrue, false float3.1412,4.2E-10,-90., complex j, J 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] '!‘ PYTHON 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 " ", line 1, in 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, then the statement if_suite is 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 while expression: 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 [' ','net-surfing','homework','chat']: print item net-surfing homework chat More on if and loops in coming chapter