Attempting to place the printed statement into columns - python-3.x

I am having trouble trying to put the output into columns. I have tried using %d but I keep getting TypeError: not all arguments converted during string formatting. what I have so far:
ids = []
scores = []
grades = []
items = []
get input until stopped by 0
id_Test = eval(input("Enter an ID number:"))
while id_Test != 0:
score = eval(input("Enter a score(0.0 - 100.0):"))
ids.append(id_Test)
scores.append(score)
id_Test = eval(input("Enter another ID number:"))
gets the average score
avg_score = sum(scores) / len(scores)
Receives a list of scores and appends the corresponding grade 2 grades list
for score in scores:
if score > avg_score + 10:
grades.append('A')
elif score > avg_score + 5:
grades.append('B')
elif score > avg_score - 5:
grades.append('C')
elif score > avg_score - 10:
grades.append('D')
else:
grades.append('F')
Headers for Columns
print("ID SCORE GRADE")
Columns
for item in range(len(ids)):
print('%%%8d' % (ids[item], scores[item], grades[item]))
I keep getting this TypeError:
Traceback (most recent call last):
File "/Users/Ambriorix/Desktop/$RECYCLE.BIN/LAB3.py", line 40, in <module>
print('%%%8d' % (ids[item], scores[item], grades[item]))
TypeError: not all arguments converted during string formatting

Related

Why won't my program define the variable even after using a return statement?

I am currently doing a challenge on hackerrank.com (https://www.hackerrank.com/challenges/finding-the-percentage/problem) about finding a percentage given a student's grade.
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
over = len(scores)
def average_score():
average = 0
if query_name == _ in name:
for scores in student_marks:
for grade in scores:
average = average + grade
return average
average_score()
print(average / over)
I'm having a hard time making sense as to why the program won't recognize the variable (average) even after using a return statement.
Traceback (most recent call last):
File "Solution.py", line 22, in <module>
print(average / over)
NameError: name 'average' is not defined
Whenever I try to run the program, a NameError pops up.
You are not storing the result of the call to average_score. Change it to this:
average = average_score()

IndexError: list index out of range: When try to display digits into English words

I am new to learning programming and I tried to make a simple prg to display input digits into English upto 999, it works correctly till 99 but when it comes to 100's than i get following error:
please help me to understand what I am doing wrong?
print('Print digits into english upto 999')
words_upto_ninteen=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Tweleve','Thirteen','Fourteen','Fifteen', 'Sixteen','Seventeen','Eighteen','Nineteen']
words_tens=['','','Twenty','Thirty','Fourty','Fifty','Sixty','Seventy','Eighty','Ninty']
words_hundreds=[' ','One Hundred','Two Hundred','Three Hundred','Four Hundred','Five Hundred','Six Hundred','Seven Hundred','Eight Hundred','Nine Hundred']
n=int(input("Please enter digits 0 to 999:"))
output=''
if n==0:
output='zero'
elif n<=19:
output=words_upto_ninteen[n]
elif n<=99:
output=words_tens[n//10]+" "+ words_upto_ninteen[n%10]
elif n<=999:
output=words_hundreds[n//100]+" "+ words_tens[n//10]+" "+ words_upto_ninteen[n%10]
else:
output=print('Please enter value upto 999')
print(output)
print('###########################################################################################')
Sample Output:
Please enter digits 0 to 999:433
Traceback (most recent call last):
File "D:/python learning/projects/4flow control/rough2.py", line 21, in <module>
output=words_hundreds[n//100]+" "+ words_tens[n//10]+" "+ words_upto_ninteen[n%10]
IndexError: list index out of range
This solution would work:
print('Print digits into english upto 999')
words_upto_ninteen=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Tweleve','Thirteen','Fourteen','Fifteen', 'Sixteen','Seventeen','Eighteen','Nineteen']
words_tens=['','','Twenty','Thirty','Fourty','Fifty','Sixty','Seventy','Eighty','Ninty']
words_hundreds=[' ','One Hundred','Two Hundred','Three Hundred','Four Hundred','Five Hundred','Six Hundred','Seven Hundred','Eight Hundred','Nine Hundred']
n=int(input("Please enter digits 0 to 999:"))
output=''
if n==0:
output='zero'
elif n<=19:
output=words_upto_ninteen[n]
elif n<=99:
output=words_tens[n//10]+" "+ words_upto_ninteen[n%10]
elif n<=999:
output=words_hundreds[n//100]+" "+ words_tens[(n//10)%10]+" "+ words_upto_ninteen[n%10]
else:
output=print('Please enter value upto 999')
print(output)
print('###########################################################################################')
You made a mistake in words_ten[n//10] in fourth condition. Hope it helps :)
When the error IndexOutOfRange is encountered, an array field is accessed which does not exist. If the number 100 is reached, the case elif n <= 999: is reached for the first time. We have n = 100, we also have
output = words_hundreds [100 // 100] + "" + words_tens [100 // 10] + "" + words_upto_ninteen [100% 10]
and thus
output = words_hundreds [1] + "" + words_tens [10] + "" + words_upto_ninteen [0]. However, the words_tens array will count to the words_tens [9] field, since 0 starts counting.

Index Error Problems

So I'm making a calculator that takes in a string and checks to see if it has certain words like add or subtract and then finding integers. However, in my current code, I run it and get this error message:
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 7, in calculator
IndexError: string index out of range
The code is typed out below.
def calculator(string):
if "add" in string or "Add" in string:
total = 0
for i in range(len(string)): #loop for length of string
try:
if type(int(string[i])) == int: #checks to see if there is a number in the string
try:
if type(int(string[i+1])): #checks to see if the number is 2 digits
number_1 = int(string[i])*10
except ValueError:
number_1 = int(string[i])
total = total + number_1 #adds all the numbers to a total variable
except ValueError:
pass
print (total)
If someone could help me out that would be great! Thanks so much!
I believe your problem is with type(int(string[i+1]))
as you have a for loop, i can already be pointing to the last index of string. When you add 1 to that, you get an IndexError
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i])
Output:
b
l
a
b
l
a
Example:
s = 'blabla'
for i in range(len(s)):
print(s[i+1])
Output:
l
a
b
l
a
File "C:\Users\python\scratch\untitled-1.py", line 3, in <module>
print(s[i+1])
builtins.IndexError: string index out of range
Sat down with my friend(#Kay Ace Elits) and realised a bunch of things were amiss but we pieced this together
def calculator(string):
if "add" in string:
total = 0
first_string = "" # before a in add
second_string = "" # after d in add
value_list = string.split('add')
for number in value_list:
total += int(number)
print(total)
elif "Add" in string:
total = 0
first_string = ""
second_string = ""
value_list = string.split('Add')
for number in value_list:
total += int(number)
print(total)
### our test your can modify for other factors
### like spellings and different operations
string = "22add43"
calculator(string)

not printing count or average regardless of indentation

I have to make a program that allows the user to enter grades until they enter a negative, and then output the number of passing grades and failing grades with the average. we aren't allowed to use the list function.
maxgrade = 100
mingrade = 0
passing = 0
failing = 0
while True:
try:
grade = int(input("Enter a grade: "))
if 100 >= grade > 60:
passing += 1
elif grade <= 60:
failing += 1
if grade < 0:
print("Invalid")
if grade < mingrade:
mingrade = grade
if grade > maxgrade:
maxgrade = grade
total == grade
count = passing + failing
avg = total/count
print("Average: ", avg)
print("# Passing: ", passing)
print("# Failing: ", failing)
except:
print("Invalid")
break
First, as I mentioned in the comment, your usage of try and except is incorrect. Try and except are used in tandem to prevent errors from occurring. In your case however, I doubt that try and except is even needed. See below code for the workaround.
You also need to take into account your logic and code execution order. The following annotated code will work as specified.
# Assume the lowest and highest possible for max and min grades, respectively
max_grade = 0
min_grade = 100
grade_sum = 0
passing_count = 0
failing_count = 0
# Loop sentinel
running = 1
# Main loop
while running:
# Input validation sentinel
invalid_input = 1
# Input validation loop
while invalid_input:
grade = input("Enter a grade: ")
if grade.isnumeric():
grade = int(grade)
invalid_input = 0
else:
print("Please enter a number!")
# Increment number of passing or failing grades
if 100 >= grade > 60:
passing_count += 1
elif 60 >= grade >= 0:
failing_count += 1
else:
running = 0
# Update grade_sum
grade_sum += grade
# Update min_grade and max_grade
if grade < min_grade:
min_grade = grade
if grade > max_grade:
max_grade = grade
# Calculate grade average
grade_avg = grade_sum / (passing_count + failing_count)
# Print results
print("Average: ", grade_avg)
print("# Passing: ", passing_count)
print("# Failing: ", failing_count)

Cannot keep certain numbers from averaging

I need help. I'm trying to run the program below. When I enter a number above 100 or below 0 I need it to disregard that input any advice?
total = 0.0
count = 0
data = int(input("Enter a number or 999 to quit: "))
while data != "":
count += 1
number = float(data)
total += number
data = int(input("Enter a number or 999 to quit: "))
try:
data = int(data)
except ValueError:
pass
average = round(total) / count
if data == 999:
break
elif data >= 100:
print("error in value")
elif data <= 0:
number = 0
print("error in value")
print("These", count, "scores average as: ", round(average, 1))
You could move the average = ... line behind the checking for invalid numbers and add continue to the checks for invalid numbers. So the last lines would end up like this:
if data == 999:
break
elif data >= 100:
print("error in value")
continue
elif data <= 0:
print("error in value")
continue
average = round(total) / count

Resources