Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
86 views
Ch. 1-6 Heatcote Python Programming
Uploaded by
naustyaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Ch. 1-6 Heatcote Python Programming For Later
Download
Save
Save Ch. 1-6 Heatcote Python Programming For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
86 views
Ch. 1-6 Heatcote Python Programming
Uploaded by
naustyaki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Ch. 1-6 Heatcote Python Programming For Later
Carousel Previous
Carousel Next
Save
Save Ch. 1-6 Heatcote Python Programming For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 39
Search
Fullscreen
Chapter 1 Data types, operators and I-O Objectives * Run commands in interactive mode * Use string, numeric and Boolean data types and operators * Learn the rules and guidelines for naming variables * Use input and output statements: Programming in Python Python is a popular, easy-to-learn programming language. A Python program is simply a series of instructions written according to the rules or syntax of the language, usually designed to perform some task or come up with a solution to a problem. You write the instructions, and then the computer translates these instructions into binary machine cods which the computer can execute, It will do this using a translator program, Whiah could be either a compiler or an interpreter. Python uses elements of both an interpreter and a compiler. Python comes with an integrated development environment called IDLE which enables you to enter your program, save it, edit it, translate it to machine cade and run It once it is free of syntax errors. If you have written a statement wrongly, that will be reported by the interpreter as a syntax error, and you ean correct it and try again. Programming in interactive mode Python has two modes of entering and running programs. In interactive mode, you can type instructions and Python will respond immediately. This is very useful for trying out statements that you are not sure about, and is a good place to start. However, you cannot save a program that you have written in interactive mode. This has to be done in script mode, described in the next chapter.LEARNING TO PROGRAM IN PYTHON ‘To begin an interactive session, from the Start menu choose Python 3.x /IDLE. You will see a screen similar to the one below: eg 3 File_fot_Shell_Bebug Options Window Help Hee nen t AETS263e11, Dec 23 2016, S7:iB:10) [SC wad tel)) on winsz i Neopyright", “credics" or "license()" for moze information. Python IDLE (interactive winciow) In this window, which is called the Python Shell window. you can type commands at the prompt, >>>, >>> ("Hello Worle") The Python interpreter responds to your command and you will see Hello World appear on the next line, followed by a new line with the prompt. Data types String data type In the above command, "Hello World" is a data type known as a string. A string is simply one or more characters enclosed in quote marks, and it doesn't matter whether you use single or double quotes. If your string contains speech or a quotation, you can use whichever type of quote mark you did not use to enclose the whole string: Do> print ("He said tHello!'*) He said ‘We The symbol + is used to concatenate, or join together, two or more strings. >>> "John" +" " + "RiadeLI® "John Riddel1" Note that numbers enclosed in quotes, or input as strings, behave as strings, not numbers. Se Py Numeric data types and Operators ‘A number can be either integer (a whole number) or floating point, (a number with a decimal point) referred to in Python as int and float respectively,The standard arithmetic operators used by Python are +, -, * (multiply), / for exponentiation (e.g. 8 = 2° or 2 ** 3), The normal rules of precedence hold, and you can use parentheses to force the order of calculation. Two other useful operators are % and //. % (mod in some programming languages) returns the remainder when one integer is divided by another, and // (div in some languages) performs integer division, Giscarding any remainder without rounding, So 19 % 5 = 4 and 19// 5 =3. Note that the result of dividing two numbers, whether they are integer or floating point, always results in a floating point answer. pop 445*2 13 >>> 16 >>> 64 >e> 3.0 >e> 3.25 DATA TYPES, OPERATORS AND |-O >o> 4,93+7.82 12.3 >>o1m//6 2 >>> 1786 Rounding a result Python printed the result of 4.53 + 7.82 as 12.350000000000001. Because computers work in binary and not decimal, this sort of rounding error often ‘occurs when working with floating point numbers (Le. numbers with a decimal point). To print an answer to a given number of decimal places, use the round () function. >>> result >>> roundedResult = >>> roundedResult 4.53 + 7.82LEARNING TO PROGRAM IN PYTHON Relational and logical operators A Boolean data type can be either True or False. Operators fall into two categories ‘relational operators such as >, == (equal) and != (not equal), and logical operators and, or, not, The following tatsle shows all the relational and logical operators. Operation name Operator Less than Less than or equal >> 18 True >>> 18 False de> (5 > 2) 7>6 True >>> (6 >> length = 4 po> width = 3 >>> area = length * width >>> perimeter = 2 * (length + width) 12 >>> perimeter >> cA Area = 12 + area) Guidelines for naming variables Using meaningful variable names will help you to create programs which are easy to follow, contain fewer errors and are easier for you or someone else to amend at a later date, Here are a few tips: * Use the standard naming conventions or traditions for Python. For example, variable names should begin with a lowercase latter. If you define @ constant, such as PI or VAT, use all uppercase letters for the name. That way you will know not to change their value in a program. * Use meaningful, descriptive names; length, width, area rather than x, y, z. * Don’t make the names too long, and use "camel caps" to separate parts of a name. For example, passMark, maxMark, averageMark, + Note that variable names are case-sensitive, so AverageMark is a different variable name from averageMark DATA TYPES, OPERATORS AND |-OLEARNING TO PROGRAM IN PYTHON Augmented assignment Operators These operators provide a quick way of writing assignment statements. Equivalent to score = score + 1 score = score - losses, score = score * 2 i score = score / total % score %= 7 score = score % 7 Ws score //=7 score = score // 7 The print statement You have already seen the print statement, which is used to display text and data on the screen. Using a comma as a separator You can use @ comma to separate strings or variables: >>> length >>> print (” ength is", length, “metres") ‘The length is 15 metres Using a comma has the advantage that you do not have to worry about the variable type. You cen mix integers, floating point numbers and strings in the print statement. However, you cannot control the spacing. One space character is automatically inserted between the output arguments of a print statement. >>> cost = 15 >> ("The cost Is &", cost) The cost is £ 15 Note: in some Python IDES, the £ sign is not recognised and will cause the program to crash.Using + as a separator Instead of using @ comma, you can use a + sign to concatenate strings in the output. However, you cannot join a string to an integer or real number, so you first have to convert any numbers to strings. >>> cost >>> print ( 45 is £" + cost) To convert @ number to a string, you use the str () function. This is discussed in more detail in the next chapter. (See Converting between strings and numbers.) ‘You need to re-enter the statement as: >>> print ("The o The cost is £15 st is £" + str(cost)) Escape sequences Escape sequences allow you to put special characters such as a newline or tab into your strings, Inserting a new line \n skips to a new line >>> s "\nHlello") Hello >>> print ("\n\nG Goodbye Inserting a tab character Assume length = 4, width = 3andarea = 12. \¢t inserts a tab character ped princ("\t\tColumnl" + "\E\tCoLumn2™ + "\t\tcoluma3") Column column2 Colunn3 >>> (\e\t", length, "\e\c", width, "\r\r", area) 4 3 12 Note: Another method of formatting output is given in Chapter 10. DATA TYPES, OPERATORS AND I-OLEARNING TO PROGRAM IN PYTHON Printing two outputs on the same line To avoid printing on a new line, add end 80 for example: to the end of the print statement, pend =" ") ine") will output This should all print on the same line Note: You cannot show this in Python's Interactive mode, but you will sometimes need the end parameter when you start writing programs. Whatever you out ‘between the quote marks, in this case a space, will be printed. Writing a multi-line statement ‘The last question demonstrates that you can split a statement over several lines, so long as you don't split it inside the quote marks. IF you do need to spit a line within quote marks, type a backslash (\) at the end of the first ine, press Enter and continue writing on the next line, he quot: This is a long line of text split in the middle of the quote Outside quote marks, additional spaces between variables or operators are ignored, Triple-quoted strings Enclosing a string in triple quotes (either single or double quotes) allows you to retain the formatting of the string, for exarnple if it extends over several lines. Try the following ‘example in IDLE:Joha Smith Elm Street Andover The input statement The input statement is used to accept input from the user, and assign the input to variable on the left-hand side of an assignment statement. It can be used with or without a prompt to tell the user what to do. (The prompt can be provided using @ print statement in the line above, Both these techniques are shown below.) >>> firstName = ("Please enter your first name: ") Please enter your first name: Martha >>> print ("Please enter your surnam: Please enter your surname >>> surname = input () Harris >>> print ("full name is", firstName, surname) Full name is Martha Harris Note that the input () statement is always followed by parentheses even if there is no prompt. In this case, you will not see any text as @ prompt for input ~ Python will just wait until something is typed. Mixing strings and variables in an input statement ‘You can use the + sign to include a variable in an input statement. >>> phoneNumber = input (firstName +", " + "please enter \ your phone number: ") Martha, please enter your phone number You must remember to convert any numbers to strings: >rqe3 >>> answer3 = (Enter the answer to question “+ str(a) + my Enter the answer to question 3: (Waits for user to enter data) DATA TYPES, OPERATORS AND |-OLEARNING TO PROGRAM IN PYTHON 10 Exercises 1 no 2 (@) Write statements to prompt a user to input their favourite food and favourite colour, and display this information in the format “My favourite food is x0 and my favourite colour is yyy", using + symbols to concatenate the separate strings. (©) Display the same information using the comma separator instead of + symbols. (a) Write statements to ask the user to enter their name and telephone number and then print this information on two separate lines, with a blank line in between. (b) Print the name and telephone number on the same line, separated by a tab character. Write statements to: {a) perform the integer division of 40 by 11 {b) find the remainder when 40 is divided by 11 {c) calculate 2'° (d) test whether “three” is greater than “two” {@) test whether “abo" is less than than “ABC” {f test whether (1 [greater than >= _| greater than or equal <__ than _ or equal using a boolean variable in condition statement can only take the value true false. so for example we could write conditional such as: amount validamount="101" and later program validamount: be tested: : is valid anoun however also written more simply l> validamount: ("This is a valid amount") The elif clause This is useful if there are several possible routes through the program depending on the value of a variable. Example 1 ‘Students are assigned a grade of A, B, C or F depending on the average mark they have achieved over a number of assignments. Mark of 75 or more: A Mark of 60 - 74: B Mark of 50 - 59: c Mark less than 50: FWrite a statement to assign the grade to a variable grade depending on the value of mark. mark grade mark grade mark grade grade = ‘A particular ¢1i£ is tested only when all previous if and elif statements are False. When one if or e1if is True, all subsequent tests are skipped. Nested selection statements If there is more than one condition to be tested, you can use a nested selection statement. Example 2 firm hiring new employees reauires all applicants to take an aptitude test. If they pass the test, they are interviewed and if they pass the interview, they are offered ‘employment. If they fail the interview, they are rejected. If they fail the aptitude test, they are given the opportunity to resit the test at a future date. testResult == "Pas interviewOK: int ("Hired") ("Resit test") Complex Boolean expressions Boolean expressions may include ana, or or not. Operator Description and Returns True if both conditions are true or Returns True if either or both conditions are true: not ‘A true expression becomes False and vice versa SELECTIONExample 3 Here are some complex Boolean expressions used in if statements: @) day weekendRate (bo) 25 (nor day ( z weekendRate fo) 25 (testResult and (interviewOk) : (nati Re. Importing library modules In Chapter 2 we used some built-in functions such as int, str and float. In addition to these built-in functions, Python has a liorary of useful modules such as datetime, time, random, sqlite3, tkinter, pdb (a debugging module) which can be imported into a program. LEARNING TO PROGRAM IN PYTHON, Generating a random number ‘The randint () function generates a random number. It is a function included in the random module and to use it, you must first import the module by ‘including the statement import random at the start of the program. This imports the module called random. Then in your Program, to generate a random integer between a range of integers a and b you write num = random. randint (a,b) Example 4 Generate two random numbers between 1 and 6 to reprasent the throw of two dice. If the numbers are equal, print, for example, “You threw a double 5* diel = random. randint (1,6) die2 = random. randint (1,6) diel die ", diet) i, diel, die2) 20Exercises 4 Write a program to allow the user to enter the length and width of a rectangle and calculate the area. If the length and width are equal, print “This is a square of area nn.nn’, Othemise, print "This is a rectangle of area nn.nn’. Write a program to display a menu of options: Menu 1. Music 2, History 3. Design and Technology 4. Exit Please enter your choice: ‘The user then enters a choice and the program prints a message such as “You chose History”. If they choose option 4, the program prints "Goodbye". \Write a program to simulate the throw of two dice (each between 1 and 6). Print the numbers representing the two throws. If the numbers on the two dice are not equal, the player's score is the sum of the numbers thrown. Print the score. Ifthe numbers on the two dice are equal, the player scores twice the sum of the number thrown. Print “You threw a double”, and the score. ‘Write a program to input the value of goods purchased in a shop. A discount is subtracted from the value to find the amount owed. IT the value is £200 or more, 10% discount is given If the value is between £100 and £199.99, 5% discount is given. Print the value of goods, discount given and amount owed. Write a program to caloulate car park charges. Up to 2 hours costs £3.50, up to 4 hours £6.00, up to 12 hours £10.00. The driver enters the number of hours they require and the machine prints the current time, expiry time and charge. For example: Time now: Wed Mar 8 15:47:46 2017 Thu Mar 9 03:47:46 2017 10.00 expire charge Tip: Use the Python library function time by writing import time at the top of the program. The time in seconds since January 1st 1970 is given by currentTime = time.time() This can be formatted as shown in the sample output above with the statement: currentTimeFormatted = time. ctime(currentTime) SELECTIONExample 3 Here are some complex Boolean expressions used in if statements: | @ & day = . say" | weekendRate | ® | C= day © > aay | weekendRate = =) = ©! (eestResult == "Pass") ss (interviewox) : ("Hired r ("Rejected") Importing library modules In Chapter 2 we used some built-in functions such as int, str and float. In addition to these built-in functions, Python has a liorary of useful modules such as datetime, time, random, sqlite3, tkinter, pdb (a debugging module] which can be imported into a program. LEARNING TO PROGRAM IN PYTHON Generating a random number ee! The randint () function generates a random number. It is a function included in 3 the random module and to use it, you must first import the module by including the statement ee import random at the start of the program. This imports the module called random. Then in your program, to generate a random intager between a range of integers a and b you write , num = random. vandint (a,b) Example 4 Generate two random numbers between 1 and 6 to represent the throw of two dice. If the numbers are equal, print, for example, “You threw a double 5” diel = random.randint (1,6) die2 = random.randint (1,6) diel == die2: + diel) (Not a double:", diel, diez) 20Exercises 1 Write 2 program to allow the user to enter the length and width of a rectangle and calculate the area, if the length and width are equal, print ‘This is a square of area nn.nn’, Otherwise, print "This is a rectangle of area nn.nn’, Write @ program to display a menu of options: Menu 1. Music 2. History 3. Design and Technology 4. Exit Please enter your choice: ‘The user then enters a choice and the program prints @ message such as “You chose History". If they choose option 4, the program prints "Goodbye". Write a program to simulate the throw of two dice (each between 1 and 6). Print the numbers representing the two throws. If the numbers on the two dice are not equal, the player's score is the sum of the numbers thrown. Print the score, If the numbers on the two dice are equal, the player scores twice the sum of the number thrown. Print “You threw @ double”, and the score. Write a program to input the value of goods purchased in a shop. A discount is subtracted fram the value to find the amount owed. If the value is £200 or more, 10% discount is given, If the value is between £100 and £199.99, 5% discount is given. Print the value of goods, discount given and amount owed, Write a program to calculate car park charges. Up to 2 hours costs £3.50, up to 4 hours £5.00, up to 12 hours £10.00. The driver enters the number of hours they require and the machine prints the current time, expiry time and charge. For example’ Wed Mar 8 15:47:46 2017 Expires: Thu Mar 9 03:47:46 2017 charge = 10.00 Tip: Use the Python library function time by writing import time at the top of the program. The time in seconds since January 1st 1870 is given by currentTime = time.time() This can be formatted as showr Time now the sample output above with the statement: currentTimeFormatted = time.ctime (currentTime) SELECTION 21are 22 Chapter 4 Iteration Objectives * Use for loops (definite iteration) * Use whi Le loops (indefinite iteration) © se string functions and operators The for loop ‘Sometimes in a program, you want to repeat a sequence of steps a certain number of times. A for loop can iterate over a sequence of numbers in a range in different ways. For example, the programmer can specify that a number used as @ counter has arange a. .b, meaning from a up to but not including b. Example 1 program name: Ch 4 Example 1 # Sam print("Numbers from 1-! foe number ange (1,6) (number, end - " ge 1: print the nun ) #Sample ra ("\eNumb: f= number (\ng) punber (number, end = y third number in (2,17,3) + atNested loops number 2 (5,0,-1)+ rine (number, end =" ") ery number from 5 down to 1:" } ITERATION The output is: Numbers from 1-5: 12345 Numbers from 0-4: 01234 Every third number from 1-16: 1471013 16 Every number from 5 down to 1: 54321 Note the following points in the sample ranges: «Sample range 1 shows that if you want the range to go from 1 to 5, you must specify the range as range (1, 6). The range will start with the first numiber specified, and go up to but not including the second number specitied. ‘* Sample range 2 shows that if you specify only one value in the range, this is taken as the end of the range. The first value in the range defaults to 0. Thus range (5) includes the five values 0, 1, 2, 3, 4. Sample range 3 shows that you can count in threes. You can increment the counter by any integer value. » Sample range 4 shows that you can increment the counter by a negative value. The counter will then count down from the first value specified. It will not include the last number in the specified range. (See Chapter 5 for an alternative and powerful way of specifying the range at the start of a for loop.) You can have one loop “nested” inside another. The next example shows how you could print all the multiplication tables from 2 to 10. Example 2 #Progrem Example 2 Multiplication t table is = (2,11): ("\n" + sc: (table) +" Times Table ") n (2,13): (os (table) 4" maxResult: maxResult = testResult testResult =", numiords) acters =", len(sentence)) Indexing strings Each character in a string can be referenced by its index, starting at 0. Thus, if a variable called word contains the characters "python", word[0] = “p", word(1] = y",word[2] = "t" andsoon, Example 5 Find the index of the first occurrence of the letter “e" in a sentence input by the user. In this example, we will make use of the “break” statement. This breaks out of the loop, transferring control to the first statement after the loop. Although this is. ‘sometimes considered by some to be bad practice in structured programming, others disagree and it often simplifies the code. #erogram name: Ch 4 Example $ first e.py eIndex = -1 sentence = input ("Please enter a sentence: ") ePosition in cance sentence [Position] elIndex (sentence) ) : ePosition is", etndex) sentence iSlicing strings Using indexing, you can isolate a single character in a string. Using slicing, you can isolate anything from a single character to the whole string, so for example you could look at the first three characters of a car registration number, or the middle five characters of a nine character string Example 6 You can try out various slices using an interactive session. >>> name = "Phillip" >>> nickname ~ name[0:5) pep >>> >>> (nickname) Phill (name [1:5]) >>> bill ‘With both indexing and slicing, you can use negative numbers. Sometimes it makes more sense to start counting position numbers from the end of a string. You can visualise the end points with alternative numberings as shown in the figure below: 1 2 38 4 5 6 7 ee CEE E ET pr Tt ttt pops hil {name [-6: If you specify an impossible slice, where the starting point is bigger than the end point, like name [3:1] of name [4:-5], Python will return an empty string. >>> impossible = name (5:1) >>> impossible However, you can mix positive and negative end points: o> (name [-6:4]) hil ITERATIONLEARNING TO PROGRAM IN PYTHON 28 Interrupting execution Sometimes a logic error may result in a program looping endlessly. You can terminate (kil) a running program by selecting Shel, interrupt execution from the menu bar in the Python Shell menu, or by pressing the shortcut key combination Ctrl-C. Example 7 In the following example, the programmer has forgotten to write an input statement at the end of the while loop. $Progran con endless Loop ("\nYou can stop it by select 2") the menu in che python name Enter a name, xxx to end (Number of (name) ) The output will be something like: Wunbe of lett Number of letters in name: Number of letters in name: 9 {endlessly repeated) Exercises 1. Write a program to generate 10 random numbers between 1 and 10, and print out the 10 numbers and the total of the numbers. 2, Extend the program in Exercise 1 to repeat the generation of 10 random numbers 1000 times. Do not print out the random numbers or the total of each set of 10 numbers — just print the average of the totals at the end of the program. Is the answer what you would expect? 3. Write a program to allow the user to enter a number of 5-character product codes, beginning with the letters "AB" or “AS” followed by 3 numeric characters, Count and print the total number of product codes starting with “AB" and the total number of product codes ending in "00" Test your program by entering product codes AS123, AS101, ABI11, AB345, 00222, AB200.(aac | Lists and tuples Objectives © Understand why lists are useful * declare a list and use list functions and methods * use one- and two-dimensional lists to solve problems * distinguish between lists and tuples Python lists A list in Python Is a type of sequence, like a string. However, unlike a string, which can contain only characters, a list can contain elements of any type. A list could contain, for example, several names: name = ["Mark", "Juan", "Ali", "Cathy", "Sylvia", "Noah"] ‘These names can be indexed, just like the elements of a string, 80 name (0) Noah” A\list can hold elements of different types, so for example you could define a lst like this: "Ben Charlton", 14,17, 16, 15,17) Defining a list A list may be defined in a Python program as in the examples above. You can also define an empty list, or alist with many elements of the same value, as shown in the interactive session below: >>> abist = (J >>> abist 0 >>> bhist = [1 * 10 >>> bhistLEARNING TO PROGRAM IN PYTHON (None, No! >>> chist >>> cList 10, 0, 0, 0, 0 None is a special value in Python which acts as a useful placeholder for a value. It evaluates to False when tested in a conditional statement. Operations on lists ‘Some list methods are shown in the table below. Assume a = (45,13, 19,13,8] List me List contents Return Spee || Dretet Example [following execution | value ‘Add a new iter to appendiitem) |lstto the end of the | a.append(a) |[45, 19, 19, 13, 8, 33] fist Remove the frst remove(ter) occurrence of an | aremove(13) | 45, 19, 19, 8, 23] item from lst len) Batam gre number | enjay 145, 19, 138,33) [5 indexftem) | Ratu the postion | aindexte) | (45, 19, 13,8, 93] |3 Insert a new item at ingertipositem) | Meh oe ainsert(2,7). |[45, 19, 7, 13, 8, 33) Remove and return pop) the astitem inthe | 2.p0p0 45, 19.7,13.6) |33 list Remove and return poptoos) —_thettemat position [apoptt) | 45, 7, 13, 8] 19 os Note that Len () isa function, not a method, and is written in a different way. Example 1 Determine whether the number 100 is in the list listB = [56,78,100,45,88,71], and if so, print its index. fecogeam nae: Ch § Example 1 List of numb: ListB = (56,78, 100,45, 88,71] 100.) 1istB: ("100 is at position ", ListB.index(100)) ("100 is not in the list™)Example 2 \Write code to print the numbers in 1istB on separate lines num i> ListB: (aun) Alternatively, you could write ror index =n r Appending to a list (ier QistB)) + yint (ListBlindex] ) Ast is a fixed size; you cannot, for example, add a new item to ListB by writing ListB[6) = 81 You will get an “index out of range” error. Instead, you must use the append method, defined in the table on the previous page. List8.append(81) This will result in ListB being set equal to (56, 78, 100, 45, 88, 71,81) You can append one list to another. If you want to concatenate (join together) two lists aumbistl and numbist2, you can use the augmented operator interactive session shows this: >>> numbistl = [1,2,3,4] >>> numbist2 = [5,6,7,8] >>> numbistl += numbist2 >>> numbist1 E> [1,2,3,4,5,6,7,8) Alternatively, write numbistl = numbist1 + numbist2 = , The following LISTS AND TUPLESList processing Items are often held in lists for further processing. The items may be input by the user or read from a file on disk, for example. Sometimes the list of values may be defined in the program. Example 3 Define a list containing the names of students in a class. Ask the user to input the exam results for each student. Print a report showing the data with column headings Student Exam mark LEARNING TO PROGRAM IN PYTHON At the end of the report, print the name of the student with the highest mark, and the mark obtained. In the following program, names have been padded with spaces to enable printing in neat columns using the tab escape sequence \t. Milner, Angela “, topMark numberOfStudents ~
topMark: topMark = mark topStudent = studentNames[etudent] int ("\nstud ) student — (numberofstudents) (studentNames [student], "\c", results [student] ) (\ntop sie: ",topstudent, topMark) 32t ; ; f E i This produces output in the format: enter mark for Khan, Afridi 56 enter mark for Milner, Ang ea Enter mark for Philips, Justine : 71 Eater mark for Osmani, Pias : 52 student Exam mark Khan, Afridi Milner, Angela a Philips, Justine Osmani, Top result: Philips, Two-dimensional lists In some applications you may need a table of values rather than a one-dimensional list. Suppose you wanted to hold the data in the following table, which shows the average maximum and minimum temperatures (°C) in London for each month of the year. Month Max temp (°C)_| Min temp (°C) January 6 3 February 7 3 March 10 4 April 13 6 May 7 9 une 20 12 July 22. 14 August 24 14 September 19 12 Oxtober 14 9 November 10 6 December 7 3 These values could be stored in a two-dimensional list named monthlyAvg: monthlyavg = [ ("January", 6,3], ["Pebruary",7, 3), ['March", 10,4], and s0 on down to ("December",7,3] 1 LISTS AND TUPLESLEARNING TO PROGRAM IN PYTHON 34 Each element of the two-dimensional lst is referred to by two indices giving the row index (between 0 and 11) and column index (between 0 and 2) ‘The average maximum temperature in March would be referred to as month1yAvg[2] [1] ‘The data for March is ("March", 10,4] and is held in monthlyAvg [2] Example 4 Write @ program to enable a user to enter the average maximum and minimum temperatures for each month and store them in a two-dimensional list named month1yAvg. Print the monthiy data when it has all been entered Some things to note about this program: «The month names are supplied in a list so that the user does not have to enter them, + The table monthLyAvg which will hold the monthly averages is initialised to an empty list. It will eventually contain 12 elements, each element being a list of 3 elements. + The three values in each row (monthName [m], maximum and minimum) have been assigned to a list variable called row, which is then appended to the table month1yavg. Recall that adding end = " " tothe end of a print statement means that one space will be printed at the end of the line, and the next print statement will print the data on the same line.gram name:Ch § Exampl #program allow the user to average maximum wapeil"; "May", ber," tober", "No monthlyavg = ( ange (12 ("Enter average maximum 4 minimum foc " + monthName(m]) maximum = 290 ( (Maximum: minimum = int (icpuc("Winimum: ")) row = [monthName[m], maximum, minimum] monthlyAvg.append (row) print the ce ™\n") fox index in canga(3): monthlyAvg{m] [index] ,end = " ") print (*\n") Tuples Tuples are very similar to lists, with one major difference: they are immutable, which means that once defined, they cannot be changed. Like a list, a tuple can hold a number of items of the same or different types, and can be indexed, sliced and sorted. tuple is written in parentheses (round brackets) rather than square brackets. The {following interactive session demonstrates the immutability of a tuple. >>> name = ("ilary", "Jenny", "George", "Ben") pe> or int (name (2]) George >>> name[2] = "Jorge" LISTS AND TUPLESLEARNING TO PROGRAM IN PYTHON 36 Exercises 1 Write Python statements to: (@) define an empty list called alist {0} append a string element "apple" to alist (c) define alist named b1ist containing 20 integer elements, all zero (d) concatenate alist and blist and assign the result to clist (6) remove the last element of clist and assign it to Last Write 2 program to do the following: Initialise an empty list. Ask the user to input as many names as they like, until they enter "End” instead of a name. Slice the list in half and print the first half of the list, If the list contains an odd number of values, ¢.g. nine values, print only the first four values. Write @ program to accept a student name, and the marks obtained on 10 weekly tests. Print the name, average mark, top three marks and bottom three marks. (Use sortedMarks = sorted(markList, reverse = True) to sort the list) Extend the program shown in Example 3 to find the months with the hottest average ‘temperature and the coldest average temperature. Print the month names and relevant ‘temperatures of these months. Write a program to simulate how the top scores of several players playing an online game many times could be held in a list (@) Define a two-dimensional list which will hold in each row, a user ID and their top score for an online game. The two-dimensional list is to be initialised with the following values: userID topScore ARADL = 135, BBBOl 87 cccol «188 pppol = 109 (0) Ask a user to enter their ID. Check if the user ID is in the list. fit is not found, append a new row containing the user ID and a score of zero. (c) Generate a random number between 50 and 200 to represent the score for this game. Locate the user. Check whether the new score is greater than the score in ‘the list, and if 80, replace it (d) Print the whole list of players and scores. Repeat steps b to d until a user ID of xxx is entered,
You might also like
Download Complete The Quick Python Book 4th Edition MEAP V01 Naomi Ceder PDF for All Chapters
PDF
100% (4)
Download Complete The Quick Python Book 4th Edition MEAP V01 Naomi Ceder PDF for All Chapters
61 pages
Resource - Python Cheat Sheets - Python Programming With Sequences of Data - Y9
PDF
No ratings yet
Resource - Python Cheat Sheets - Python Programming With Sequences of Data - Y9
8 pages
Variable Function: Python Keywords and Identifiers
PDF
No ratings yet
Variable Function: Python Keywords and Identifiers
75 pages
An Introduction To Interactive Programming in Python
PDF
No ratings yet
An Introduction To Interactive Programming in Python
3 pages
5.lists: 5.1. Accessing Values in Lists Ex
PDF
No ratings yet
5.lists: 5.1. Accessing Values in Lists Ex
8 pages
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
PDF
No ratings yet
12 Comp Sci 1 Revision Notes Pythan Advanced Prog
5 pages
Python1 Worksheet
PDF
No ratings yet
Python1 Worksheet
4 pages
Fundamentals of Python Programming
PDF
No ratings yet
Fundamentals of Python Programming
135 pages
E Accts Easyweb Chettinad Chettinadadmin Homework 011018 9HCSC011018 PDF
PDF
No ratings yet
E Accts Easyweb Chettinad Chettinadadmin Homework 011018 9HCSC011018 PDF
12 pages
Lab-02 Basics in Python Language: Objectives
PDF
No ratings yet
Lab-02 Basics in Python Language: Objectives
14 pages
Python
PDF
No ratings yet
Python
18 pages
Intro To Python Programming
PDF
No ratings yet
Intro To Python Programming
28 pages
Python: From Darkness to Dawn (.DOCX)
PDF
No ratings yet
Python: From Darkness to Dawn (.DOCX)
42 pages
CP CS115
PDF
No ratings yet
CP CS115
67 pages
Introduction To Python
PDF
No ratings yet
Introduction To Python
24 pages
Python Lecture-1
PDF
No ratings yet
Python Lecture-1
41 pages
Introduction To Microsoft Access
PDF
No ratings yet
Introduction To Microsoft Access
3 pages
Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
PDF
No ratings yet
Numpy and Matplotlib: Purushothaman.V.N March 10, 2011
27 pages
Starting
PDF
No ratings yet
Starting
82 pages
Constants, Variables, & Data Types: Prepared By:vipul Vekariya
PDF
No ratings yet
Constants, Variables, & Data Types: Prepared By:vipul Vekariya
46 pages
DiTEC Unit 08 - Python Programming
PDF
No ratings yet
DiTEC Unit 08 - Python Programming
72 pages
Introduction To Python Programming: Dr. R. Rajeswara Rao Professor & Head Dept. of CSE Jntuk-Ucev Vizianagaram
PDF
No ratings yet
Introduction To Python Programming: Dr. R. Rajeswara Rao Professor & Head Dept. of CSE Jntuk-Ucev Vizianagaram
27 pages
Python Operators
PDF
No ratings yet
Python Operators
7 pages
Python Skills Homework 2
PDF
0% (3)
Python Skills Homework 2
3 pages
Beginners Python Cheat Sheet PCC BW
PDF
No ratings yet
Beginners Python Cheat Sheet PCC BW
2 pages
Python Programming
PDF
No ratings yet
Python Programming
4 pages
Python Mastery - 2 BOOK IN 1
PDF
No ratings yet
Python Mastery - 2 BOOK IN 1
438 pages
G-8 Computer Worksheet Answerkey
PDF
No ratings yet
G-8 Computer Worksheet Answerkey
2 pages
Python Programming
PDF
No ratings yet
Python Programming
59 pages
Python-Course-PPT
PDF
No ratings yet
Python-Course-PPT
184 pages
Module 3 - Intro To C++
PDF
No ratings yet
Module 3 - Intro To C++
54 pages
Python Worksheet 1 Data Types
PDF
No ratings yet
Python Worksheet 1 Data Types
2 pages
Python All Programs
PDF
No ratings yet
Python All Programs
7 pages
Python by Geeky Show
PDF
No ratings yet
Python by Geeky Show
9 pages
Python ToC
PDF
No ratings yet
Python ToC
4 pages
Functions: Python For Informatics: Exploring Information
PDF
No ratings yet
Functions: Python For Informatics: Exploring Information
24 pages
Data File Handling: Worksheet
PDF
No ratings yet
Data File Handling: Worksheet
10 pages
Pythonlevel 2
PDF
No ratings yet
Pythonlevel 2
99 pages
Class -9 Python Notes
PDF
100% (1)
Class -9 Python Notes
26 pages
Python 07 Files
PDF
No ratings yet
Python 07 Files
17 pages
Lab 2 Variable and Data Type I
PDF
No ratings yet
Lab 2 Variable and Data Type I
9 pages
Introduction To Python PDF
PDF
No ratings yet
Introduction To Python PDF
42 pages
Python Programming - Introduction All
PDF
No ratings yet
Python Programming - Introduction All
44 pages
9 Using The Maya Python API
PDF
100% (1)
9 Using The Maya Python API
11 pages
Learn Python Programming Language
PDF
No ratings yet
Learn Python Programming Language
178 pages
Python For Beginners - Daniel Correa Paola Vallejo
PDF
No ratings yet
Python For Beginners - Daniel Correa Paola Vallejo
408 pages
Applied Text Analysis with Python Enabling Language Aware Data Products with Machine Learning 1st Edition Benjamin Bengfort instant download
PDF
No ratings yet
Applied Text Analysis with Python Enabling Language Aware Data Products with Machine Learning 1st Edition Benjamin Bengfort instant download
55 pages
What Is Computer Programming? Basics To Learn Coding
PDF
No ratings yet
What Is Computer Programming? Basics To Learn Coding
5 pages
Module 4 - C++ Basic IO - 2015
PDF
No ratings yet
Module 4 - C++ Basic IO - 2015
11 pages
Python Interview Questions
PDF
No ratings yet
Python Interview Questions
61 pages
(R18A0513) Python Programming
PDF
No ratings yet
(R18A0513) Python Programming
183 pages
Ques Python
PDF
No ratings yet
Ques Python
30 pages
Python Notes: Invented By: Guido Van Rossum (1991)
PDF
No ratings yet
Python Notes: Invented By: Guido Van Rossum (1991)
2 pages
Python 100 Days Course PDF
PDF
No ratings yet
Python 100 Days Course PDF
8 pages
Unit 1
PDF
100% (1)
Unit 1
69 pages
Keywords in Python
PDF
No ratings yet
Keywords in Python
18 pages
Comprehension in Python
PDF
No ratings yet
Comprehension in Python
2 pages
PYTHON-PROGRAMMING-topic-2
PDF
No ratings yet
PYTHON-PROGRAMMING-topic-2
76 pages
PWP Notes (Chapter Wise)
PDF
100% (1)
PWP Notes (Chapter Wise)
123 pages
Programming With Python (PWP) Notes: Chapter No. Name of Chapter
PDF
No ratings yet
Programming With Python (PWP) Notes: Chapter No. Name of Chapter
113 pages
Thank You! Your Order Has Been Received
PDF
No ratings yet
Thank You! Your Order Has Been Received
3 pages
Application 0
PDF
No ratings yet
Application 0
6 pages
4.5.2023 Unit - 05 - Assessment - H
PDF
No ratings yet
4.5.2023 Unit - 05 - Assessment - H
3 pages
1500 Word Essay
PDF
No ratings yet
1500 Word Essay
2 pages