How to call upon values in a nested loop? - python

I'm working on my first exam for my programming class. I can't figure out how to call upon and sum the values of a given index in a nested loop. I need to sum the wage of each employee together as well as the hours of each employee together. These values are nested as [record] in [employee_records], as index 2 and 3, respectively. Any help would be greatly appreciated!
here's the error I'm getting:
line 54, in <module>
for y in record[2]:
TypeError: 'float' object is not iterable
code is as follows:
num_employees = int(input("Enter number of salespersons to be evaluated: "))
numNums = num_employees
employee_records = []
wage = None
lrange = [1, 2, 3, 4]
while num_employees > 0:
record = []
name = (input("Enter employee name: "))
try:
level = int(input("Enter this employee's level: "))
if level not in lrange:
print("Employee level must be from 1 to 4. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
except ValueError:
print("Employee level must be from 1 to 4. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
try:
hours = float(input("Enter hours worked by this employee: "))
except ValueError:
print("Entry must be a number. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
try:
sales = float(input("Enter revenue generated by this employee: "))
except ValueError:
print("Entry must be a number. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
num_employees -= 1
record.append(name.capitalize())
record.append(level)
record.append(hours)
record.append("${:,.2f}".format(sales))
employee_records.append(record)
print(employee_records)
totalsales = None
totalhours = None
for x in employee_records:
for y in record[2]:
totalhours += y
for y in record[3]:
totalsales += y
print(totalhours)
print(totalsales)

You don't need a nested loop. Just use the fields directly. However, you should NOT be formatting the sales as a string. You need the raw number in order to do math. Format it when you print it, not before.
record.append(name.capitalize())
record.append(level)
record.append(hours)
record.append(sales)
employee_records.append(record)
print(employee_records)
totalsales = None
totalhours = None
for x in employee_records:
totalhours += record[2]
totalsales += record[3]
print(totalhours)
print(totalsales)

Related

Check if the input value is valid in list using python

The programm is check if input value is valid in list.
below is my code. could you please help?thanks
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
for i in range(days):
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( 0<= Day_list[i] <=10):
print('good' )
else:
print('Amount cant be negative, try again')
break
i would like check the value one by one
eg.
Enter the day 1 : -1
then output : Amount cant be negative, try again
return Enter the day 1 : 1
Enter the day 2 :
but i dont have idea where is mistake,thanks
here you are:
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
if days >= 0:
for i in range(days):
valid = False
while not valid:
try:
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( Day_list[i] >= 0 and Day_list[i] <=10):
print('good' )
valid = True
except ValueError:
print ('input is not valid')
break
else:
print('Amount cant be negative, try again')

I have defined the variable but python still shows error

This progam was working fine before i used data validation(the while loops) but now i get the following error -
average_grade = (grade1 + grade2) / 2
NameError: name 'grade2' is not defined
This error was not happening before , I have just started programming so i am quite confused
valid = False
while valid==False:
grade1 = float( input("Enter the grade1: ") )
if grade1 <0 or grade1 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
valid = True
while valid==False:
grade2 = float(input("Enter the grade2: "))
if grade2 < 0 or grade2 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
valid = True
while valid == False:
absences = int(input("Enter the number of absences: "))
if type(absences)!=int:
print("Number of absences can only be an integer value")
continue
else:
valid = True
while valid == False:
total_classes = int(input("Enter the total number of classes: "))
if type(total_classes)!=int:
print("Total number of classes can only be an integer value")
continue
else:
valid = True
average_grade = (grade1 + grade2) / 2
attendance = ((total_classes - absences) / total_classes)*100
print(average_grade)
print("Your attendance is :", attendance , "%")
if(average_grade>=6):
if(attendance>=0.8):
print("YOU HAVE PASSED")
else:
print("You have failed as your attendance is less than 80%")
elif(attendance>=0.8):
print("You have failed due to average grade being lower than 6")
else:
print("You have failed due to average grade being lower than 6 and attendance lower than 80%")
The problem is that you're never resetting the value of valid, so once you set valid = True in the first while loop, none of the other loops will execute (because the loop condition will be false).
You don't need the valid variable in any case; instead of having a
conditional loop expression with a flag, just break out of the loop
when you receive a valid value:
while True:
grade1 = float( input("Enter the grade1: ") )
if grade1 <0 or grade1 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
break
while True:
grade2 = float(input("Enter the grade2: "))
if grade2 < 0 or grade2 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
break
while True:
absences = int(input("Enter the number of absences: "))
if type(absences)!=int:
print("Number of absences can only be an integer value")
continue
else:
break
while True:
total_classes = int(input("Enter the total number of classes: "))
if type(total_classes)!=int:
print("Total number of classes can only be an integer value")
continue
else:
break
Unrelated to your question, but when you have a boolean variable you
don't need to compare it explicitly to False (or True); you can
use the value of the variable itself as the condition:
while somevar == False:
You can just write:
while not somevar:

Validate the score in python

array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
while True:
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
if score <= 0 & score >= 101:
break
print(int(input("Invalid score, please re-enter: ")))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
I tried to make a python program, to validate the score, but it's still a mistake, I want to make a program if I enter a score of less than 0 it will ask to re-enter the score as well if I input more than 100. Where is my error?
Change the if statement:
array = []
total = 0
text = int(input("How many students in your class: "))
print("\n")
for x in range(text):
score = int(input("Input score {} : ".format(x+1)))
while True:
if 0 <= score <= 100:
break
score = int(input("Invalid score, please re-enter: "))
array.append(score)
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/text))
Here, the score at the same time can't be less than 0 and greater than 100. So as you want to break of the score is between 0 and 100, we use 0 <= score <= 100 as the breaking condition.
Also the loops were reversed, since you won't get what you expected to.
try this one:
array = []
total = 0
num_of_students = int(input("How many students in your class: "))
print("\n")
for x in range(num_of_students):
score = int(input("Input score {} : ".format(x + 1)))
while True:
if score < 0 or score > 100:
score = int(input("Invalid score, please re-enter: "))
else:
array.append(score)
break
print("\n")
print("Maximum: {}".format(max(array)))
print("Minimum: {}".format(min(array)))
print("Average: {}".format(sum(array)/num_of_students))
I renamed some of your variables. You should always try to using self explanatory variable names. I am also using string interpolation (should be possible for Python +3.6) and comparison chaining.
score_list = []
total = 0
number_of_students = int(input("How many students in your class: "))
print("\n")
for student in range(number_of_students):
score_invalid = True
while score_invalid:
score_student = int(input(f"Input score {student + 1} : "))
if (0 <= score_student <= 100):
score_invalid = False
else:
score_invalid = True
if score_invalid:
print("Invalid score!\n")
score_list.append(score_student)
print("\n")
print(f"Maximum: {max(score_list)}")
print(f"Minimum: {min(score_list)}")
print(f"Average: {sum(score_list) / number_of_students}")
You could try something like this:
score = -1
first_time = True
while type(score) != int or score <= 0 or score >= 101 :
if first_time:
score = int(input("Input score: "))
first_time = False
else:
score = int(input("Invalid score, please re-enter: "))
array.append(score)

Python: Returning array values from a function

I'm trying to understand how to use functions properly. In this code, I want to return 2 arrays for pupil names and percentage scores. However I am unable to return the array variables from the first function.
I've tried using different ways of defining the arrays (with and without brackets, both globally and locally)
This is the relevant section of code for the program
#function to ask user to input name and score
def GetInput():
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
I'm expecting to be asked to enter the values for both arrays.
I'm instead getting:
Traceback (most recent call last):
File "H:/py/H/marks.py", line 35, in <module>
name, mark = GetInput()
File "H:/py/H/marks.py", line 7, in GetInput
names[counter] = input("Please enter the student's name: ")
NameError: global name 'names' is not defined
You need to use dictionary instead of list if your want to use key-value pairs. furthermore you need to return the values outside of for loop. You can try the following code.
Code:
def GetInput():
names = {} # Needs to declare your dict
percentages = {} # Needs to declare your dict
for counter in range(0, 3):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages # Return outside of for loop.
name, mark = GetInput()
print(name)
print(mark)
Output:
>>> python3 test.py
Please enter the student's name: bob
Please enter the student's score %: 20
Please enter the student's name: ann
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{0: 'bob', 1: 'ann', 2: 'joe'}
{0: 20, 1: 30, 2: 40}
If you want to create a common dictionary which contains the students' name and percentages, you can try the following implementation:
Code:
def GetInput():
students = {}
for _ in range(0, 3):
student_name = input("Please enter the student's name: ")
valid = False
while not valid:
student_percentages = int(input("Please enter the student's score %: "))
if student_percentages < 0 or student_percentages > 100:
print("Please enter a valid % [0-100]")
continue
valid = True
students[student_name] = student_percentages
return students
students = GetInput()
print(students)
Output:
>>> python3 test.py
Please enter the student's name: ann
Please enter the student's score %: 20
Please enter the student's name: bob
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{'ann': 20, 'bob': 30, 'joe': 40}
You forgot to set the names and percentages as empty dictionaries so you can use them. Also the "return" should be outside of the for loop.:
def GetInput():
names={}
percentages={}
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
Probably this may help to you.
#function to ask user to input name and score
def GetInput():
names=[]
percentages=[]
for counter in range(0,3):
names.append(input("Please enter the student's name: "))
valid = False
while valid == False:
percentages.append(int(input("Please enter the student's score %: ")))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
print(name,mark)
This is implemented by using two lists. (Not suggested for keeping records. Better use dictionary as done below.)
counter = 10
def GetInput():
names = []
percentage = []
for i in range(counter):
names.append(input("Please enter the student's name: "))
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
return names, percentage
students, marks = GetInput()
The following is implemented by using dictionary, and for this, you do not need the variable counter.
def GetInput():
records = dict()
for i in range(counter):
name = input("Please enter the student's name: ")
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
#percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
records[name] = percent
return records
record = GetInput()
Change the value of counter to how many records you want. This takes care of marks to be between 0 and 100 (included) and to be integer. Its better if you implement it with dictionary.
Wouldn't it be better to have name and percentage in one dict?
#function to ask user to input name and score
def GetInput():
name_percentage = {}
for counter in range(0,10):
name = input("Please enter the student's name: ")
valid = False
while not valid:
percentage = int(input("Please enter the student's score %: "))
if percentage < 0 or percentage > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
name_percentage[name] = percentage
return name_percentage
name_percentage = GetInput()
print(name_percentage)

How to combine str and int variables?

For this problem, I need to "separate" or identify individual sets of 3 different user inputs: a name, an address, and a salary. Then the program needs to find the highest salary and print the name and the address of the person that it belongs to.
I'm not sure how I can do this in Python.
I know I can use max(salary) but how can I print the associated name and address?
I'm trying to do this using a while loop.
Edit:
Ok, so I'm a beginner so I apologize if this is too basic.
This is what I came up with so far.
name = str(raw_input("Input name: "))
address = str(raw_input("Input address: "))
salary = int(raw_input("Input salary or a number < 0 to end program: "))
x = []
while salary > 0:
name = str(raw_input("Input name: "))
address = str(raw_input("Input address: "))
salary = int(raw_input("Input salary or a number < 0 to end program: "))
x.append(salary) #this returns error: 'int' object is not iterable
m = max(salary)
print #should print name, address associated with max(salary)
Thank you
max_salary = None
max_index = None
salary = 1
index = 0
x = []
while salary > 0:
name = raw_input("Input name: ")
address = raw_input("Input address: ")
salary = int(raw_input("Input salary or a number < 0 to end program: "))
if max_salary is None or salary > max_salary:
max_salary = salary
max_index = index
index += 1
x.append("{} {} {}".format(name, address, salary))
if max_index is not None:
print(x[max_index])
Another way (preferred):
x = []
while True:
name = raw_input("Input name: ")
address = raw_input("Input address: ")
salary = int(raw_input("Input salary or a number < 0 to end program: "))
if salary < 0:
break
x.append((name, address, salary))
if x:
print("{} {} {}".format(*max(x, key=lambda t: t[2])))
This should be working fine.
people=[]
elements= int(input('enter the number of people you want: '))
for i in range(elements):
name= input('enter the name of person %d: '% (i+1))
address= input('enter the address: ')
salary= int(input('enter the salary: '))
person={}
person['name']=name
person['address']= address
person['salary']= salary
people.append(person)
# getting the max from all the salaries and the max
sal_max= max([x['salary'] for x in people])
# matching the max salary:
for i in people:
if i['salary']==sal_max:
print (i['name'], i['address'])

Categories

Resources