a high-level language that translate a set of instructions into! )!<24<=.'8'.!.)$4#)4'!,<),!,&)$*.),'!)!*',!->!2$*,&#?,2-$*!2$,-!5)?<2$'!



Similar documents
Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

PYTHON Basics

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

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

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Installing Java. Table of contents

Introduction to Python

Chapter 2 Writing Simple Programs

Exercise 4 Learning Python language fundamentals

Lecture 2 Mathcad Basics

Introduction to. Marty Stepp University of Washington

Chapter 8 Selection 8-1

Installing C++ compiler for CSc212 Data Structures

CS 100 Introduction to Computer Science Lab 1 - Playing with Python Due September 21/23, 11:55 PM

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

CS101 Lecture 24: Thinking in Python: Input and Output Variables and Arithmetic. Aaron Stevens 28 March Overview/Questions

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

PHP Tutorial From beginner to master

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

Python Basics. S.R. Doty. August 27, Preliminaries What is Python? Installation and documentation... 4

Python Lists and Loops

Using and the Internet

Manual for Configuring Cisco Any Connect Secure Mobility Client in Linux Red Hat

Lab 1: Introduction to C, ASCII ART and the Linux Command Line Environment

Computer Programming In QBasic

Objectives. Python Programming: An Introduction to Computer Science. Lab 01. What we ll learn in this class

Web Editing Tutorial. Copyright Esri All rights reserved.

Practice Fusion API Client Installation Guide for Windows

Create a New Database in Access 2010

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

Informatica e Sistemi in Tempo Reale

Hypercosm. Studio.

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Building and Using Web Services With JDeveloper 11g

Advanced Programming with LEGO NXT MindStorms

Chapter 1: Getting Started

Topic 11 Scanner object, conditional execution

VHDL Test Bench Tutorial

Introduction to Eclipse

Getting Started using the SQuirreL SQL Client

How to test and debug an ASP.NET application

How To Install Amyshelf On Windows 2000 Or Later

Grandstream XML Application Guide Three XML Applications

How to install and use the File Sharing Outlook Plugin

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Information Technology. Introduction to Vista

Lecture 4: Writing shell scripts

CLC Server Command Line Tools USER MANUAL

Chapter 2: Software Development in Python

Python Programming: An Introduction to Computer Science

12Planet Chat end-user manual

Introduction to Python

Installing the Android SDK

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

GE Intelligent Platforms. Activating Licenses Online Using a Local License Server

CS10110 Introduction to personal computer equipment

User Guide For ipodder on Windows systems

JMM Software Suite

Table of Contents. Installing V-Ray for SketchUp..2. Setting Up Additional Users with a Floating License Server.19. Additional Information...

Python Programming: An Introduction to Computer Science

>print "hello" [a command in the Python programming language]

Building a Python Plugin

Setting Up ALERE with Client/Server Data

Computer Science 217

F ahrenheit = 9 Celsius + 32

INTEGRATING MICROSOFT DYNAMICS CRM WITH SIMEGO DS3

A Sample OFBiz application implementing remote access via RMI and SOAP Table of contents

CHAPTER 14 Understanding an App s Architecture

Python for Series 60 Platform

NLP Programming Tutorial 0 - Programming Basics

v4: How to create a BartPE Rescue CD for Macrium Reflect

Chapter 28: Expanding Web Studio

edgebooks Quick Start Guide 4

Click the "Connect" button. You should now see the following screen:

Upgrading from Windows XP to Windows 7

For Introduction to Java Programming, 5E By Y. Daniel Liang

Java Web Start Guide

Kentico CMS 7.0 User s Guide. User s Guide. Kentico CMS

Java Basics: Data Types, Variables, and Loops

Figure 1: Graphical example of a mergesort 1.

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

Chapter 2 Introduction to Java programming

Cascaded Lookup 5.0 User Guide

Novell ZENworks Asset Management 7.5

Audio Web Conferencing Elluminate Live and Skype Guidelines for Use

Introduction to Python

Sample CSE8A midterm Multiple Choice (circle one)

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

Android Environment SDK

TIBCO Spotfire Automation Services 6.5. User s Manual

CS Unix Tools & Scripting Lecture 9 Shell Scripting

Getting Started with Citrix Remote Connectivity Service

Right now, the latest and greatest version of Java available for download is Start with this link to find out more about it

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Advanced Digital Imaging

Tutorial - How to Use Lotus Domino Web Services in Java Development

RECOMMENDED JAVA SETTINGS

wce Outlook Contact Manager Documentation

Transcription:

Python!"#$%&!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"#$%!"&''%!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!()*+!,-!.')&$/!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&')0!)$0!1&2,'% Introduction '&#(%)*+#,%& a programming language like Java and C++.! )!3&-4&)552$4!.)$4#)4'!.26'!7)8)!)$0!9::; a high-level language that translate a set of instructions into! )!<24<=.'8'.!.)$4#)4'!,<),!,&)$*.),'!)!*',!->!2$*,&#?,2-$*!2$,-!5)?<2$'! machine language, which is represented by 0s and 1s..)$4#)4'/!1<2?<!2*!&'3&'*'$,'0!@+!A*!)$0!B*;! Getting Python -.##,&/0!"#$%& At home: You want to download the latest version, which is 2.5.2. 1#0$%2.3 Go to http://www.python.org/download/ C-#!1)$,!,-!0-1$.-)0!,<'!.),'*,!8'&*2-$/!1<2?<!2*!D;E;D; Assuming you are using Windows, after you have installed it, go to F-!,-!<,,3GHH111;3+,<-$;-&4H0-1$.-)0H Start > All > Programs > Python > IDLE. I**#52$4!+-#!)&'!#*2$4!J2$0-1*/!)>,'&!+-#!<)8'!2$*,)..'0!2,/!4-!,-!K,)&,!L!I..! In the lab: M&-4&)5*!L!M+,<-$!L!NOP(; Go to Start > All Programs > Python 2.5 > IDLE. '&0#$.04563 F-!,-!K,)&,!L!I..!M&-4&)5*!L!M+,<-$!D;E!L!NOP(; 1

Now try this out! In the window that appears, you should see the python prompt >>>. This is asking you to enter python commands. Type in the following to see what happens. To display or output: >>> print "Hello World" >>> print 'Hello World' >>> print Hello World Q1: Why is there an error? To do arithmetics (use Python as a calculator): >>> print 25+38 >>> print 3*6 >>> print 3/6 >>> print 3.0/6.0 Q2: Why does 3/6=0? >>> print 2+4*2 Q3: Why is the value above 10 but not 12? >>> print 2**2 >>> print 2**3 To connect or link 2 or more words: >>> print 'abc'+'def' >>> print 'joe'+' '+'smith' >>> print '25'+'58' To know what type a value is: >>> type(21) >>> type( Hello World ) >>> type('hello Word') 2

>>> type(2.5) >>> type( 15 ) >>> type( 2.5 ) To link to another piece of data (variables): >>> words = "Hello World!" >>> print words >>> firstname = 'joe' >>> lastname = 'smith' >>> print firstname + lastname >>> print %s is my name. % ("Jane ) >>> print %d is my favorite number. % (7) >>> print "%s is number %d! " % ("Python", 1) >>> x=2 >>> print x+5 >>> print x-0 >>> print x*7 >>> print 'x'*7 Q4: Explain why. >>> print x/2 >>> y=3 >>> print x+y >>> print x-y >>> print x*y >>> print x/y To obtain user input from command-line: >>> result = raw_input() (Python will wait for you (the end-user) to enter something. Enter some text and hit Enter.) 3

>>> print result >>> x = raw_input('please enter a string: ') >>> print x >>> name = raw_input("enter your name here: ") >>> age = raw_input("enter your age here: ") >>> print "Your name is:", name >>> print "And you are", age To combine variables, expressions and statements: >>> print The distance from my house to my school is, 10, miles. >>> minute = 5 >>> print minute, minute is equals to, minute*60, seconds. 4

More challenges! Looping The art of repeating itself You can use loops when you want to repeat a set of instruction multiple times. while loop pseudocode: while (expression): else: # statements to execute while loop expression is True # statements to execute when loop expression is False >>> i = 0 >>> while(i < 10): i = i + 1 print i >>> x = 10 >>> while (x > 0): x = x - 1 print x >>> x = 10 >>> while (x!= 0): print x x = x - 1 print "wow, we've counted x down, and now it equals", x 5

for loop pseudocode for item in container: # action to repeat for each item in the container else: # action to take once we have finished the loop. >>> for i in range(1,11): print i >>> for i in range(1,1000): print i >>> for x in 'summer': print x >>> for word in ('one','word', 'after', 'another'): print word 6

The if statement Execute a block of statements depending on some condition. if statement pseudocode if(expression one): # Action to take if expression one evaluates True else: # Action to take if all expression one evaluates False >>> i = 8 >>> if(i % 2): print "Odd Number" else: print "Even Number" >>> z = 4 >>> if (z > 70): print "Something is very wrong" elif (z < 7): print "This is normal" >>> i = -8 >>> if(i > 0): print "Positive Integer" elif(i < 0): print "Negative Integer" 7

else: print "Zero" Combo while loop and if statement >>> a = 10 >>> while a > 0: print a if (a > 5): print "Big number!" elif ((a % 2)!= 0): print "This is an odd number" print "It isn't greater than five, either" else: print "this number isn't greater than 5" print "nor is it odd" print "feeling special?" a = a - 1 print "we just made 'a' one less than what it was!" print "and unless a is not greater than 0, we'll do the loop again." 8

List of Elements To add elements to a list >>> list = [] # gives an empty list you can add elements to >>> list.append( a ) >>> print list you can also initialize the elements of a list and access each element >>> list2 = [ a, b, c ] >>> print list2[0] # in computer science we count from 0 >>> print list2[2] # list2[2] is the 3 rd element not the 2 nd >>> print list2[3] Q5: Explain why there is an error? getting the length of a list or the number of elements >>> print len(list2) to print the elements of a list using a while loop: >>> list3 = [ sarah, bob, joe ] >>> i = 0 >>> while i < len(list3) print list[i] i = i + 1 Questions 1. Create the list [0,1,2,3,4,5,6,7,8,9] without using append. 2. Create the same list starting with an empty list and using a loop. 3. Make one change to your code from number 2 to create the list [0,2,4,6,8]. 4. Write a loop that creates the list [1,3,5,7,9] using an if statement. 9

Writing a Program in a File By writing a program in a file, we can run our code all at once. 1. To do so, open any text editor and enter the following four lines in a file named 'hello.py'. Put the lines on the left-margin-- no tabs or spaces. print "hello" print "world" name = "jive" print name 2. Save the file as hello.py 3. At the terminal window, enter: python hello.py Note that you should enter the above at the operating system prompt, not the Python prompt. If you're still within the Python interpreter, exit with control-d. Executing the above should result in the following being printed: hello world jive Challenge Questions 1. Write an if statement that translates scores to grades. You can follow the guide below: A: 90-100 B: 80 90 C: 70 80 D: 60 70 E: 0 60 10

2. Write a for loop to produce the following output: * ** *** **** ***** 3. Write a while loop to produce the following output: ***** **** *** ** * 4. Write a program (in a file temp.py ) that converts Celsius to Fahrenheit: Sample: Enter a temperature in Celcius: 20 20 C = 68 F Steps: 1. Ask for input from the user 2. Compute the temperature in Fahrenheit: F = (9/5)*C+32 3. Print the result in the form: _ C = _ F (Use what you know about dividing integers and floating point numbers to compute the correct temperature) 5. Modify your program to convert Fahrenheit to Celsius as well: Sample: Steps: Enter a temperature: 68 Convert to (F)ahrenheit or (C)elsius: C 68 F = 20 C 1. Ask for input from user 2. Use an if-else statement to do the correct conversion: 11

For example: if (input == a ) do something else do something else 3. Compute the temperature in Fahrenheit or Celsius: F = (9/5)*C+32 C = (5/9)*(F-32) 4. Print the Result 12

Media Programming Introduction JES is a development environment for Python. If you don't have JES on your computer, you can download it at http://coweb.cc.gatech.edu/mediacomp-plan/94. If you're working in a USF CS lab, JES is already installed. On Linux, you can find it in Applications > Programming > JES. On Windows, look for the frog in 'All Programs'. JES has two main windows. The bottom panel is an interactive interpreter. This allows you to try a single command at a time. Usually you'll use the top window, which is a text editor. You write the program there, then click 'Load program' to run it. Tutorial 1. With JES you work with pictures. So the first step is to download an image from the web into your H: directory. With most browsers, you can right-click an image and choose "Save Images as" or something similar. 2. Open the JES programming environment and type in the following mini-program into the top panel editor. a. Ask the end-user to choose a graphic file b. Create a picture in memory holding the pixels of the image c. Show the picture filename = pickafile() pic = makepicture(filename) show(pic) Enter the lines exactly as shown above, then click File > Save Program. Save in imagesample.py. 3. Run your program by clicking the "Load Program" near the middle of the JES Window. You (the end-user) will be prompted to choose a.jpg or other graphic file. Choose an image from one of your folders, and the program should render the picture. That is all this first program does. 13

4. Now we'll modify your program and have it change the image, just as a human might do in Photoshop. For now, let's just draw some text and a line on our picture. Add the following below the previous code in your sample.py file: a. Draw a line going from coordinate (0,0) to (200,200) b. Draw some text at coordinate (100,100) c. Repaint the picture with the changes addline(pic,0,0,200,200) addtext(pic,100,100,"hey dude ) repaint(pic) Do you see the line on the picture? Try different numbers and text for the parameters. What happens? 5. Note that the manipulations take place on an in-memory (RAM) version of the image. You can save the modified image to a file: writepictureto(pic,'/home/wolber/pics/out.jpg') If you're using Windows, you need to put an 'r' in front of the file path. For instance: writepictureto(pic,r"h:\out.jpg") Add the appropriate line to the bottom of your program, rerun your program, then go into the folder you specified and see if the new file has been created and if the image inside it is the modified picture. 6. Play around with some of the Photoshop-like functions that JES provides. To view a list of the functions, select Help! Understanding Pictures > Picture Functions in JES. This specification describes the functions you can call. 14

Calling Functions: Parameters and Return Values A function does some work for us. We can send a function some data, and it will perform some task and send us something back. Consider the function sqrt. A program can send it a number and get something back: result = sqrt(16) When you call a function, you sometimes send it some data that it needs to do its job. We call such data a parameter. 16 is the parameter sent to sqrt in the sample above. Parameters are placed in parenthesis after the function name. Sometimes functions return you some data when they complete. We call such data a return value. We say that the calling function catches the return value. In the sample above, the return value is caught by the variable result. Some functions are built-in to the Python language. sqrt is one example. Other functions are just sub-programs written by some programmer-- named pieces of code that you can call. Anyone can write such functions using the 'def' statement. For example, I could create a function cube: def cube(x): return x*x*x and then call it: result = cube(3) In the JES Media Introduction tutorial, you called some functions: filename = pickafile() pic = makepicture(filename) show(pic) addline(pic,0,0,200,200) addtext(pic,100,100,"hey dude") repaint(pic) 15

The makepicture function has one parameter, filename. You tell makepicture a filename, and it loads a picture for you (in memory). That picture is returned to your program and 'caught' in the variable pic. In-Class Worksheet 1. What are the parameters of the other JES function calls above? Which need to catch a return value? 2. The JES Help provides a list of function definitions, also known as an application programmer interface (API). Open JES and find the definition for the function addline. What are the names for the five parameters it expects sent to it? How would you call it to draw a vertical line all the way down the middle of a picture? 16

Using Python to Send Email #Sample program 1 import smtplib name = "Sami Rollins" sender = "srollins@cs.usfca.edu" recipient = "srollins@gmail.com" session = smtplib.smtp("nexus") msg = "To: " + name + " <" + recipient + ">\n" + "This is a test message." try: smtpresult = session.sendmail(sender, recipient, msg) except: print "failure" #Sample program 2 import webbrowser webbrowser.open("http://www.google.com") print "done..." Exercises 1. Write a program to prompt the user for a word and print "You entered: " followed by the word that the user entered. 2. Write a program to prompt the user for a URL (using raw_input) and launch a browser window displaying that URL. 3. Write a program to prompt the user for a name, sender email address, and receiver email address and send an email message to the specified address. 17