practice work in a different file.:
Focus on: Basic list operations, methods, and functions.Write a program that does the following:
- Create a list of length 10 whose elements are randomly selected integers between 2 and 9.
- Print out the list.
- Create a copy of the list sorted in decreasing order and print it.
- Print the original list.
- Report the distinct elements in the list
- Ask the user for an integer between 2 and 9. If the number is in the list, report howmany times it occurs.
Here are two sample runs.
the following work is just like last time:
Programming Assignment 6 Focus on basic list functions, parallel lists
A. The file USPopulation.txt is provided with this assignment. The file contains the midyear population of the United States, in thousands, during the years 1950 through 1990. The first line in the file contains the population for 1950, the second line contains the population for 1951, and so forth.
Write a program that will
a. Read the file contents into a list named population and create two additional lists:
- A list named year with a list of the years from 1950 to 1990
- A list named pop_changes which stores the population changes from one yearto the next. The change is the difference from one year to the next. The first change is for the year 1950 and is 2114 (153982 in 1951 minus 151868 in 1950). Note that there won’t be one for 1990 because we don’t have data for the following year.
- the average population during the time period 1950 to 1990
- the overall population change from 1950 to 1990
- The average annual change in population during the time period
- The year with greatest change in population during the time period
- The year with smallest change in population during the time period
c. Prompt the user to input a year. Report:
- the population for that year
- the change from the previous year (There won’t be one for 1950)
- the change for the following year (There won’t be one for 1989)
Use appropriate error prevention techniques, including input validation and exception handling.
Use this same fro both practice and main work.
• Use inline comments to describe complex sections of code Avoid unnecessary and trivial comments
avg = (score1 + score2 + score3)/3 # add scores and divide by 3
ALMOST AS BAD – because well designed variable names should make the comment unnecessary
avg = (score1 + score2 + score3)/3 # calculate average
Whitespace and indentation:
• Use correct, consistent indentation.
o All blocks of code within a given function or control flow structure must be distinguished
from the preceding code by one indentation level.
o Use 4 spaces per indentation level. IDLE will automatically indent 4 spaces when you hit
the tab key.
- Always place a line break after a colon ( : )
- Avoid long lines.
o Avoid lines longer than 80 characters, including indentation. Make sure to maintain
correct indentation when breaking long lines into shorter ones.
- Make smart variable type decisions and utilize type conversionsStore data using the appropriate data types (making sure to use the appropriate literals as well), and make sure to use the type conversion functions (str(), int(), float())when necessary. Remember, for example, that if you ask the user to input the temperature outside and you want to use that value in a calculation, you will have to convert their input to a float before you can use it.
- Follow variable naming conventions
Name variables using underscore (AKA snake case) like_this. Use concise, descriptive namesfor variables that precisely describe what information they’re storing.
- Create one variable per line of codeNever initialize more than one variable in a single statement.# bad # good a, b, c = 7, -43, 19 a = 7b = -43 c = 19
• Use named constants when appropriate
If a particular constant value is used frequently in your code, identify it as a constant, and always refer to the constant in the rest of your code rather than referring to the corresponding literal value. Name constants in uppercase with underscores between words LIKE_THIS.
DAYS_IN_WEEK = 7 DAYS_IN_YEAR = 365 HOURS_IN_DAY = 24
Part 2 – Conditionals and Loops
These requirements apply to Chapters 3 & 4 and later assignments
• Avoid empty if or else branches
o When using if/else statements, you should not have `if` or `else` branches that are blank.
Rephrase your condition to avoid this.
• Avoid unnecessary control flow checks
When using if/else statements, properly choose between various if and else patterns depending on whether the conditions are related to each other. Avoid redundant or unnecessary if tests. Ask yourself if all of the conditions always need to be checked.
# badif points >= 90:
print('You got Gold!')if points >= 70 and points <90:
print('You got Silver!')if points >= 50 and points <70:
print('You got Bronze!')...
# goodif (points >= 90):
print(‘You got Gold!’)} elif points >= 70:
print(‘You got Silver!’) elif points >= 50:
print('You got Bronze!')...
- Beware of infinite loops
Avoid writing loops that never stop. An infinite loop will cause your program to neverstop executing. Replace infinite loops with loops that terminate.
- Choose the right loopConsider when it would be more appropriate to use a while loop or for item in list loop or for item in range loop.
Part 3 – Functions
These requirements apply to Chapter 5 and subsequent assignments
- Use descriptive names for functionsGive functions descriptive names, such as discount(price, rate) or make_a_star(). Avoid one-letter names and non-descriptive names, like x() or go() or function1().Function names should be all lowercase, with words separated by underscores to improve readability.
- Keep your main program a concise summaryAs much as possible, avoid having too much of your program’s functionality directly in your main() code. When writing your programs, try to break the problem down into smaller sub-problems. Create functions for these individual sub-problems. This makes your program easy to read and forms a concise summary of the overall behavior of the program.
- Minimize redundant codeIf you repeat the same code block two or more times, find a way to remove the redundant code so that it appears only once. For example, you can place it into a function that is called from both places.
- Avoid long functionsEach function should perform a single, clear, coherent task. If you have a single function that is very long or that is doing too much of the overall work, break it into smaller sub- functions. If you try to describe the function’s purpose and find yourself using the word “and” a lot, that probably means the function is doing too many things and should be split into sub-functions.
- Consider short functions for common tasks
It can be useful to have a short function if it wraps another function with some additionalcontrol flow or if it contributes to an easier to understand name.# bad
def square_root(x): return math.sqrt(x)
def discount(price, rate): discount = price – rate*price
- Write an overall header comment for every function – use the IPO notation described in Chapter 5 slide 49
• Eliminate redundancy by introducing functions with parameters
If you repeat the same code two or more times that is nearly but not entirely the same, try
making a helper function that accepts a parameter to represent the differing part.
x = foo(10) y= x- 1 print(x * y) …
x = foo(15) y= x- 1 print(x * y)
print(helper(10)) print(helper(15)) ...
def helper(p): x = foo(p)
y=x -1 return x * yx
Part 4 – Classes
These requirements apply to Chapter 10 and subsequent assignments
- Do not access object attributes directly in the client (abstraction)You should avoid directly accessing attributes of classes you write. Instead, use getter and setter methods to access the appropriate pieces of information when necessary.
- Keep related tasks bundled together within the appropriate class (encapsulation)You should design your classes in a such a way that all of the appropriate data and the methods that act upon that data are all encapsulated within the class. For example, the client of a graphics program should not be implementing its own graphical behavior or directly accessing graphical objects.
- Avoid unnecessary instance variables (attributes)Use instance variables (attributes) only when they are required to implement certain functionality, or if it makes sense for that variable to persist outside of any given method. Don’t use them to store temporary values used in only a single call to one method, for instance. You should assess whether a variable is needed across multiple methods before making it an instance variable.
Please let me know if you have any questions.
thank you so much in advance,