Loading...

Messages

Proposals

Stuck in your homework and missing deadline? Get urgent help in $10/Page with 24 hours deadline

Get Urgent Writing Help In Your Essays, Assignments, Homeworks, Dissertation, Thesis Or Coursework & Achieve A+ Grades.

Privacy Guaranteed - 100% Plagiarism Free Writing - Free Turnitin Report - Professional And Experienced Writers - 24/7 Online Support

Charge account validation python

19/11/2020 Client: arwaabdullah Deadline: 24 Hours

Programming in Python CS21A

Lab 4: Lists and Tuples – Files (25 points)

Learning Objectives for this lab include:

 Understand list basics including elements and subscripts.

 Learn how to find high and low values of a list.

 Learn how to step through and process the elements of a list.

 Learn how to pass lists as arguments to a function.

 Learn how to write lists in Python code.

 Open a text file for output and write strings or numbers to the file

 Open a text file for input and read strings or numbers from the file

An array is called a list in Python. A list is an object that contains multiple data items. Lists are

mutable, which means that their contents can be changed during a program's execution. Lists are

dynamic data structures, meaning that items may be added to them or removed from them.

Index or subscript starts at 0 in Python.

Numeric Arrays

Elements of an array can be defined as follows if the values are known:

even_numbers = [2, 4, 6, 8, 10]

If the numbers are not known at the beginning, use the repetition operator (*) to create a list with

a specific number of elements, each with the same example. The following will create an array

of 10 elements all set to 0 in the beginning.

numbers = [0] * 10

String Arrays

Elements of a string array are initialized as follows:

names = ['Molly', 'Will', 'Alicia', 'Adriana']

Printing Values of the Array

This can be done in one sequence by the following:

print (even_numbers)

The will result in the list printing as follows: [2, 4, 6, 8, 10].

Using Loops and Index

In most cases, a loop should be used to get values in or out of an array. This will allow a specific

index to be specified. A for loop or a while loop will work.

The for loop

numbers = [99, 100, 101, 102]

for n in numbers:

print(n)

The while loop

index = 0

while index < 4:

print (my_list[index])

index += 1

Lists and Tuples

- Lists are mutable; tuples are immutable.

- Lists and tuples are sequences.

- Lists allow assignment: L[3] = 7

Tuples do not.

Standard operations:

- length function: len(L)

- membership: in

- max and min: max(L) and min(L)

- sum: sum(L)

Indexing and Slicing

Given: L = ['b', 7, 6, 5,[2,9,1],5.5]

- Tuples work the same with indexing and slicing.

- Indexing starts at 0: L[0] is ‘b’.

- Negative indices work backward from the end: L[-1] is 5.5.

- Slicing selects a subset up to but not including the final index: L[1:4] is [7,6,5].

- Slicing default start is the beginning, so L[:3] is ['b', 7, 6].

- Slicing default end is the end, so L[4:] is [[2, 9, 1], 5.5].

- Using both defaults makes a copy: L[:].

- Slicing’s optional third argument indicates step: L[:6:2] is ['b', 6, [2, 9, 1]].

- The idiom to reverse a list: L[::-1] is [5.5, [2, 9, 1], 5, 6, 7, 'b'].

List Methods (partial list)

Given: L1 = [1,3,2] and L2 = [7,8]

- L1.append(0) changes L1 to be [1,3,2,0].

- L1.append(L2) changes L1 to be [1,3,2,[7,8]].

- L1.extend(L2) changes L1 to be [1,3,2,7,8].

- L1.sort() changes L1 to be [1,2,3].

- L1.insert(2,11) inserts 11 before index 2, so L1 becomes [1,3,11,2].

- L1.remove(3) removes 3, so L1 becomes [1,2].

- L1.reverse() changes L1 to be [2,3,1].

- L1.pop() pops 2 off, so L1 becomes [1,3] and returns 2.

Programming in Python Summer 2014

CS21A June 30, 2014

Methods Shared by Lists and Tuples (partial list)

Given: L1 = [1,3,2] and L2 = [7,8]

- L1.index(3) returns the index of item 3, which is 1.

- L1.count(1) counts the number of 1’s in L1: 1 in this case.

Writing to a File

When writing to a file, an internal file name must be created, such as outFile.

This file must then be opened using two arguments. The first argument is the name of the file

and the second is the mode you want to open the file in. You can select either the ‘a’ append

mode or the ‘w’ write mode. For example:

outFile = open('filename.txt', 'w')

Files must then be closed. This works the same for both input and output.

outFile.close() or inFile.close()

Reading from a File

When reading from a file, an internal file name must be created such as inFile.

This file must then be opened using two arguments. The first argument is the name of the file

and the second is the mode you want to open the file in, ‘r’ for read. For example:

inFile = open('filename.txt', 'r')

Reading from a file is done sequentially in this lab, and a call to read must occur. If a string

header is done first, that must be read into a string variable. That variable can then be used for

processing within the program.

A string literal can be read from a file and displayed to the screen such as:

str1 = inFile.read()

print (str1)

Arrays and variables can be read as a single input such as:

arrayName = inFile.read()

print (arrayName)

Lab 4.1: Total Sales [10 points]

1. Open the program TotalSales.py file.

2. Fill in the code so that the program will do the following:

 Ask the user to enter a store’s sales for each day of the week.

 The amounts should be stored in a list.

 Use a loop to calculate the total sales for the week and display the result.

Save the code to a file by going to File Save.

Python Code:

def main():

# Variables

total_sales = 0.0

# Initialize lists

daily_sales = [0.0,0.0,0.0,0.0,0.0,0.0,0.0]

days_of_week = ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday",

"Friday", "Saturday"]

'''Fill in this space to ask the user to enter a store’s sales for each

day of the week. The amounts should be stored in a list.

Use a loop to calculate the total sales for the week and display the

result'''

print ("Total sales for the week: $", format(total_sales, '.2f'), sep='')

main()

Here is a sample run of the program:

Enter the sales for Sunday: 56

Enter the sales for Monday: 23

Enter the sales for Tuesday: 67

Enter the sales for Wednesday: 23

Enter the sales for Thursday: 42

Enter the sales for Friday: 78

Enter the sales for Saturday: 23

Total sales for the week: $312.00

Lab 4.2 – Charge Account Validation [15 points]

1. Open the program AccountValidation.py file.

2. Fill in the code so that the program will do the following:

 Read the contents of the file into a list.

 Ask the user to enter a charge account number.

 Determine whether the number is valid by searching for it in the list. If the number is

in the list, the program should display a message indicating the number is valid. If the

number is not in the list, the program should display a message indicating the number

is invalid.

The file charge_accounts.txt has a list of a company’s valid charge account numbers. Each

account number is a seven-digit number, such as 5658845 .

Save the code to a file by going to File Save.

Python Code:

def main():

# Local variables

test_account = ''

# Open the file for reading

input_file = open('charge_accounts.txt', 'r')

# Read all the lines in the file into a list

accounts = input_file.readlines()

# Strip trailing '\n' from all elements of the list

for i in range(len(accounts)):

accounts[i] = accounts[i].rstrip('\n')

# Fill in this space to get user input

# Fill in this space to use in operator to search for the

# account specified by user

# Call the main function.

main()

Here is a sample run of the program:

Enter the account number to be validated: 56

Account number 56 is not valid.

Enter the account number to be validated: 5658845

Account number 5658845 is valid.

Submission

1. Include the standard program header at the top of your Python file.

2. Submit your files to Etudes under the “Lab 04“ category.

TotalSales.py

AccountValidation.py

Standard program header

Each programming assignment should have the following header, with italicized text

appropriately replaced.

Note: You can copy and paste the comment lines shown here to the top of your assignment each

time. You will need to make the appropriate changes for each lab (lab number, lab name, due

date, and description).

'''

* Program or Lab #: Insert assignment name

* Programmer: Insert your name

* Due: Insert due date

* CS21A, Summer 2014

* Description: (Give a brief description for Lab4)

Lab 5: Strings - sets and dictionaries (25 points)

This lab will give you some experience with strings and sets.

Lab 5.1: Character Analysis [12 points]

1. Open the Python program CharacterAnalysis.py.

2. Fill in the code so that the program will do the following:

 Read the file’s contents (text.txt) and determines the following:

o The number of uppercase letters in the file

o The number of lowercase letters in the file

o The number of digits in the file

o The number of whitespace characters in the file

3. Save the code to a file by going to File Save.

Python File:

def main():

# Local variables

num_upper = 0

num_lower = 0

num_space = 0

num_digits = 0

data = ''

# Open file text.txt for reading.

infile = open('text.txt', 'r')

# Read in data from the file.

data = infile.read()

# Fill in this space to step through each character in

# the file.

# Determine if the character is uppercase,

# lowercase, a digit, or space, and keep a

# running total of each.

# Close the file.

infile.close()

# Display the totals.

# Call the main function.

Main()

Here is a sample run:

Uppercase letters: 29

Lowercase letters: 1228

Digits: 30

Spaces: 260

Lab 5.2: Unique Words [13 points]

1. Open the Python program UniqueWords.py.

2. Fill in the code so that the program will do the following:

 Open a specified text file

 Then displays a list of all the unique words found in the file.

Hint: Store each word as an element of a set.

3. Save the code to a file by going to File Save.

Python File:

def main():

# Get name of input file.

input_name = input('Enter the name of the input file: ')

# Open the input file and read the text.

input_file = open(input_name, 'r')

text = input_file.read()

words = text.split()

# Fill in this space to create set of unique words.

# Fill in this space to print the results.

# Close the file.

input_file.close()

# Call the main function.

main()

Submission

1. Include the standard program header at the top of your Python file.

2. Submit your files to Etudes under the “Lab 5 “ category.

CharacterAnalysis.py

UniqueWords.py

Standard program header

Each programming assignment should have the following header, with italicized text

appropriately replaced.

Note: You can copy and paste the comment lines shown here to the top of your assignment each

time. You will need to make the appropriate changes for each assignment (assignment number,

due date, and description).

'''

* Program or Lab #: Insert assignment name

* Programmer: Insert your name

* Due: Insert due date

* CS21A, Summer 2014

* Description: (Give a brief description for Lab 5)

'''

Homework is Completed By:

Writer Writer Name Amount Client Comments & Rating
Instant Homework Helper

ONLINE

Instant Homework Helper

$36

She helped me in last minute in a very reasonable price. She is a lifesaver, I got A+ grade in my homework, I will surely hire her again for my next assignments, Thumbs Up!

Order & Get This Solution Within 3 Hours in $25/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 3 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 6 Hours in $20/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 6 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

Order & Get This Solution Within 12 Hours in $15/Page

Custom Original Solution And Get A+ Grades

  • 100% Plagiarism Free
  • Proper APA/MLA/Harvard Referencing
  • Delivery in 12 Hours After Placing Order
  • Free Turnitin Report
  • Unlimited Revisions
  • Privacy Guaranteed

6 writers have sent their proposals to do this homework:

Instant Assignments
Calculation Guru
Finance Homework Help
Custom Coursework Service
Best Coursework Help
Helping Hand
Writer Writer Name Offer Chat
Instant Assignments

ONLINE

Instant Assignments

Hey, I can write about your given topic according to the provided requirements. I have a few more questions to ask as if there is any specific instructions or deadline issue. I have already completed more than 250 academic papers, articles, and technical articles. I can provide you samples. I believe my capabilities would be perfect for your project. I can finish this job within the necessary interval. I have four years of experience in this field. If you want to give me the project I had be very happy to discuss this further and get started for you as soon as possible.

$55 Chat With Writer
Calculation Guru

ONLINE

Calculation Guru

I see that your standard of work is to get content for articles. Well, you are in the right place because I am a professional content writer holding a PhD. in English, as well as having immense experience in writing articles for a vast variety of niches and category such as newest trends, health issues, entertainment, technology, etc and I will make sure your article has all the key pointers and relevant information, Pros, Cons and basically all the information that a perfect article needs with good research. Your article is guaranteed to be appealing, attractive, engaging, original and passed through Copyscape for the audience so once they start reading they keep asking for more and stay interested.

$55 Chat With Writer
Finance Homework Help

ONLINE

Finance Homework Help

I have a Master’s degree and experience of more than 5 years in this industry, I have worked on several similar projects of Research writing, Academic writing & Business writing and can deliver A+ quality writing even to Short Deadlines. I have successfully completed more than 2100+ projects on different websites for respective clients. I can generally write 10-15 pages daily. I am interested to hear more about the project and about the subject matter of the writing. I will deliver Premium quality work without Plagiarism at less price and time. Get quality work by awarding this project to me, I look forward to getting started for you as soon as possible. Thanks!

$55 Chat With Writer
Custom Coursework Service

ONLINE

Custom Coursework Service

Hey, Hope you are doing great :) I have read your project description. I am a high qualified writer. I will surely assist you in writing paper in which i will be explaining and analyzing the formulation and implementation of the strategy of Nestle. I will cover all the points which you have mentioned in your project details. I have a clear idea of what you are looking for. The work will be done according to your expectations. I will provide you Turnitin report as well to check the similarity. I am familiar with APA, MLA, Harvard, Chicago and Turabian referencing styles. I have more than 5 years’ experience in technical and academic writing. Please message me to discuss further details. I will be glad to assist you out.

$55 Chat With Writer
Best Coursework Help

ONLINE

Best Coursework Help

I am an Academic writer with 10 years of experience. As an Academic writer, my aim is to generate unique content without Plagiarism as per the client’s requirements.

$60 Chat With Writer
Helping Hand

ONLINE

Helping Hand

I am an Academic writer with 10 years of experience. As an Academic writer, my aim is to generate unique content without Plagiarism as per the client’s requirements.

$60 Chat With Writer

Let our expert academic writers to help you in achieving a+ grades in your homework, assignment, quiz or exam.

Similar Homework Questions

External and Internal Environments - Business - What challenges is zappos facing - Buying and selling business math formulas - Balanced scorecard case study coca cola - Cultural constraints in management theories - How the irish saved civilization sparknotes - Breathing underwater questions and answers - Knowing that the tension in cable bc is 725 n - Suppose that the equilibrium price in the market for widgets - What is the exact speed of light - Understanding business research terms and concepts part 2 - Coles lolly gobble bliss bombs - Bank of america merrill lynch acquisition - Mass of empty 100 ml beaker - Analytics Capstone Project - Plot a yield curve based on these data - How to palpate spine of scapula - Slim chickens slims plate calories - Dulux trade paint expert - Bodily fluid clean up procedure - Bringham company issues bonds with a par value - Abingdon medical practice glasgow - Financial Accounting Theory - Scholars research library der pharmacia lettre - The Management And Human Resources  - A factory processes 1 560 ounces - Health care policy - Box and whisker graph calculator - Scylla and charybdis odyssey - Child observation notes - Pa state police southwest training center - Purchased merchandise from boden company for $6 000 - Cedrus deodara divinely blue - All india association of industries - Que oyen los estudiantes de la residencia todas las mañanas - Sap india payroll schema documentation - Lance twomey lecture theatre - Suppose 10-year t-bonds have a yield of 5.30 - Tryst with destiny speech transcript - Prioritizing Threats Executive Summary - Types of audible notification appliances - Blue eyes brown eyes jane - World civilizations the global experience 7th edition outlines - John deere 42 hydraulic tiller manual - Rock paper scissors lizard spock java program code - The forsaken merman by matthew arnold summary - LDR531 Week 5 Strategic Change Case Study - Improvement plan presentation - Penélope muestra sus fotos a mí. - The traveling bra salesman's lesson answers - Fiona dolman new tricks - Strategic and business planning documents of bounce fitness - Case analysis in business policy and strategic management - NURSING - Ascia e training for health professionals - Business Analytiv - Re french caledonia travel - Express the following functions in cosine form - Cpni hostile vehicle mitigation - What does copper and silver nitrate make - Payout for green on roulette - Practical Connection - Area of a4 paper - Http domwebserver hitchcock org mbti - Music as poetry assignment - Stylistic choices in film - Just need to re write this in diferent words so no pagirism - WK10 ASSIGNMENT 6050 TEMPLATE - What were the most compelling topics learned in this course - Unplugged the myth of computers in the classroom pdf - How to find z score on statcrunch - Costco wholesale corporation mission business model and strategy - Keratinized stratified squamous epithelium - Order # 9346 - Week 8 - Barkhausen criterion for oscillation - Ana cumple veintiún años - What australian company is the largest surfwear manufacturer - Optus change paper bill to email - I need 1600 words on Instruction contract. - Pecking order theory investopedia - The power of habit summary chapter 2 - We are only what we always were page number - Beowulf battle with grendel - Bsbrsk501 risk management plan - Igcse history 40 mark question - Introduction to human communication: perception, meaning, and identity pdf - Businees Intelligence - Imc planning process steps - Rpm to rad s - Individual Project - Uncle sam's toolbox - Telco bella vista charge - Mass of pluto in kg - Patient medication teaching plan example - Skimming and scanning ppt - Which of the following statements best describes alcohol - Proj 587 week 5 case study - Wella color charm discontinued