need a little help from someone who understand code - python

import random
def main():
random1 = random.randrange(10,21,1)
create_file(random1)
process_file()
def create_file( random1):
generate = open('random_numbers.txt','w')
for x in range(random1):
random2 = random.randrange(1,101,1)
generate.write(str(random2)+'/n')
generate.close()
def process_file():
generate = open('random_numbers.txt','r')
entries = 0
total = 0
for x in generate:
entries += 1
integer = int(x)
total = integer + total
mean= sum/entries
print("There are",(entries),"entries in the file.")
print("The sum total of all the entries is ",(total))
print("The average of all the entries is ", format((mean),'.2f'))
main()
This keeps giving me this error and ive don't understand why the integer value is not working. I tried to reduce the integer=int(x) to integer = x but then I couldn't use the x as an integer and that's a problem in it of itself
Traceback (most recent call last):
File "U:\john oconnor lab 6.2.py", line 41, in <module>
main()
File "U:\john oconnor lab 6.2.py", line 20, in main
process_file()
File "U:\john oconnor lab 6.2.py", line 35, in process_file
number = int(x)
ValueError: invalid literal for int() with base 10: '29/n59/n17/n2/n8/n14/n2/n14/n9/n21/n5/n25/n15/n47/n'

generate.write(str(random2)+'/n')
Are you trying to write a newline at the end there? You got the escape sequence wrong.
generate.write(str(random2)+'\n')
This ought to fix the problem in process_file, since "random_numbers.txt" will now be filled with digits separated on their own individual lines, rather than being digits separated by a slash and the letter N.
Also, this line:
mean= sum/entries
Should use the variable total instead of the built-in function sum.
mean= total/entries

When you do this for x in generate: your are getting every line of your file. So, as you know, every line of your file is something like '15\n' or '67\n'.
You should do this:
for x in generate:
entries += 1
x = x.strip()
integer = int(x)
total = integer + total
mean= sum/entries
x.strip() will eliminate the term '\n' of every line.
Also be careful with the difference between '\n' and '/n'

Related

outputting strings and function outputs in Python

I am coding a simple program to add all positive integers not greater than a given integer n. My code:
print("Enter an integer:")
n=input()
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
#print("1+2+3+...+"+str(n)+"="+str(add(n)))
print(add(100))
The function works.
Why does the line in the one line comment not work, if I remove the hash tag? It should - there is a concatenation of four strings. Thank you.
EDIT: the whole output:
Enter an integer:
12
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "<string>", line 6, in add
TypeError: can only concatenate str (not "int") to str
>
input() returns a string. You are passing n=input() which is a string so it is not working as expected.
change it to n=int(input())
Also sum is a reserved keyword and it will be best to change that to a different name
input returns a string, so add(n) will look something like add("1234"). Then, range(k+1) inside the function will be range("1234" + 1), but "1234" + 1 is an error since it's not possible to add a string and a number.
The problem exists in your input, it's current data type is str, and must be converted into int.
Also, it's best if you use .format() when printing strings.
print("Enter an integer:")
n = int(input())
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
print("1 + 2 + 3 + ... + {} = {}".format(n, add(n)))

How can I correct an "'int' object is not iterable" error using Python?

def square_each(nums):
import math
for i in range(len(nums)):
nums[i] = nums[i]**2
def sum_list(nums):
for values in nums:
sums = sum(values)
print(sums)
def to_numbers(str_list):
numbers = [int(strings) for strings in str_list]
return numbers
def main():
print("This program computes the sum of the squares of numbers read from a file.")
filename = input("Please enter the file name:")
file = open(filename, 'r')
line = file.readline()
list1 = line.split(" ")
numbers = to_numbers(list1)
square_each(numbers)
sums = sum_list(numbers)
print("The sum of the squares of the numbers in the file is{0}".format(sums))
main()
Traceback (most recent call last):
File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 35, in <module>
File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 32, in main
sums = sum_list(numbers)
File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 16, in sum_list
sums = sum(values)
TypeError: 'int' object is not iterable
I opened a file with a list of strings(numbers). Then I used three functions to convert string to numbers, square each number, and sum the list of numbers. The last function, main(), included those three functions. But I have an 'int' object is not iterable error. How can I correct this error here?
To elaborate on the comment above, you don't need to run your list through a for loop as the sum function will handle that for you. In actual fact, your sum_list function is quite redundant.
The working function looks like:
def sum_list(nums):
sums = sum(nums)
return sums
I'd eliminate that function and just do:
def square_each(nums):
import math
for i in range(len(nums)):
nums[i] = nums[i]**2
def to_numbers(str_list):
numbers = [int(strings) for strings in str_list]
return numbers
def main():
print("This program computes the sum of the squares of numbers read from a file.")
filename = input("Please enter the file name:")
file = open(filename, 'r')
line = file.readline()
list1 = line.split(" ")
numbers = to_numbers(list1)
square_each(numbers)
sums = sum(numbers) # <- this instead of your function presuming that you are feeding a list
print("The sum of the squares of the numbers in the file is{0}".format(sums))
main()
Some reading for the sum function in python:
http://interactivepython.org/runestone/static/pythonds/Recursion/pythondsCalculatingtheSumofaListofNumbers.html
The reason I chose this example is because it shows what I believe your function is trying to achieve - if your input was not already a list; but in your case, it is not really required.

Stranger error with the .join function

I've been trying to write a program which finds the roots of an inputted mathematical function. I've only just started, so what I show here is only the start, and there are unused variables.
Here I wrote a function which is supposed to replace the term 'x' in a function with a value you input, say, 100. Here is the code:
code = list(input("Enter mathematical function: "))
lowBound = int(input("Enter lower bound: "))
upBound = int(input("Enter upper bound: "))
def plugin(myList, value):
for i in range(len(myList)):
if myList[i] == 'x':
myList[i] = value #replaces x with the inputted value
return ''.join(myList) #supposed to turn the list of characters back into a string
print(plugin(code,upBound))
But when I run the program, I get the error:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 9, in plugin
TypeError: sequence item 0: expected str instance, int found
(I'm using an online programming platform, so the file is just called 'python')
This doesn't make any sense to me. myList should not be an int, and even if it was the right data type (str), it should be a list. Can someone explain what's going on here?
You are replacing a str type (or character) with an int type.
Try this instead:
myList[i] = str(value)
You can only join an iterable of strings
return ''.join(str(x) for x in myList)
Or, more succinctly. Remove the function
print(''.join(str(upBound if x =='x' else x) for x in code)

How do I add up total numbers in a text file for python?

I've been getting stuck in the total_num() function as it gives the error
"ValueError: invalid literal for int() with base 10: ''"
I know how to do it if its a defined list but if its set by the user I get confused.
def total_num():
total = 0
num_file = open("num_list.txt", "r")
line = num_file.read()
while line != "":
num1 = int(num_file.readline())
total = total + num1
print total
def read_num():
num_file = open("num_list.txt", "r")
for line in num_file:
print line.rstrip("\n")
def write_num():
num = input("Enter a number: ")
num_file = open("num_list.txt", "w")
num_consec = 0
for x in range(num):
num_consec = num_consec + 1
num_file.write(str(num_consec)+ "\n")
num_file.close()
def main():
write_num()
read_num()
total_num()
main()
The error is because you are getting an empty string from your text file. Look at this bit of code; you are reading the whole file into memory.
line = num_file.read()
while line != "":
Over here, unless you opened an empty file line != "" you are comparing the whole file with an empty string. So you will keep on looping until your num1 = int(num_file.readline()) reads an empty line from the file.
You can find the solution if you look at your read_num method.
for line in num_file:
try:
total += int(line)
except ValueError:
print "Invalid data in ", line
By using try except you are able to handle the situation where the file might contain other invalid texts.
You are reading the file in an odd way - namely, twice. read() puts the entire file contents into a string. If you repeatedly check whether there are characters in it, and then never change it, it will either not execute or loop infinitely.
Using input() to get a number will work, but it's better to use raw_input() and cast with int() for safety. Also, xrange() is a better practice than range() in Python 2. You don't need to keep a manual counter if you're already iterating over range(), either.
Overall, your code could be condensed to this:
def write_num():
num = int(raw_input("Enter a number: "))
with open("num_list.txt", "w") as output:
for x in xrange(1, num+1):
output.write(str(x) + "\n")
def read_num():
with open("num_list.txt") as f:
numbers = map(int, f)
for number in numbers:
print number
return numbers
def main():
write_num()
print sum(read_num())
main()

What is IndexError? I keep Getting It

Here is my code:
quote = input("Enter a Sentence: ")
a = len(quote)
counter = 0
counter1 = 0
reverse = a
print("The Length of the sentence is",a,"characters long!")
for x in range(0,a):
if str.isspace(quote[x]) == True:
counter = counter + 1
print("The Length of the sentence is",a - counter,"characters long (excluding space...)!")
for x in range(0,a):
if str.isupper(quote[x]) == True:
counter1 = counter1 + 1
print("The number of Upper Case Characters in the sentence is",counter1,"characters!")
print("The number of Lower Case Characters in the sentence is",a-counter1,"characters long!\n")
while reverse >= 1:
r = reverse
print(quote[r])
r = r - 1
It's aim is to find everything about that sentence, but the only problem is the 'While' loop at the bottom. It doesn't seem to work, and it's aim is to 'inverse' the sentence. However, it gives my an error which looks a bit like this:
Traceback (most recent call last):
File "C:\Documents and Settings\ususer\My Documents\Downloads\StringStuff.py", line 27, in <module>
print(quote[r])
IndexError: string index out of range
What Am I doing wrong? Please help!
Python is 0-indexed, so the first character of a string is str[0] and the last is str[len(str) - 1]. So, since you start with reverse = len(quote), at the end you are doing quote[len(quote)], which is one past the end of the string.
So, you should probably start with reverse = a - 1 and your loop at the end should look something like:
while reverse >= 0:
print(quote[reverse])
reverse = reverse - 1
You have run into the common problem that Python starts indexing from 0, but returns the lenght of a list as a valid integer counted from 1. This results that for any list, l[len(l)] will give you IndexError, because a list of length 10 will only have indexes 0...9.
All you have to do is to initialize reverse = len(quote)-1.
You also have to descend your loop variable inside the while loop, so use reverse-=1 instead of r=r-1.

Categories