Add numbers and strings in python - python

This may seem like a duplicate but the other ones don't apply. So I am trying to make a piggy bank but I cannot figure out how to add a new line while I am using numbers. Right now I am using strings because it is the only way to add a new line. However, when I add the two numbers, it adds them like string. For example, if you entered 5.93 twice. It would print "5.935.93". So, I have to convert it to a string but then I won't be able to add a new line. Here is my code:
def piggybank():
file = open('piggybank.txt','r+')
money = input('How much money are you adding?')
file.write(money + '\n')
for line in file:
money += line
print("You now have:\n", money)
file.close()
In the third line I could make money a float but then in the fourth line I wouldn't be able to add a new line. Can somebody help?

You could keep money as an Integer, but when writing, use %s. Also, if you want to write to a file, you need to make a new variable set to open('piggybank.txt', 'wb') to write to the file.:
def piggybank():
filew = open('piggybank.txt','wb')
file = open('piggybank.txt','rb')
money = input('How much money are you adding?')
filew.write('%s\n' % money)
for line in file:
money += line
print("You now have:\n%s" % money)
filew.close()
file.close()

You can do this :
def piggybank():
file = open('piggybank.txt','rb')
money = input('How much money are you adding?')
file.write(str(money) + "\n")
for line in file:
money += float(line.strip())
print("You now have:\n" + str(money))
file.close()

You can convert to floats when your doing the math.
float(money) += float(line)

Addtion could be done between numeric objects.You need to notice that input() will give you a str(string) type object. And you need to convert str to float using float().
By trail and error,I've found following solition.Refernece doc links are strip() doc, open() doc.
def piggybank():
file = open('piggybank.txt','a') #open file for appending to the end of it.
money = input('How much money are you adding? ')
file.write(money + '\n') # Write strings to text file.
file.close()
file = open('piggybank.txt','r')
sum = float(0) # initialize sum with zero value.
for line in file:
sum += float(line.strip('\n')) # srtip '\n' and convert line from str to float.
print("You now have: %s" % sum)
file.close()

Related

How do I undo what I'm currently writing before close()?

for i in range(0,5):
f = open("StudentRecords.txt", "a")
try:
f.write(input("Name: ")+"\n")
f.write(str(int(input("ID: ")))+"\n")
f.write(str(float(input("GPA: ")))+"\n")
except ValueError:
print("Error: You entered a String for ID or GPA.")
f.close()
Here for example if I tried to write a string for GPA, I will catch the error and the program will move on, but the Name and ID of the same iteration will still be written
I want it to only write if all the 3 data are valid.
As the comments said, the best approach is to validate all the data before writing anything. But if you really need to undo, you can do it by saving the file position before each record, seeking back to it, and truncating to remove everything written after.
And rather than reopening the file for each record, you should open it once before the loop. Use with to close it automatically when the block is finished.
with open("StudentRecords.txt", "w") as f:
for i in range(0,5):
try:
filepos = f.tell()
f.write(input("Name: ")+"\n")
f.write(str(int(input("ID: ")))+"\n")
f.write(str(float(input("GPA: ")))+"\n")
except ValueError:
print("Error: You entered a String for ID or GPA.")
f.seek(filepos)
f.truncate()
The simple solution is to save the inputs in variables first, and then save to file.
for i in range(0,5):
f = open("StudentRecords.txt", "a")
try:
name = input("Name: ")+"\n"
ID = str(int(input("ID: ")))+"\n"
GPA = str(float(input("GPA: ")))+"\n"
f.write(name + ID + GPA)
except ValueError:
print("Error: You entered a String for ID or GPA.")
f.close()
That being said, I would suggest updating the code a little more:
for i in range(0,5):
name = input("Name: ") + "\n"
try:
ID = str(int(input("ID: "))) + "\n"
GPA = str(float(input("GPA: "))) + "\n"
with open("StudentRecords.txt", "a") as f:
f.write(name + ID + GPA)
except ValueError:
print("Error: You entered a String for ID or GPA.")
Using with means you won't have to deal with the f.close(), among other things, and so you won't forget it. And since the name = ... line doesn't seem to need a try-except block, we can move it outside.
Others have shown you a way to validate your data, but right now the program just stops if the user makes a mistake. You really want some way for them to correct their error and continue.
To put this in your main routine would require a separate loop and try/except structure for each number, which isn't too bad right now with two values, but gets unwieldy as you add more.
So instead of repeating ourselves, let's write a function that repeats until the user enters a valid number. We can pass in the type of number we want (int or float).
def inputnum(prompt, T=float):
while True:
try:
return T(input(prompt))
except ValueError:
print(">>> You entered an nvalid number. Please try again.")
Then call that function to get your numbers (combined with some other small improvements):
with open("StudentRecords.txt", "a") as f:
for i in range(5):
name = input("Name: ")
ID = inputnum("ID: ", int)
GPA = inputnum("GPA: ", float)
f.write(f"{name}\n{ID}\n{GPA}\n")

random integers reading and writing a file. Attempting to create multiple functions using a range 0,501

Im working on some python assignments for class and I cannot answer this question. I cannot find the error in my code. The error I receive is TypeError: 'function' object is not iterable. The question is:
a. Random Number File Writer Function
Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file.
b. Random Number File Reader Function
Write another function that reads the random numbers from the file "random.txt", displays the numbers, then displays the following data:
The total of the numbers
The number of random numbers read from the file
c. Main Function
Write a main function that asks the user about how many random number the user wants to generate. It them calls the function in a. with the number the user wants as an argument and generates random numbers to write to the file. Next, it calls the function in b.
Here is my code:
import random
def random_Write(num):
# Open a file for writing
file_w = open('random.txt', 'w')
for i in range(0,num):
rand = random.randrange(1,501)
file_w.write(str(rand) + '\n')
#closing file
file_w.close()
def random_Read():
# Reading from file
readFile = open('random.txt', 'r')
count = 0
total = 0
for lines in random_Read:
count +=1
total += float(lines)
print ('number count: ', str(count))
print ('The numbers add up to: ', str(total))
readFile.close()
def main():
num = int(input("How many numbers would you like to generate?: "))
random_Write(num)
random_Read()
main()
Quite simple actually, in random_Read(), in the for loop, instead of for lines in random_Read: put in for lines in readFile.readlines(): Why are you getting the error? because of a simple typo because you said random_Read which is the function...
Your function random_Read has some mistakes. Here is a corrected version:
def random_Read():
#Reading from file
readFile = open('random.txt', 'r')
count = 0
total = 0
#You were looping with random_Read. I changed to readFile.readlines()
#so you get a list with all of the lines of the file.
for lines in readFile.readlines():
count +=1
total += float(lines)
print ('number count: ', str(count))
print ('The numbers add up to: ', str(total))
#only call .close() once, at he end of the function
readFile.close()

how do you write integers to an external file in python

i am trying to create a leaderboard for a game and need to decide if a players score is there high score or not but every time i try to run the program it says " '>' not supported between instances of 'int' and 'str'" what do i do
heres my code:
score = 0
s = open("highscore.txt", 'r')
scores = s.read()
s.close()
if score > (scores):
highscore = score
s = open("highscore.txt", 'w')
s.write(highscore)
s = open("highscore.txt", 'r')
scores = s.read()
s.close()
print(f"your score was {score}")
When you use a read() method it returns a string. That means value in "scores" is a string and you cannot compare a String with an integer. Hence you need to typecast it.
if score > int(scores):
highscore = score
You will need to convert to a string and back again.
For example, here is how you could write the number to a file. By calling str(highscore) it converts it to the equivalent string (e.g. '0'). This can then be written to the file.
with open("highscore.txt", 'w') as s:
s.write(str(highscore))
You can optionally also add a newline if you use s.write(str(highscore) + '\n'), but it will work without it.
Here is how you would read the whole contents of the file - i.e. the string that you wrote - and convert it to an integer using int(). This relies on the fact that the file only contains the number and nothing else.
with open("highscore.txt") as s:
highscore = int(s.read())
Note also the pattern for reading and writing files using with. It is probably best to learn this as-is for now, but note that you do not need a close statement when doing it this way.

find out how many times does that inputed sign appear in the document

In this program, I want print a document; count the lines and the number of a specific character you ask for in the input part. I want to find out how many times does that inputed sign appear in the document.
But the program returns the same number as for num_lines while the number is not the same. Why is that so? How to make it work and what are some other ways of getting same results? Thanks in advance!
file = open('notes.txt', 'r')
for i in file:
print (i)
num_lines = sum(1 for line in open('notes.txt'))
print('The number of lines in the document is:', num_lines)
signs=input('Input the sign you want to count:')
num_sign = sum(1 for signs in open('notes.txt'))
print('The number of signs in the document is:', num_sign) ```
When you write:
for signs in open('notes.txt')
You override your previously declared variable signs.
You can replace it with:
signs = input('Input the sign you want to count:')
num_sign = 0
for line in open('notes.txt'):
num_sign += line.count(signs)
I'd do this:
signs = input('Input the sign you want to count:')
file = open('notes.txt', 'r')
f = file.read()
print('lines:', len(f.split('\n')))
print('signs:', f.count(signs))

making lists from data in a file in python

I'm really new at python and needed help in making a list from data in a file. The list contains numbers on separate lines (by use of "\n" and this is something I don't want to change to CSV). The amount of numbers saved can be changed at any time because the way the data is saved to the file is as follows:
Program 1:
# creates a new file for writing
numbersFile = open('numbers.txt', 'w')
# determines how many times the loop will iterate
totalNumbers = input("How many numbers would you like to save in the file? ")
# loop to get numbers
count = 0
while count < totalNumbers:
number = input("Enter a number: ")
# writes number to file
numbersFile.write(str(number) + "\n")
count = count + 1
This is the second program that uses that data. This is the part that is messy and that I'm unsure of:
Program 2:
maxNumbers = input("How many numbers are in the file? ")
numFile = open('numbers.txt', 'r')
total = 0
count = 0
while count < maxNumbers:
total = total + numbers[count]
count = count + 1
I want to use the data gathered from program 1 to get a total in program 2. I wanted to put it in a list because the amount of numbers can vary. This is for an introduction to computer programming class, so I need a SIMPLE fix. Thank you to all who help.
Your first program is fine, although you should use raw_input() instead of input() (which also makes it unnecessary to call str() on the result).
Your second program has a small problem: You're not actually reading anything from the file. Fortunately, that's easy in Python. You can iterate over the lines in a file using
for line in numFile:
# line now contains the current line, including a trailing \n, if present
so you don't need to ask for the total of numbers in your file at all.
If you want to add the numbers, don't forget to convert the string line to an int first:
total += int(line) # shorthand for total = total + int(line)
There remains one problem (thanks #tobias_k!): The last line of the file will be empty, and int("") raises an error, so you could check that first:
for line in numFile:
if line:
total += int(line)

Categories