Finding the sum of a list created by a user - python-3.x

I am having trouble getting the sum of the list inputted by the user, I have tried multiple ways, I just need help in what I can do to the sum of the list. Thanks, for any help.
import statistics
data=[]
while True:
num = input("Enter a number (type quit to leave): ")
data.append(num)
if num == "quit":
data.remove("quit")
break
def Average(data):
return sum(data) / len(data)
print(*data, sep=", ")
data.sort()
print("The max value entered is: ", max(data))
print("The min value entered is: ", min(data))
print("Sorted list: ", data)
print("First and Last removed: ", (data[1:-1]))
print("The List average is: ", sum(data))

data=[]
while True:
num = input("Enter a number (type quit to leave): ")
data.append(num)
if num == "quit":
data.remove("quit")
break
for i in range(0, len(data)):
data[i] = int(data[i])
print(*data, sep=", ")
data.sort()
print("The max value entered is: ", max(data))
print("The min value entered is: ", min(data))
print("Sorted list: ", data)
print("First and Last removed: ", (data[1:-1]))
print("The List average is: ", sum(data))

Related

Improving in function clarity and efficiency in python

I am very new in programming so I need help in "cleaning up my code" if the code is a mess if not then please recommend some better commands that accomplish the same purpose of any line or multiple lines.
Here is my program.
import random
def random_num():
lower_bound = input("what is your lower bound: ")
upper_bound = input("What is your upper bound: ")
trials = input("How many time would you like to try: ")
random_number = random.randint(int(lower_bound),
int(upper_bound))
user_input = input(
"What is the number that I am thinking in the range "
+ lower_bound + "-" + upper_bound + " (only " + trials + " tries): ")
ending = "Thanks For Playing"
continue_game = "That's it. Do you want to continue the game?
(Yes/No): "
count = 0
while True:
answer = int(user_input)
if count == int(trials) - 1:
lost = input("Sorry you have lost " + continue_game).lower()
if lost in ["yes"]:
random_num()
else:
return ending
else:
if answer == random_number:
win = input(continue_game).lower()
if win in ["yes"]:
random_num()
else:
return ending
elif answer >= random_number:
user_input = input("The number is smaller than that: ")
else:
user_input = input("The number is bigger than that: ")
count += 1
print(random_num())

How to fix "undefined name" error message in Python?

I am creating a simple calculator with Python as my first "bigger" project.
I am trying to use def function and when i am trying to call that function it gives "undefined name" error message.
while True:
print ("Options: ")
print ("Enter '+' to add two numbers")
print ("Enter '-' to subtract two numbers")
print ("Enter '*' to multiply two numbers")
print ("Enter '/' to divide two numbers")
print ("Enter 'quit' to end the program")
user_input = input(": ")
def calculation (argnum1, argnum2):
argnum1 = float (input("Enter your fist number: "))
argnum2 = float (input("Enter your second number: "))
number = argnum1
number = argnum2
result = argnum1 + argnum2
print (result)
print("-"*25)
return number
return result
if user_input == "quit":
break
elif user_input == "+":
calculation (argnum1, argnum2)
I expect the output of argnum1 + argnum 2 result.
You have needlessly defined your function to take two parameters, which you cannot provide as they are defined inside the function:
def calculation (argnum1, argnum2): # argnum1 and argnum2 are immediately discarded
argnum1 = float (input("Enter your fist number: ")) # argnum1 is defined here
argnum2 = float (input("Enter your second number: "))
# do things with argnum1 and argnum2
...
calculation(argnum1, argnum2) # argnum1 and argnum2 are not defined yet
Note that the body of a function is executed only when the function is called. By the time you call calculation, argnum1 and argnum2 are not defined - and even then, they only get defined in another scope.
Ideally, move the input call outside of your function:
def calculation (argnum1, argnum2):
# do things with argnum1 and argnum2
...
argnum1 = float (input("Enter your fist number: ")) # argnum1 is defined here
argnum2 = float (input("Enter your second number: "))
calculation(argnum1, argnum2)
Note that you should define your function outside the loop. Otherwise, it is needlessly redefined on every iteration. There is also no point in having multiple return statements after one another.
Your code should look like this:
def add(argnum1, argnum2):
result = argnum1 + argnum2
print (result)
print("-"*25)
return result
while True:
print ("Options: ")
print ("Enter '+' to add two numbers")
print ("Enter '-' to subtract two numbers")
print ("Enter '*' to multiply two numbers")
print ("Enter '/' to divide two numbers")
print ("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "+":
argnum1 = float (input("Enter your fist number: "))
argnum2 = float (input("Enter your second number: "))
add(argnum1, argnum2)
You can move the function definition out of the while block.
def calculation():
argnum1 = float(input("Enter your fist number: "))
argnum2 = float(input("Enter your second number: "))
result = argnum1 + argnum2
print(result)
return result
while True:
print("Options: ")
print("Enter '+' to add two numbers")
print("Enter '-' to subtract two numbers")
print("Enter '*' to multiply two numbers")
print("Enter '/' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "+":
calculation()

Python 3 Count and While Loop

I am trying to figure out an error in the code below. I need the following conditions to be met:
1) If equal to zero or lower, I need python to state "Invalid Input"
2) If greater than zero, ask whether there is another input
3) As long as there is another input, I need the program to keep asking
4) If "done", then I need Python to compute the lowest of inputs. I have not gotten to this part yet, as I am getting an error in the "done" portion.
print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
while True:
number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
if number < 0 or number == 0:
print ("Input should be greater than zero. Please enter score: ")
if number == "Done":
print ("NEED TO COUNT")
break
I tried to modify your code according to your desired output. I think this should give you an idea. However there is still small things to deal in code. I suppose you can manage rest of it.
empthy_list = []
print ("Lowest Score for the Racer.")
while True:
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
if number > 0:
empthy_list.append(number)
reply = input('Do you have another input? If "Yes" type another score, if "No" type "Done": ')
if reply == "Yes" :
number = float(input("Please enter score: "))
empthy_list.append(number)
if reply == "Done":
print("NEED TO COUNT")
print("Lowest input is: ",min(empthy_list))
break
I wrote an alternative solution which is more robust regarding input errors. It might include some ideas for improving your code but probably isn't the best solution, either.
print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
foo = input('Please enter score: ')
try:
number = float(foo)
if number > 0:
num_arr.append(number)
valid_input = True
else:
raise ValueError
while foo != 'Done' and valid_input:
try:
number = float(foo)
if number > 0:
num_arr.append(number)
else:
raise ValueError
except ValueError:
print('Invalid input! Input should be number greater than zero or
"Done".')
finally:
foo = input('Do you have another input? If yes type another score,
if no type "Done": ')
except ValueError:
print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))

If statement error: ValueError: invalid literal for int() with base 10: ' ' and out of order int()

My code is as follows:
allnums = []
odds = []
evens = []
number = 0
while True:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '"+str(allnums[0])+"'")
break
if int(number) % 2 == 0:
evens.append(number)
evens.sort()
allnums.append(number)
allnums.sort()
if int(number) % 2 != 0:
odds.append(number)
odds.sort()
allnums.append(number)
allnums.sort()
else:
print("Invalid input")
I'm trying to create a program that reads a list of numbers and determines the lowest value, while also offering a list of even and odd numbers. I'm running into two issues with my code where the lowest number is not often correct, for example:
Enter a number or type 'done':33
Enter a number or type 'done':4
Invalid input
Enter a number or type 'done':6
Invalid input
Enter a number or type 'done':4
Invalid input
Enter a number or type 'done':6
Invalid input
Enter a number or type 'done':7
Enter a number or type 'done':44
Invalid input
Enter a number or type 'done':88
Invalid input
Enter a number or type 'done':done
=============================
Your even numbers are ['4', '4', '44', '6', '6', '88']
Your odds numbers are ['33', '7']
=============================
Your smallest number is '33'
I also get the following error when I use just a space(' ') as an answer, which I would like to write a print("Invalid input") response to something that is not a number or done, but always results in:
Traceback (most recent call last):
File "XXXX", line 17, in <module>
if int(number) % 2 == 0:
ValueError: invalid literal for int() with base 10: ' '
I know this has mostly to do with order of events, but what am I missing?
allnums = []
odds = []
evens = []
number = 0
while True:
try:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(sorted(evens)))
print("Your odds numbers are", str(sorted(odds)))
print("=============================")
print("Your smallest number is '"+str(sorted(allnums)[0])+"'")
break
elif int(number) % 2 == 0:
evens.append(number)
#evens.sort()
allnums.append(number)
#allnums.sort()
elif int(number) % 2 != 0:
odds.append(number)
#odds.sort()
allnums.append(number)
#allnums.sort()
pass
except:
print("Invalid input")
pass
are you sure, this is my output
deathnote#deathnote:~/Desktop/d$ python3 code.py
Enter a number or type 'done':12
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':qwe
Invalid input
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':wqew
Invalid input
Enter a number or type 'done':done
=============================
Your even numbers are ['12']
Your odds numbers are []
=============================
Your smallest number is '12'
The error message is pretty clear: number contains a space, which can't be parsed into an integer. If you want to flag such input as invalid, you have to test it before trying to convert it to an integer (or catch the error that doing so generates).
You have two issues:
Need check for space before you are trying to get a number from it.
Then you are appending number input as string into your list, which will end with wrong sorting result as it will sort string instead of number.
allnums = []
odds = []
evens = []
number = 0
if number.lower() == 'done':
evens.sort()
odds.sort()
allnums.sort()
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '"+str(allnums[0])+"'")
break
if number.isspace():
print("Invalid input")
else:
number = int(number)
if int(number) % 2 == 0:
evens.append(number)
allnums.append(number)
elif int(number) % 2 != 0:
odds.append(number)
allnums.append(number)
allnums = []
odds = []
evens = []
number = 0
while True:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '" + sorted(allnums)[0] + "'")
break
if not number.isnumeric():
print("Invalid input")
continue
if int(number) % 2 == 0:
evens.append(number)
evens.sort()
allnums.append(number)
allnums.sort()
if int(number) % 2 != 0:
odds.append(number)
odds.sort()
allnums.append(number)
allnums.sort()

Counting Grades to print

Hopefully this will be very simple all I need help with is getting a count of the letter grades and then printing them along with the list.
Here is my code:
def getScores():
f_obj = open("scores.txt", "r")
data = f_obj.readlines() #read file into a list of record strings
f_obj.close()
return data
def displayData(data):
print("Name Avg Grade")#print headings
for record in data:
name, ex1, ex2, ex3 = record.split()
exam1 = float(ex1)
exam2 = float(ex2)
exam3 = float(ex3)
avg = round(exam1 + exam2 + exam3) / 3
if avg >= 100:
letterGrade = "A"
elif avg >= 89:
letterGrade = "B"
elif avg >= 79:
letterGrade = "C"
elif avg >= 69:
letterGrade = "D"
elif avg >= 59:
letterGrade = "F"
Just above here is where im stuck I cannot figure out how to do a count with the certain letter grades.
print("%-10s %5s %5s" % (name, round(avg, 1), letterGrade))
print()
print(
def addStudent():
name = input("Enter student name: ")
ex1 = int("Enter Exam 1 grade: ")
ex2 = int("Enter Exam 2 grade: ")
ex3 = int("Enter Exam 3 grade: ")
return name + "\t" + ex1 + "\t" + ex2 + "\t" + ex3
def storeData(data):
f_obj = open("scores.txt", "w")
f_obj.writelines(data)
f_obj.close()
def main():
scoreData = getScores() # read data file into a list
while True:
print("""
Program Options
1.) Display Students.
2.) Add a new student:
3.) Exit Program """)
option = input("Enter option 1, 2, or 3: ")
if option == "1":
displayData(scoreData)
elif option == "2":
scoreData.append(addItem()) # add record string to our list
elif option == "3":
storeData(scoreData)
print("Good bye.")
break
else:
print("Not a valid entry. Please enter 1, 2, or 3.")
main() # start the program
Hint: you already know how to determine if a grade is an A, B, C, etc. So all you need to do is increment a counter at the same time.
For example, you'd add in something like this to count the number of A grades:
if avg >= 100:
letterGrade = "A"
numAs += 1
Then do the same thing for each other grade type. Since this appears to be homework, I'll let you figure out how to do all this. Most importantly, even though Python isn't strict about this, think about the correct place to declare the counter variables.
Once you've got that working, here's an "extra credit" assignment: see if you can do all that using just a single array.

Resources