How to print multiple lines of input given from a while loop? - python

For a bit of context, the user enters patient number, and 3 body temps, and then those 3 temps are averaged and a diagnosis is given. Problem is I cannot get all of the inputs to be printed and not sure how to fix it.
average = 0
total_patient = 0
total = 0
i = 0
fever = 0
chilled = 0
avg_list = []
PT_list = {}
diagnosis = ('')
print()
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
patient = input('Enter patient: ')
while patient != '':
avg_list = patient.replace(',', ' ')
if patient != ('\n'):
total_patient += 1
total = avg_list.split()
average = (float(total[1]) + float(total[2]) + float(total[3])) / 3
patient = input('Enter patient: ')
PT_list[i] = total[0], average, diagnosis
print()
print('PT AVG Diagnosis')
for num in PT_list:
if average > 98.7:
diagnosis = ('fever')
fever += 1
elif average < 95.0:
diagnosis = ('chilled')
chilled += 1
else:
diagnosis = ('')
print(total[0], ' ', round(average, 2), ' ', diagnosis)

You only need to increment i after this line PT_list[i] = total[0], average, diagnosis. the edited version of code:
average = 0
total_patient = 0
total = 0
i = 0
fever = 0
chilled = 0
avg_list = []
PT_list = {}
diagnosis = ('')
print()
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
patient = input('Enter patient: ')
while patient != '':
avg_list = patient.replace(',', ' ')
if patient != ('\n'):
total_patient += 1
total = avg_list.split()
average = (float(total[1]) + float(total[2]) + float(total[3])) / 3
patient = input('Enter patient: ')
PT_list[i] = total[0], average, diagnosis
i += 1 # <=== check this line
print()
print('PT AVG Diagnosis')
for num in PT_list:
if average > 98.7:
diagnosis = ('fever')
fever += 1
elif average < 95.0:
diagnosis = ('chilled')
chilled += 1
else:
diagnosis = ('')
print(total[0], ' ', round(average, 2), ' ', diagnosis)

total_patient = fever = chilled = 0
PT_list = []
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
while True:
patient = input('Enter patient: ')
if patient == "": break
avg_list = patient.replace(',', ' ')
total_patient += 1
total = avg_list.split()
average = (float(total[1]) + float(total[2]) + float(total[3])) / 3
PT_list.append((total[0], average))
print('PT AVG Diagnosis')
for PT in PT_list:
if PT[1] > 98.7:
diagnosis = 'fever'
fever += 1
elif PT[1] < 95.0:
diagnosis = 'chilled'
chilled += 1
else:
diagnosis = ''
print(PT[0], ' ', round(PT[1], 2), ' ', diagnosis)

Use a list instead of a dict, then you can just append to it instead of having to keep track of (and increment) a key value.
patient_data = []
print()
print('Enter patient number and three temperature readings')
print('Enter blank line to stop entering data')
while True:
patient = input('Enter patient: ').replace(",", " ")
if not patient:
break
num, *temps = patient.split()
average = sum(float(t) for t in temps) / len(temps)
patient_data.append((num, average))
print()
print('PT AVG Diagnosis')
for num, average in patient_data:
if average > 98.7:
diagnosis = 'fever'
elif average < 95.0:
diagnosis = 'chilled'
else:
diagnosis = ''
print(f"{num:<10}{average:<10}{diagnosis}")
Enter patient number and three temperature readings
Enter blank line to stop entering data
Enter patient: 123,99,101,100
Enter patient: 234,98,99,99
Enter patient: 345,97,96,95
Enter patient:
PT AVG Diagnosis
123 100.0 fever
234 98.67
345 96.0

Related

Budget tracker program not working in Linux

I am trying to improve this program. I am working with Linux. I want to add a menu function where the user can pick an option and based on the option call the respective function, but the program is not working, when I run it in the Terminal it doesn't do anything and doesn't show any errors. Please, I need help to solve the problem and make the program works. Thanks!
Here's what I have so far, still there are some functions that need to develop:
#! /usr/bin/python3
import sys
def menu(self):
print ("""
1. Add an Expense
2. Remove an Expense
3. Add revenue
4. Remove Revenue
5. Exit
""")
option = input ("What would you like to do [Number Only]?")
if option == "1":
self.add_expense()
elif option == "2":
self.remove_expense()
elif option == "3":
self.add_revenue()
elif option == "4":
self.remove_revenue()
else:
self.reset_program()
self.close_program()
return option
def add_expense(self):
def __init__(self):
self.month_balance = 0
self.expenses = 0
self.expense_list = []
self.expense_name = []
self.month_balance_name = []
self.month_balance_list = []
self.prompt_income()
def month_balance_ask(self):
add_month_balance = input('Add monthly balance? [y/n]: ')
return add_month_balance
def month_balance_sum(self):
self.month_balance = sum(self.month_balance_list)
def expense_ask(self):
add_expense = input('Add expense? [y/n]: ')
return add_expense
def expense_sum(self):
self.expenses = sum(self.expense_list)
def month_balance_check(self):
if not self.month_balance_list:
print('Please enter at least one monthly balance. ')
self.prompt_month_balance()
def expense_check(self):
if not self.expense_list:
print('Please enter at least one expense. ')
self.prompt_expense()
def prompt_month_balance(self):
x = False
while not x:
result = self.month_balance_ask()
if result == 'y':
month_balance_input = int(input('Enter monthly balance. [Numbers Only]: '))
self.month_balance_list.append(month_balance_input)
month_balance_name = input('Enter monthly balance name. [Name Only]: ')
self.month_balance_name.append(month_balance_name)
else:
self.month_balance_check()
x = True
self.month_balance_sum()
name = [name for name in self.month_balance_name]
month_balance = [month_balance for month_balance in self.month_balance_list]
month_balancedict = dict(zip(name, month_balance))
for k in incomedict:
print(k + ': ', '$' + str(month_balancedict[k]))
print('Total user monthly balance: ', '$' + str(self.month_balance))
self.prompt_expense()
def prompt_expense(self):
x = False
while not x:
result = self.expense_ask()
if result == 'y':
expense_input = int(input('Enter expense amount. [Numbers Only]: '))
self.expense_list.append(expense_input)
expense_name = input('Enter expense name. [Name Only]: ')
self.expense_name.append(expense_name)
else:
self.expense_check()
x = True
self.expense_sum()
name = [name for name in self.expense_name]
expense = [income for income in self.expense_list]
expensedict = dict(zip(name, expense))
for k in expensedict:
print(k + ': ', '$' + str(expensedict[k]))
print('Total user expenses: ', '$' + str(self.expenses))
self.added_expense()
def added_expense(self):
expenseadded = self.month_balance - self.expenses
if expenseadded < 0:
print('You are in the negative, you have a deficit of ' + '$' + str(expenseadded))
if expenseadded == 0:
print('You have broken even, you are spending exactly as much as you make.')
if expenseadded > 0:
print('You are in the positive, you have a surplus of ' + '$' + str(expenseadded))
another = input('Would you like to run another analysis? [y/n]: ')
if another == 'y':
self.menu()
else:
self.reset_program()
self.close_program()
def remove_expense(self):
print("code goes here")
def add_revenue(self):
print("code goes here")
def remove_revenue(self):
print("code goes here")
def reset_program(self):
self.month_balance = 0
self.expenses = 0
del self.expense_list[0:]
del self.expense_name[0:]
del self.month_balance_name[0:]
del self.month_balance_list[0:]
self.prompt_month_balance()
def close_program(self):
print('Exiting Program.')
sys.exit(0)

i want to add a simple Y or N loop to my python code

So here is my code ive tried so many loop options and just cant seem to get it to loop the whole thing when any help would be apreciated
# Displays the Program Header
print('----------------------------------------------------------------------')
print('The Innovation University of Australia (IUA) Grade System')
print('----------------------------------------------------------------------')
# These print commands display the spaces to divide the sections
print()
# Asks the lecturer to input all marks out of 100
print('Please enter all marks out of 100.')
#Asks to input stydents ID and name
#Asks the to input the marks for Assignment 1 and Assignment 2
# and the Final Exam and stores them as floats
studentID = input('Please enter the student ID: ')
studentname = input('Please enter the student name: ')
assignment1 = float(input('Please enter the marks for Assignment 1: '))
assignment2 = float(input('Please enter the marks for Assignment 2: '))
final_exam = float(input('Please enter the marks for the Final Exam: '))
print()
# Displays the Thank You! message
print('Thank You!')
print()
# Calculates the weighted mark for Assignment 1, Assignment 2, and the
# total weighted mark of the Assignments by mutiplying by 20% and 30%
weighted_assignment1 = 0.2 * assignment1
weighted_assignment2 = 0.3 * assignment2
total_weighted_assignments = weighted_assignment1 + weighted_assignment2
# Displays the weighted mark for Assignment 1, Assignment 2, and the total
# weighted mark of the Assignments
print('Weighted mark for Assignment 1:', int(weighted_assignment1))
print('Weighted mark for Assignment 2:', int(weighted_assignment2))
print('Total weighted mark of the assignements:', int(total_weighted_assignments))
print()
# Calculates the weighted mark for the Final Exam and the total weighted
# mark for the subject
weighted_final_exam = 0.5 * final_exam
total_weighted_subject = total_weighted_assignments + weighted_final_exam
# Displays the weighted mark of the Final Exam and the total weighted mark
# for the subject
print('Weighted mark for Final Exam is:', int(weighted_final_exam))
weightedtotal = print('Total weighted mark for the subject:', int(total_weighted_subject))
print()
# Calculates the bonus mark for the subject depending on how high the
# total mark is
if total_weighted_subject > 50 and total_weighted_subject <= 70:
bonus_mark = (total_weighted_subject - 50) * 0.1
elif total_weighted_subject > 70 and total_weighted_subject <= 90:
bonus_mark = (total_weighted_subject - 70) * 0.15 + 2
elif total_weighted_subject > 90 and total_weighted_subject <= 100:
bonus_mark = (total_weighted_subject - 90) * 0.20 + 5
else:
bonus_mark = 0
# Displays the bonus mark for the subject
print('Bonus mark:', format(bonus_mark, '.1f'))
# Calculates the total mark for the subject with the bonus mark
total_with_bonus = total_weighted_subject + bonus_mark
# Check if total mark with bonus is greater than maximum
# possible mark of 100 and if it is set to 100 and display
# total mark with bonus
if total_with_bonus > 100:
total_with_bonus = 100
print('Total mark with bonus:', format(total_with_bonus, '.1f'))
else:
print('Total mark with bonus:', format(total_with_bonus, '.1f'))
print()
outFile = open("TestFile.txt", "w")
outFile.write("student \t student \t A1 \t A2 \t final \t weighted \t weighted total\n" )
outFile.write("id \t name \t \t exam \t total \t with bonus\n")
outFile.write("-----------------------------------------------------------------------------------------------\n")
outFile.close()
content = str(studentID) + "\t" "\t" + str(studentname) + "\t" + str(assignment1) + "\t" + str(assignment2) + "\t" + str(final_exam) + "\t" + str(weightedtotal)
outFile = open("TestFile.txt", "a")
outFile.write(content)
outFile.close()
#Displays Goodbye. message
print('Goodbye.')
How about something like this pattern:
while True:
# Your code here
if enter_more_data == 'N':
break

Function not defined, although its been defined... Going Insane

So I am quite new to python and have been working on this assignment for a week now on and off and can't quite get it to run correctly. I am now getting errors that tell me the function get_in_code is not defined although I've defined it. Any help would be greatly appreciated!
SENTINEL = 'XXX'
DAY_CHARGE = 1500.00
#Define get_days
def get_days():
good_data = False
while not good_data:
try:
n_days = int(input("Please enter the number of days you stayed: "))
except ValueError:
print("Error, Bad Data")
else:
if n_days > 0:
good_data = True
else:
print("This is bad data, please re enter data")
return n_days
#define get_cost(p)
def get_cost():
cost = float(input("Please enter the cost for the procedures: "))
while cost < 0:
print("Procedure cost cant be negative: ")
cost = float(input("Please enter the cost for the procedures: "))
return cost
#define med cost
def med_cost():
med_cost = float(input("Enter the cost of your medicine: "))
while med_cost < 0:
print("Medicine cost cant be negative: ")
med_cost = float(input("Enter the cost of your medicine: "))
return med_cost
#Find day cost
def find_day_cost(in_code, n_days):
day_cost = n_days * DAY_CHARGE
if in_code == 'ZH':
p_day_cost = day_cost * 0.20
in_day_cost = day_cost *0.80
elif in_code == 'HH':
p_day_cost = day_cost * 0.10
in_day_cost = day_cost * 0.90
elif in_code == 'CH':
p_day_cost = day_cost * 0.25
in_day_cost = day_cost * 0.75
else:
p_day_cost = day_cost
in_day_cost = 0
return p_day_cost, in_day_cost
#find procedure cost
def find_proc_cost(in_code, cost):
if in_code == 'ZH':
p_proc_cost = 0
in_proc_cost = cost
elif in_code == 'HH':
p_proc_cost = cost * 0.10
in_proc_cost = cost * 0.90
elif in_code == 'CH':
p_proc_cost = cost * 0.50
in_proc_cost = cost * 0.50
else:
p_proc_cost = cost
in_proc_cost = 0
return p_proc_cost, in_proc_cost
#find medicine cost
def find_med_cost(in_code, med_cost):
if in_code == 'ZH':
p_med_cost = 0
in_med_cost = med_cost
elif in_code == 'HH':
p_med_cost = med_cost * 0.10
in_med_cost = med_cost * 0.90
elif in_code == 'CH':
p_med_cost = med_cost * 0.50
in_med_cost = med_cost * 0.50
else:
p_med_cost = med_cost
in_med_cost = 0
return p_med_cost, in_med_cost
#Display pat_info
def display_pat_info(pat_name, in_name):
print("City Hospital - Patient Invoice")
print("Patient Name: ", pat_name)
print("Insurance: ", in_name)
#display day cost
def display_day_cost(p_day_cost, in_day_cost):
print("Patient Day Cost: ", p_day_cost,"\tInsurance Day Cost: ", in_day_cost)
#display procedure cost
def display_proc_cost(p_proc_cost, in_proc_cost):
print("Patient Procedure Cost: ", p_proc_cost, "\tInsurance Procedure Cost: ", in_proc_cost)
#display medicine cost
def display_med_cost(p_med_cost, in_med_cost):
print("Patient Medicine Cost: ", p_med_cost, "\tInsurce Medicine Cost: ", in_med_cost)
#Display totals
def display_totals(total_pat, total_in):
print("Total Billed To Patient: ", total_pat, "\tTotal Billed To Insurance: ", total_in, "\tTotal Bill: ", (total_pat + total_in))
#display day_totals
def display_day_totals(total_zip, total_happy, total_cheap, total_pat):
print("City Hospital - End Of Day Billing Report")
print("Total Dollar Amount Billed Today: ", total_zip+total_happy+total_cheap+total_pat)
print("Total Billed To Zippy Healthcare: ", total_zip)
print("Total Billed To Happy Healthcare: ", total_happy)
print("Total Billed To Cheap Healthcare: ", total_cheap)
print("Total Billed To Uninsured: ", total_pat)
#display day_counts()
def display_day_counts(zip_count, happy_count, cheap_count, no_in_count):
print("The total amount of Zippy Healthcare patients is: ", zip_count)
print("The total amount of Happy Healthcare patients is: ", happy_count)
print("The total amount of Cheap Healthcare patients is: ", cheap_count)
print("The total amount of Uninsured patients is: ", no_in_count)
#def main
def main():
#Counters and accumulators
total_zip= 0.00
total_cheap= 0.00
total_happy= 0.00
total_pat= 0.00
zip_count= 0
cheap_count= 0
happy_count= 0
no_in_count= 0
total_in = 0
#Open file
try:
Pat_File = open('PatientBill.txt', 'w')
except ValueError:
print("*****ERROR***** - Corrupt File")
else:
file_exist = True
#Priming read
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Processing loop
while pat_name != SENTINEL:
#Input data
in_code = get_in_code()
num_days = get_days()
proc_cost = get_cost()
med_cost = med_cost()
#find each cost
pat_day, insure_day = find_day_cost(in_code, num_days)
pat_proc, insure_proc = find_proc_cost(in_code, proc_cost)
pat_med, insure_med = find_med_cost(in_code, med_cost)
#update accumulators and totals
total_pat += pat_day + pat_proc + pat_med
if in_code == 'ZH':
zip_count += 1
total_zip += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Zippy Healthcare'
elif in_code == 'HH':
happy_count += 1
total_happy += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Happy Healthcare'
elif in_code == 'CH':
cheap_count += 1
total_cheap += in_day_cost + in_proc_cost + in_med_cost
in_name = 'Cheap Healthcare'
else:
no_in_count += 1
in_name = 'Uninsured'
total_in = total_zip + total_happy + total_cheap
#displays patients invoice
display_pat_info(pat_name,in_name)
display_day_cost(pat_day, insure_day)
display_proc_cost(pat_proc, insure_proc)
display_med_cost(pat_med, insure_med)
display_totals(pat_day + pat_proc + pat_med, insure_day + insure_proc + insure_med)
#Write output to file
if file_exist:
Pat_File.write(pat_name, pat_day+pat_med+pat_proc )
#Get next patients name
pat_name = input("Please enter the patients name: (XXX to stop program)")
#Close the output file
if file_exist:
Pat_File.close()
#display the accumlators and totals
display_day_totals(total_zip, total_happy, total_cheap, total_pat)
display_day_counts(zip_count,happy_count,cheap_count,no_in_count)
#define get_in_code
def get_in_code():
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
while in_code not in ('ZH', 'HH', 'CH', 'XX'):
print("***Please enter a proper insurance code***")
in_code = input("Please enter one of the insurance codes, ZH, CH, HH, XX")
return in_code
main()
Python is a interpreted language. You need to define function prior to its usage. Just move a function definitions at the top of a file.
The problem is also with indentation. You're defining your methods inside while, just after a return statement. Actual functions aren't defined at all - interpreter doesn't reach those lines.
Besides, the code is "dirty". Split the code into separate classes/modules. Create well defined areas of responsibility, that would improve the code and it'll be easier to work with it.

Python making GUI windows

I wrote a program that makes 3 things which user may choose:
def createLeague(): #creates a list with all teams
file = open('league1.txt', 'r')
teams = []
for line in file:
team = line.split()
teams.append(team)
file.close()
return teams
def getTeam(teams): #this function gets a team that user inputs
result = ' '
choice = input('Enter the team: ')
checkforteam = False
for line in teams:
team = line[0]
if choice == team: #check for input team in all lines
result = team
games = line[1]
wins = line[2] #assign all statistics to the variables with
draws = line[3] #appropriate names
loses = line[4]
checkforteam = True
if checkforteam: #if it is True, it will return the team. If False, returns an error message
print(result, games, wins, draws, loses)
else:
print('No such a team')
def getWinner(teams): #returns a leader
winner = ' '
result = 0
loses = 100
for team in teams:
points = int(team[2])*3 + int(team[3])
lose = int(team[4])#counting all points
if points > result: #find a team with maximum points
result = points
winner = team[0]
loses = lose
elif points == result:
if lose < loses:
winner = team[0]
print('Winner: ', winner)
print('Points: ', result)
def updateScore(teams): #update the table
firsteam = input('Home: ')
secondteam = input('Away: ')
goal1 = int(input('Goals scored by home: '))
goal2 = int(input('Goals scored by away: '))
f = open('nhl.txt', 'w')
for team in teams:
komanda = team[0]
matches = int(team[1])
wins = int(team[2])
draws = int(team[3])
loses = int(team[4])
if firsteam == komanda:
if goal1 > goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
elif secondteam == komanda:
if goal1 < goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
newline = komanda+ ' '+ str(matches) + ' ' +str(wins)+ ' '+ str(draws) + ' '+ str(loses)+ '\n'
f.write(newline)
f.close()
print('Saved')
teams = createLeague()
loop = 1 #variable that makes 'while' working until user wants to close the program
while loop == 1:
print('0. Exit')
print('1. Find a team')
print('2. Get a leader')
print('3. Update the results')
x = input('Choose: ')
if x == '1':
getTeam(teams)
elif x == '2':
getWinner(teams)
elif x == '3':
updateScore(teams)
elif x == '0':
print('Goodbye!')
loop = 0
else:
print('Wrong!')
Now I want that when I choose 1, 2 or 3 in IDLE, there will be a GUI window appeared where the function that called in while loop will work. I am stucked about it. How I can do it? Please, just show an example for one of the function.

Python Repetition Structures and Files

I have a question about my python program . I have trouble finding the total and ntotal in this program. Rest works fine. Is there any way i can fix this? I have this program due soon. I'd appreciate any tips I can get :D Thanks
midSalary = 50000
maxSalary = 60000
def main():
inFile = open('program7.txt', 'r')
lineRead = inFile.readline()
total = 0.0
ntotal = 0.0
count = 0
while lineRead != '':
words = lineRead.split()
for word in words:
num = float(word)
total += num
count += 1
print("\nFaculty Member # ",count, ": $" , format(num, '.2f'), sep ="")
if num >= maxSalary:
payIncrease(num, .04)
elif num >= midSalary:
payIncrease(num, .07)
else:
payIncrease(num , .055)
lineRead = inFile.readline()
#averagePayRaise = (ntotal - total) / count
inFile.close()
for divider in range(45):
print("-", end ='')
print("\nTotal Faculty payroll : $", format(total , ",.2f"),sep ="")
print("The New Total Faculty payroll : $", format(ntotal , ",.2f"),sep ="")
print("Average Pay Raise : $", format(averagePayRaise, ",.2f"), sep ="")
def payIncrease(amount, prcnt):
print("Pay Raise Percent : ", format(prcnt*100, ".1f")+"%")
total = 0.0
ntotal = 0.0
count = 0
salRaise = amount * prcnt
newSal = amount + salRaise
print("Pay Raise : $", format(salRaise, ',.2f'), sep ="")
print("New Salary : $", format(newSal, ',.2f'), sep = "")
total += amount
count += 1
ntotal += newSal
averagePayRaise = (ntotal - total) / count
main()
By default, names that you assign to in Python are local to the function in which they are declared. So, if you have:
def main():
total = 0
def payIncrease():
total = 0
total += amount
then you have two independent values named total. One way to solve this is to make it global:
total = 0
def main():
global total
total = 0
def payIncrease():
global total
total += amount
Note that you don't want to assign total = 0 inside payIncrease(), because that would reset your running total to 0. You probably added that when you broke out your code into the payIncrease() function because Python gave you an error without that.
def payIncrease(salary):
if current_sal >= maxSalary: return 0.04
if current_sal >= midSalary: return 0.07
return 0.055
def processSalaryData(line):
"""take a line and return current salary and new salary (note that a line is actually just a float)"""
try:
current_sal = float(line)
except ValueError:
return None
return current_sal,current_sal + current_sal*payIncrease(current_sal)
def main():
salaryData = [processSalaryData(line) for line in open("salaries.txt")]
salaryData = filter(None,salaryData) #filter out invalid data
adjustments = [b-a for a,b in salaryData]
old_salaries,new_salaries = zip(*salaryData)
print "OLD TOTAL PAYROLL :",sum(old_salaries)
print "NEW TOTAL PAYROLL :",sum(new_salaries)
print "AVG ADJUSTMENT:",sum(adjustments)/len(adjustments)
print "MAX SALARY:",max(new_salaries)
print "MIN SALARY:",min(new_salaries)

Categories

Resources