Josh Cogliati - Non-Programmers Tutorial For Python (779876), страница 2
Текст из файла (страница 2)
exponents **3. multiplication *, division \, and remainder %4. addition + and subtraction -2.4Talking to humans (and other intelligent beings)Often in programming you are doing something complicated and may not in the future remember what you did.When this happens the program should probably be commented. A comment is a note to you and other programmersexplaining what is happening. For example:#Not quite PI, but an incredible simulationprint 22.0/7.0Notice that the comment starts with a #. Comments are used to communicate with others who read the program andyour future self to make clear what is complicated.2.4.
Talking to humans (and other intelligent beings)52.5ExamplesEach chapter (eventually) will contain examples of the programming features introduced in the chapter. You should atleast look over them see if you understand them. If you don’t, you may want to type them in and see what happens.Mess around them, change them and see what happens.Denmark.pyprint "Something’s rotten in the state of Denmark."print "-- Shakespeare"Output:Something’s rotten in the state of Denmark.-- ShakespeareSchool.py#This# andprintprintprintprintprintprintprintprintprintprintprintprintprintprintprintprintprintis not quite true outside of USAis based on my dim memories of my younger years"Firstish Grade""1+1 =",1+1"2+4 =",2+4"5-2 =",5-2"Thirdish Grade""243-23 =",243-23"12*4 =",12*4"12/3 =",12/3"13/3 =",13/3," R ",13%3"Junior High""123.56-62.12 =",123.56-62.12"(4+3)*2 =",(4+3)*2"4+3*2 =",4+3*2"3**2 =",3**2Output:6Chapter 2.
Hello, WorldFirstish Grade1+1 = 22+4 = 65-2 = 3Thirdish Grade243-23 = 22012*4 = 4812/3 = 413/3 = 4 R 1Junior High123.56-62.12 = 61.44(4+3)*2 = 144+3*2 = 103**2 = 92.6ExercisesWrite a program that prints your full name and your birthday as separate strings.Write a program that shows the use of all 6 math functions.2.6.
Exercises78CHAPTERTHREEWho Goes There?3.1Input and VariablesNow I feel it is time for a really complicated program. Here it is:print "Halt!"s = raw_input("Who Goes there? ")print "You may pass,", sWhen I ran it here is what my screen showed:Halt!Who Goes there? JoshYou may pass, JoshOf course when you run the program your screen will look different because of the raw_input statement. Whenyou ran the program you probably noticed (you did run the program, right?) how you had to type in your name andthen press Enter. Then the program printed out some more text and also your name. This is an example of input.
Theprogram reaches a certain point and then waits for the user to input some data that the program can use later.Of course, getting information from the user would be useless if we didn’t have anywhere to put that information andthis is where variables come in. In the previous program s is a variable. Variables are like a box that can store somepiece of data. Here is a program to show examples of variables:a = 123.4b23 = ’Spam’first_name = "Bill"b = 432c = a + bprint "a + b is", cprint "first_name is", first_nameprint "Sorted Parts, After Midnight or",b23And here is the output:a + b is 555.4first_name is BillSorted Parts, After Midnight or Spam9Variables store data.
The variables in the above program are a, b23, first_name, b, and c. The two basic typesare strings and numbers. Strings are a sequence of letters, numbers and other characters. In this example b23 andfirst_name are variables that are storing strings. Spam, Bill, a + b is, and first_name is are the stringsin this program. The characters are surrounded by " or ’.
The other type of variables are numbers.Okay, so we have these boxes called variables and also data that can go into the variable. The computer will see a linelike first_name = "Bill" and it reads it as Put the string Bill into the box (or variable) first_name. Lateron it sees the statement c = a + b and it reads it as Put a + b or 123.4 + 432 or 555.4 into c.Here is another example of variable usage:a = 1printa = aprinta = aprinta+ 1a* 2aAnd of course here is the output:124Even if it is the same variable on both sides the computer still reads it as: First find out the data to store and than findout where the data goes.One more program before I end this chapter:num =str =printprintprintprintprintprintinput("Type in a Number: ")raw_input("Type in a String: ")"num =", num"num is a ",type(num)"num * 2 =",num*2"str =", str"str is a ",type(str)"str * 2 =",str*2The output I got was:Type in a Number: 12.34Type in a String: Hellonum = 12.34num is a <type ’float’>num * 2 = 24.68str = Hellostr is a <type ’string’>str * 2 = HelloHelloNotice that num was gotten with input while str was gotten with raw_input.
raw_input returns a stringwhile input returns a number. When you want the user to type in a number use input but if you want the user totype in a string use raw_input.The second half of the program uses type which tells what a variable is. Numbers are of type int or float (which10Chapter 3. Who Goes There?are short for ’integer’ and ’floating point’ respectively). Strings are of type string. Integers and floats can beworked on by mathematical functions, strings cannot. Notice how when python multiples a number by a integer theexpected thing happens.
However when a string is multiplied by a integer the string has that many copies of it addedi.e. str * 2 = HelloHello.The operations with strings do slightly different things than operations with numbers. Here are some interative modeexamples to show that some more.>>> "This"+" "+"is"+" joined."’This is joined.’>>> "Ha, "*5’Ha, Ha, Ha, Ha, Ha, ’>>> "Ha, "*5+"ha!"’Ha, Ha, Ha, Ha, Ha, ha!’>>>Here is the list of some string operations:OperationRepetitionConcatenation3.2Symbol*+Example"i"*5 == "iiiii""Hello, "+"World!" == "Hello, World!"ExamplesRate times.py#This programs calculates rate and distance problemsprint "Input a rate and a distance"rate = input("Rate:")distance = input("Distance:")print "Time:",distance/rateSample runs:> python rate_times.pyInput a rate and a distanceRate:5Distance:10Time: 2> python rate_times.pyInput a rate and a distanceRate:3.52Distance:45.6Time: 12.9545454545Area.py3.2.
Examples11#This program calculates the perimeter and area of a rectangleprint "Calculate information about a rectangle"length = input("Length:")width = input("Width:")print "Area",length*widthprint "Perimeter",2*length+2*widthSample runs:> python area.pyCalculate information about a rectangleLength:4Width:3Area 12Perimeter 14> python area.pyCalculate information about a rectangleLength:2.53Width:5.2Area 13.156Perimeter 15.46temperature.py#Converts Fahrenheit to Celsiustemp = input("Farenheit temperature:")print (temp-32.0)*5.0/9.0Sample runs:> python temperature.pyFarenheit temperature:320.0> python temperature.pyFarenheit temperature:-40-40.0> python temperature.pyFarenheit temperature:212100.0> python temperature.pyFarenheit temperature:98.637.03.3ExercisesWrite a program that gets 2 string variables and 2 integer variables from the user, concatenates (joins them togetherwith no spaces) and displays the strings, then multiplies the two numbers on a new line.12Chapter 3.
Who Goes There?CHAPTERFOURCount to 104.1While loopsPresenting our first control structure. Ordinarily the computer starts with the first line and then goes down from there.Control structures change the order that statements are executed or decide if a certain statement will be run. Here’s thesource for a program that uses the while control structure:a = 0while a < 10:a = a + 1print aAnd here is the extremely exciting output:12345678910(And you thought it couldn’t get any worse after turning your computer into a five dollar calculator?) So what doesthe program do? First it sees the line a = 0 and makes a zero.
Then it sees while a < 10: and so the computerchecks to see if a < 10. The first time the computer sees this statement a is zero so it is less than 10. In other wordswhile a is less than ten the computer will run the tabbed in statements.Here is another example of the use of while:13a = 1s = 0print ’Enter Numbers to add to the sum.’print ’Enter 0 to quit.’while a != 0 :print ’Current Sum:’,sa = input(’Number? ’)s = s + aprint ’Total Sum =’,sThe first time I ran this program Python printed out:File "sum.py", line 3while a != 0ˆSyntaxError: invalid syntaxI had forgotten to put the : after the while.
The error message complained about that problem and pointed out whereit thought the problem was with the ˆ . After the problem was fixed here was what I did with the program:Enter Numbers to add to the sum.Enter 0 to quit.Current Sum: 0Number? 200Current Sum: 200Number? -15.25Current Sum: 184.75Number? -151.85Current Sum: 32.9Number? 10.00Current Sum: 42.9Number? 0Total Sum = 42.9Notice how print ’Total Sum =’,s is only run at the end. The while statement only affects the line that aretabbed in (a.k.a. indented). The != means does not equal so while a != 0 : means until a is zero run the tabbedin statements that are afterwards.Now that we have while loops, it is possible to have programs that run forever.