Program to display total of numbers created in a file python - python

I have written the code below to display the following:
A number of random integers to be chosen by the user
The total of these integers
The total number of numbers
The problem lies in the display of the total, it is concatenating the integers, even though I believe I have used int() correctly.
# This program will write a series of random numbers to a file, and then read and print these numbers
# total of all numbers will be displayed
# number of files read from the file will be displayed
import random
def randomNumberMaker():
random_numbers = open('randoms.txt', 'w')
try:
for i in range(int(input('How many random numbers? :'))):
line_1 = str(random.randint(1, 501))
random_numbers.write(line_1)
print(line_1)
except bad_number:
print("A non integer was entered, sorry.")
random_numbers.close()
randomNumberMaker()
random_number_file = open("randoms.txt", "r")
total= 0
number_of_numbers= 0
line = random_number_file.readline()
while line != "" :
number_of_numbers += 1
number= int (line)
total += number
print(number)
line = random_number_file.readline()
print ("\nThe total number of numbers:" + str(total) +\
"\n There are " + str(number_of_numbers)+ \
" numbers in the file")

Just add endline at the end of each random number.
line_1 = str(random.randint(1, 501)) + '\n'
Since you didn't add any endline character, your input file contains only 1 line of input, and what your code really does is to convert that 1 concatenated string into an int and prints it out.

You used int() correctly, but the problem is in your randoms.txt file. You write all your numbers in a single line without any spaces, so there is no way for the program to know, where to split your numbers. Adding a line break after you write each number fixes the problem:
random_numbers.write(line_1 + "\n")

There is a problem in your randomNumberMaker() function. You are writing all numbers in one line and thus always getting back only one number, which is a textual concatenation of all random numbers.
Change the line
random_numbers.write(line_1)to random_numbers.write(line_1+"\n")and everything will work as expected.

Related

How do I make it so that the print statement stays on the same line while having my input to next one down

So I want to make it so the print output is in one line, and I did that using end, but my input happens on the same line Shown here. I used the \n on the int, but that indents the program one line when I run it.
while True:
guess = int(input("Number of characters: "))
for i in range(int(guess)):
print(random.choice(letters), end='',)
You do want to use end='' so that all of the print statements in your loop print to the same line. But then, after your loop, you want to output a newline before you accept more input. So you want this:
while True:
guess = int(input("Number of characters: "))
for i in range(int(guess)):
print(random.choice(letters), end='',)
print()
Sample run:
Number of characters: 7
acdeeda
Number of characters: 24
dbffdeebgccdfbfcfdgdbbcf
Number of characters:

Unsupported Opperand Type Error

(EDITED)
I am trying to make a piggybank by saving the previous money amounts to a file so you can access how much money you have previously had. But, it is giving me an error(see title). Please don't mark this as a duplicate because I already checked the others and they don't apple to my problem. Here is my code:
def piggybank():
newamount = 0.0
file = open('piggybank.txt','r+')
addedmoney = input('How much money are you adding?')
file.write(addedmoney + '\n')
for line in file:
newamount += line
print("You now have:\n", newamount)
Basically I am saying that the new amount is 0. Then I open my file in read and write mode and ask how much the user wants to add. Then I add it to a new line on my file and add up everything in the file. Lastly, I print the sum. However, this does not work because I keep getting the error. Please Help!
(I am sort of a noob at Python and Stack Overflow because I am 13 and just started learning.)
Here is my new 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()
If you look at my original code, I added a newline to money and I did that here as well. However, it adds the money strings as if they were strings so it gives '5.005.00' if you enter 5.00 twice. Does anyone know how to add a new line if you want to print numbers and not strings?
It's because your line is string and newamount is number. That's why you get the error. You have to convert the string to number first before proceeding the math calculation.
def piggybank():
newamount = 0.0
file = open('piggybank.txt', 'r+')
addedmoney = input('How much money are you adding?')
file.write(str(addedmoney) + '\n')
file.seek(0)
for line in file:
newamount += float(line)
print("You now have:\n", newamount)
def piggybank():
newamount = 0.0 # newamount is a floating point number
file = open('piggybank.txt','r+')
addedmoney = input('How much money are you adding?')
file.write(addedmoney + '\n')
for line in file: # line is a string
newamount += line # you are trying to add a floating point number to a string, so the error (I assume) happens here.
print("You now have:\n", newamount)
In conclusion, the operands do not match. First you must convert the string to a floating point number like so:
newamount += float(line.strip()) # strip removes trailing whitespace
On another note, why write addedmoney to the file if you only need to store the total? You can try calculating newamount first and then proceed write that result.

The String is Not Read Fully

I wrote a programme to generate a string of number, consisting of 0,1,2,and 3 with the length s and write the output in decode.txt file. Below is the code :
import numpy as np
n_one =int(input('Insert the amount of 1: '))
n_two =int(input('Insert the amount of 2: '))
n_three = int(input('Insert the amount of 3: '))
l = n_one+n_two+n_three
n_zero = l+1
s = (2*(n_zero))-1
data = [0]*n_zero + [1]*n_one + [2]*n_two + [3]*n_three
print ("Data string length is %d" % len(data))
while data[0] == 0 and data[s-1]!=0:
np.random.shuffle(data)
datastring = ''.join(map(str, data))
datastring = str(int(datastring))
files = open('decode.txt', 'w')
files.write(datastring)
files.close()
print("Data string is : %s " % datastring)
The problem occur when I try to read the file from another program, the program don't call the last value of the string.
For example, if the string generated is 30112030000 , the other program will only call 3011203000, means the last 0 is not called.
But if I key in 30112030000 directly to the .txt file, all value is read. I can't figure out where is wrong in my code.
Thank you
Some programs might not like the fact that the file doesn't end with a newline. Try adding files.write('\n') before you close it.

how do I differentiate between str and int and is this what ValueError: invalid literal for int() with base 10: error means?

choice = input (" ")
choice = int(choice)
if choice == 2:
print ("What class are you in? Please choose (class) 1, 2 or 3.")
Class = int(input ())
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
ScoreCount = str(ScoreCount)
c1.write(myName + "-" + ScoreCount)
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
if choice == 3:
row[1]=int(row[1]) #converts the values into int.
row[2]=int(row[2])
row[3]=int(row[3])
row[4]=int(row[4])
if choice == 4:
WMCI= 1
print ("Thank You. Bye!")
So when this code is actually run it outputs an error which I don't understand:
ValueError: invalid literal for int() with base 10:#(myName-score)
How to fix this and what does this error mean in simple terms?
You've got 2 bugs.
The first is when you store your score into the csv, you're converting ScoreCount into a string, and keeping it that way. You need to let the conversion be temporary for just the job:
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
c1.write(myName + "-" + str(ScoreCount))
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
That'll fix it with Class 1, you'll need to do 2 & 3. Your second bug is when you're reading the scores from the file, you've stored them as: "Name-5" if the person called Name had scored 5. That means you can't convert them as a whole entity into a number. You'll need to split the number part off. So in min max, where you've got:
row[0] = int (row[0])
It needs to become:
row[0] = int(row[0].split("-")[1])
But from there I can't figure out your logic or what you're trying to achieve in that section of code. It'll get rid of the current error, but that part of your code needs more work.
Explaining the right hand side of the above line of code by building it up:
row[0] # For our example, this will return 'Guido-9'
row[0].split("-") # Splits the string to return ['Guido','9']
row[0].split("-")[1] # Takes the second item and returns '9'
int(row[0].split("-")[1]) # Turns it into a number and returns 9
split("-") is the part you're likely to not have met, it breaks a string up into a list, splitting it at the point of the "-" in our example, but would be at the spaces if the brackets were left empty: split() or any other character you put in the brackets.
You are probably trying to convert something that can't be converted to an int for example
int("h")
This would give the base 10 error which you are getting

Converting/concatenating integer to strying with python

I'm trying to read the last line from a text file. Each line starts with a number, so the next time something is inserted, the new number will be incremented by 1.
For example, this would be a typical file
1. Something here date
2. Something else here date
#next entry would be "3. something date"
If the file is blank I can enter an entry with no problem. However, when there are already entries I get the following error
LastItemNum = lineList[-1][0:1] +1 #finds the last item's number
TypeError: cannon concatenate 'str' and 'int objects
Here's my code for the function
def AddToDo(self):
FILE = open(ToDo.filename,"a+") #open file for appending and reading
FileLines = FILE.readlines() #read the lines in the file
if os.path.getsize("EnteredInfo.dat") == 0: #if there is nothing, set the number to 1
LastItemNum = "1"
else:
LastItemNum = FileLines[-1][0:1] + 1 #finds the last items number
FILE.writelines(LastItemNum + ". " + self.Info + " " + str(datetime.datetime.now()) + '\n')
FILE.close()
I tried to convert LastItemNum to a string but I get the same "cannot concatenate" error.
LastItemNum = int(lineList[-1][0:1]) +1
then you've to convert LastItemNum back to string before writing to file, using :
LastItemNum=str(LastItemNum) or instead of this you can use string formatting.

Categories

Resources