How do I get my loop to write to the file until I stop the loop?
For example
outFile = "ExampleFile.txt", "w"
example = raw_input(" enter number. Negative to stop ")
while example >= 0:
example = raw_input("enter number. Negative to stop")
outFile.write("The number is", example,+ "\n")
I feel like im hitting it close but I'm not sure. I wasn't sure how to search for this question in paticular. Sorry, I keep getting a error stating that the function takes 1 argument, when I enter more than 2.
import os.path
outFile = open("purchases.txt","w")
quantity = float(raw_input("What is the quantity of the item :"))
cost = float(raw_input("How much is each item :"))
while quantity and cost >= 0:
quantity = float(raw_input("What is the quantity of the item :"))
cost = float(raw_input("How much is each item :"))
total = quantity * cost
outFile.write("The quantity is %s\n"%(quantity))
outFile.write("the cost of the previous quality is $s\n" %(cost))
outFile.close()
outFile = open("purchases.txt","a")
outFile.write("The total is ",total)
outFile.close()
when you write:
outFile = "ExampleFile.txt", "w"
you create a tuple, not a file object.
You probably meant to write:
outFile = open('ExampleFile.txt','w')
Of course, you could do this a little better using a context manager:
with open('ExampleFile.txt','w') as outFile:
#...
Your code has a second error:
outFile.write("The number is", example,+ "\n")
baring the SyntaxError (,+), file.write takes only 1 argument. You probably wanted something like:
outFile.write("The number is {0}\n".format(example))
or using the old style of string formatting (as requested):
outFile.write("The number is %s\n"%(example))
Related
Edit the program provided so that it receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program should print:
The Average and The Sum
I've been able to get it to print the sum of the numbers put in but I think it is messing up when trying to calculate the average. I really need some help with this. try inputting 100 59 37 21 and you will see what I mean
data = input("Enter a number: ")
number = float(data)
while data != "":
number = float(data)
theSum += number
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum // number
print("The average is", average)```
As Mat and Nagyl have pointed out in the comments you need to keep track of how many numbers were given and divide the sum by that to get the average
data = input("Enter a number: ")
number = float(data)
numbersGiven = 0
theSum = 0
while data != "":
number = float(data)
theSum += number
numbersGiven += 1
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum / numbersGiven
print("The average is", average)
Notice that the first input isn't counted (I start with numbersGiven = 0) but the empty input at the end is counted so it gives the correct count.
you can use these code too!
instead of writing the formula for average you can use statistics module
import statistics
the code below asks you the numbers how many times you wrote in the number of datas
number_of_datas=int(input("number of inputs asking: "))
datas=[]
The following code takes the number from the number of times you wrote in the number of inputs
also you can write a Specified number instead of getting an input
for i in range(number_of_datas):
data = float(input("Enter a number: "))
datas.append(data)
fmean is float average
average=statistics.fmean(datas)
print(average)
numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
file = open("scores.txt","w")
for loop in range(numberofbands):
name = input("\nEnter the name of the band: ")
votes = input("Enter how many votes that band received: ")
file.write(name + "," + votes + "," + "\n")
file.close()
number_of_lines = len(open("scores.txt").readlines( ))
def removebottom3():
#code to remove bottom 3 here
removebottom3()
The first part writes the band's name and score to the file.
I want the code to remove the lowest 3 scoring bands from the file. There will be a function for that.
How can I do this?
Thanks in advance.
You are quite off. Let me help you.
First, consider using Counter, it is meant for this kind of cases.
Second, try dividing the script logic into blocks (divide and conquer!), first get the data, then sort and remove the last 3, and only at the end write the results to a file.
Here is an example of the implementation.
from collections import Counter
numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
scores = Counter()
for n in range(numberofbands):
name = input("\nEnter the name of the band: ")
vote = input("Enter how many votes that band received: ")
scores.update({name:int(votes)})
#remove the last 3
final = scores.most_common()[:-3]
#write to file
with open('scores.txt', 'w') as f:
for name, vote in final:
f.write(f'{name},{vote}\n')
since you are already reading all the lines from the file,
number_of_lines = len(open("scores.txt").readlines( ))
you can use sorted to sort your lines by score,
lines = open("scores.txt").readlines()
sorted(lines,
key=lambda x : float(x.split(",")[1]),
reverse = True)
New to Python, doing Introduction to Programming with Python with Grok Learning.
I have this problem where I need to take input, convert to a list, convert to integers and then collect the sum of the integers. Here's what I have so far:
expenses = input("Enter the expenses: ")
expenses.split()
for expense in expenses:
print(int(expenses))
total = sum(expenses)
print("Total: $" + total)
I was told I have to loop over the array and then convert to integers. But I have no idea what this means, can someone please show me?
Since you already wrote that for loop I'm assuming you know what it means, so you simply need to create another list, for storing the int values:
intValues = []
for expense in expenses:
intValues.append(int(expense))
and then print(sum(intValues)) works the same. You could do the same in just one line using Python's list comprehension syntax:
intValues = [int(expense) for expense in expenses]
Firstly you need to indent total=sum(expenses) into the for loop and need to save the split result in a variable so modified program is:
expenses = input("Enter the expenses: ")
for expense in expenses.split:
print(int(expense))
total = sum(expense)
print("Total: $" + total)
Try this:
expenses = input('Enter the expenses: ')
expenses = expenses.split()
total = 0
for expense in expenses:
total += int(expense)
print('Total: $' + str(total))
When I did this challenge, this was my code:
money = input("Enter the expenses: ")
money = money.split()
total = sum([int(i) for i in money ])
print("Total:", "$" + str(total))
The first line is just the input of money. The second line splits each number into a list. The 3rd line calculates the sum of the input as an integer, then the 4th changes it back to a string and prints it.
To fix your error, try this:
expenses = input("Enter the expenses (separated by spaces): ")
total = 0
for expense in expenses.split():
total += int(expense)
print(expense)
print( "Total: $" + str(total) )
A sample session:
Enter the expenses (separated by spaces): 12 34 56
12
34
56
Total: $102
I have encountered an error when writing my program and would like some help with it. The program has to replace a specific segment of the line with a calculated value. The segment in which I am talking about is the third index in a line, formatted like this:
Product01, 12346554, 15, 6
I am having the program calculate the value in which I want to replace with the final value but no matter how much I seem to try, my code frequently gives errors. For an example, I have used seek to try and move the cursor to allow myself to edit this value, however with the following code:
Total = 0
receipt = open("Receipt.txt", "w")
while True:
try:
Prod_Code = input("Enter a code or Done to get your final receipt: ")
if len(Prod_Code) == 8:
int(Prod_Code)
with open("Data Base.txt", "r+") as searchfile:
for line in searchfile:
if Prod_Code in line:
print(line)
Quantity = input("What quantity of this product do you want? ")
Total += float(line.split(",")[2]) * int(Quantity)
print(Quantity)
print(Total)
receipt.write(line)
print(line.split(",")[3])
W = int(line.split(",")[3]) - int(Quantity)
print(W)
L = (line)
L.seek(27, 0)
L.write(str(W))
elif Prod_Code == "Done":
receipt.close()
with open("Receipt.txt", "r") as datafile:
for item in datafile:
print(item.split(",")[1])
print(item.split(",")[2])
print("Your total cost is £", Total)
input("Press Enter to exit:")
exit()
else:
print("Incorrect length, try again")
except ValueError:
print("You must enter an integer")
However, when I run it this is the error that I get:
AttributeError: 'str' object has no attribute 'seek'.
I was wondering if anyone could help, and/or provide a different answer to my problem? Thanks in advance.
I am trying to build a list with raw inputs.
while True:
inp = raw_input("Enter a number: ")
#edge cases
if inp == "done" : break
if len(inp) < 1 : break
#building list
try:
num_list = []
num = int(inp)
num_list.append(num)
except:
print "Please enter a number."
continue
#max and min functions
high = max(num_list)
low = min(num_list)
#print results
print "The highest number: ", high
print "The lowest number: ", low
print "Done!"
At the moment it seems to only save one of the inputs at a time and therefore the the last raw input is printed as both the max and min.
Any ideas? I am new to Python and could use some direction. So far I have been unable to find the answer in StackOverflow or in the Python documentation.
Thanks in advance!
That's because you keep erasing the list with each iteration. Put num_list = [] outside the while loop:
num_list = []
while True:
...
You should also put these two lines:
high = max(num_list)
low = min(num_list)
outside the loop. There is no reason to keep executing them over and over again.