Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
Basically i want my output from previous value to be new input.
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
for month in range(24):
amount = (((deposit2 * RSK) * rate) * 30 + md + deposit2)
new_amount = amount
print("%4d%21.2f" % (month, new_amount ))
Current output:
Enter initial deposit: 55000
Risk: 0.38
Rate: 0.025
monthly deposits: 10000
0 80675.00
1 80675.00
2 80675.00
3 80675.00
4 80675.00
5 80675.00
6 80675.00
7 80675.00
8 80675.00
9 80675.00
10 80675.00
11 80675.00
12 80675.00
13 80675.00
14 80675.00
15 80675.00
16 80675.00
17 80675.00
18 80675.00
19 80675.00
20 80675.00
21 80675.00
22 80675.00
23 80675.00
Desired output:
Enter initial deposit: 55000
Risk: 0.38
Rate: 0.025
monthly deposits: 10000
0 80675.00
1 113667.00
2 156063.00
3 210540.00
I basically want each output value of input for next process. For example 80675 becomes the new deposit2 value.
Please help me in this
You simply need to reassign deposit2 to amount for every iteration of the loop. Changing the value of variables is a very common thing to do, and there's nothing wrong with doing it. Also, the variable new_amount is not needed, you can simply just change deposit2 to amount once it is calculated. Here's your code, but fixed:
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
for month in range(24):
amount = (((deposit2 * RSK) * rate) * 30 + md + deposit2)
deposit2 = amount
print("%4d%21.2f" % (month, deposit2 ))
Set a new "amount" variable equal to the user input (deposit2) to
start and then just update it in the loop.
print ("Welcome to Derivative Risk Calculator")
while True:
try:
deposit2 = float(input("\nEnter initial deposit: "))
RSK = float(input("Risk: "))
rate = float(input("Rate: "))
md = float(input("monthly deposits: "))
if deposit2<1:
print ("Not a valid amount, please try again.")
else:
break
except ValueError:
print ("You have not entered a number. Please enter a valid number")
amount = deposit2
for month in range(24):
amount = amount * RSK * rate * 30 + md + amount
print("%4d%21.2f" % (month, amount))
Related
I am trying to write a program where i need to be able to enter 5 student marks across 4 different subjects and then output the highest average mark of both the student and the subject.
The desired input and output is :
Student 1 (courses 1-4): 50 60 70 60
Student 2 (courses 1-4): 100 90 87 90
Student 3 (courses 1-4): 70 100 90 90
Student 4 (courses 1-4): 30 65 50 50
Student 5 (courses 1-4): 58 50 74 43
The highest average mark of students: 91.75
The highest average mark of courses: 74.2
The current code I have works for calculating for one subject and not 4. How am I able to enter 4 grades per student to get my desired output.
see my code below:
m1 = int(input("Student 1 (courses 1-4): "))
m2 = int(input("Student 2 (courses 1-4): "))
m3 = int(input("Student 3 (courses 1-4): "))
m4 = int(input("Student 4 (courses 1-4): "))
m5 = int(input("Student 5 (courses 1-4): "))
avg = (m1 + m2+ m3+ m4 + m5) / 5;
avg1 =(m1 + m2+ m3+ m4 + m5) / 20;
print("The Highest average mark of students =", avg)
print("The Highest average mark of courses =", avg1)
This code does the job,
import pandas as pd
import numpy as np
# Part 1
student_num = 5
all_marks = []
for i in range(student_num):
marks = input(f"Student {i + 1} (courses 1-4): ")
all_marks.append(list(map(float, marks.split(" "))))
# Part 2
df = pd.DataFrame(all_marks, columns = ['Marks'])
course_avg = df.Marks.apply(np.mean)
student_avg = df.Marks.apply(np.mean, axis = 1)
The first part of the code converts the input into numbers and stores them into a list. This list is then converted into a data frame in Part 2. I firstly apply np.mean on the columns to find the average for each course, then on the rows to find the average for each student.
You can use idxmax() on both course_avg and student_avg to find the index of the maximum average and find the course/student with the highest average accordingly.
(It's better to store the values in a .xlsx or .csv file directly instead of inputing them through Python this way. Once you have the files, just pass the file path in pd.read_excel() or pd.read_csv() depending upon the format of the file.)
First, create a dictionary to take the inputs of marks for each student. Lets call it d_marks. Create a dictionary to get the average of all students. Let's call it avg_marks. Create a dictionary to get the total marks of all courses. Let's call it avg_course. After that get the max of them. Here's how you can do it:
d_marks = {}
avg_marks = {}
avg_course = {}
for i in range(1,6): # We loop for 5 students
d_marks[f'Student {i} (courses 1-4)'] = list(map(int, input(f"Student {i} (courses 1-4): ").split())) # Split the string and creates an integer list
avg_marks[f'Average of Student {i}'] = sum(d_marks[f'Student {i} (courses 1-4)']) / len(d_marks[f'Student {i} (courses 1-4)']) #Create average dictionary for Students
for j in range(1, len(d_marks[f'Student {i} (courses 1-4)'])+1):
if f'Course {j} sum' in avg_course: # if course sum already in dictionary then add it to previous.
avg_course[f'Course {j} sum'] += d_marks[f'Student {i} (courses 1-4)'][j-1]
else:
avg_course[f'Course {j} sum'] = d_marks[f'Student {i} (courses 1-4)'][j-1] # if course sum not in dictionary then create one.
print("The Highest average mark of students =", max(avg_marks.values()))
print("The Highest average mark of courses =", max(avg_course.values())/ len(d_marks))
Output:
Student 1 (courses 1-4): 50 60 70 60
Student 2 (courses 1-4): 100 90 87 90
Student 3 (courses 1-4): 70 100 90 90
Student 4 (courses 1-4): 30 65 50 50
Student 5 (courses 1-4): 58 50 74 43
The Highest average mark of students = 91.75
The Highest average mark of courses = 74.2
PYTHON 3.7.7
For a school assignment, I have to submit code using an evil program called Mimir. Basically if my output is not pixel-perfect, I get a fail on the test case (15min writing a code, 50min making the output "look right").
Question:
I have no clue how to get my number outputs to look like the assignment's. My shown attempt here uses the 'g' format, as it is the only format modifier that removes trailing zeros and removes the decimal point when necessary. I need to be able to do this while maintaining a '.6' precision. Also, how do I make it that the output is never displayed in scientific notation.
Thank you for the help!
MY CODE:
#Asking user to define parameters for the calculation
Organs = float(input('Starting number of organisms: \n'))
DailyInc = float(input('Average daily increase: \n'))
DaysX = int(input('Number of days to multiply: \n'))
#Doing % to decimal calc. only one to make program work faster
Inc = (1 + (DailyInc / 100))
#Print table heading and first day
print('Day Approximate Population')
print('1', ' ', format(Organs, 'g'))
#Loop to calculate running daily total and print using format hell
for Day in range (2, DaysX + 1):
Organs = Organs * Inc
if Day >= 100:
print(Day," ", format(Organs, 'g'))
elif Day >= 10:
print(Day," ", format(Organs, 'g'))
else:
print(Day," ", format(Organs, 'g'))
MY OUTPUT (input - 2, 30, 60):
Starting number of organisms:
Average daily increase:
Number of days to multiply:
Day Approximate Population
1 2
2 2.6
3 3.38
4 4.394
5 5.7122
6 7.42586
7 9.65362
8 12.5497
9 16.3146
10 21.209
11 27.5717
12 35.8432
13 46.5962
14 60.575
15 78.7475
16 102.372
17 133.083
18 173.008
19 224.911
20 292.384
21 380.099
22 494.129
EXPECTED OUTPUT (input - 2, 30, 60):
Starting number of organisms:
Average daily increase:
Number of days to multiply:
Day Approximate Population
1 2
2 2.6
3 3.38
4 4.394
5 5.7122
6 7.42586
7 9.653618
8 12.549703
9 16.314614
10 21.208999
11 27.571698
12 35.843208
13 46.59617
14 60.575021
15 78.747528
16 102.371786
17 133.083322
18 173.008318
19 224.910814
20 292.384058
21 380.099275
22 494.129058
try something like this:
val1 = 1.2635485547884475
val2 = 1.2
print(val1)
print(f'{val1:.2f}')
print(f'{val1:.6f}')
print(f'{val2:.6f}')
output:
1.2635485547884475
1.26
1.263549
1.200000
First example is displayed on a single line to demonstrate formating
val1 = 1.2635485547884475
val2 = 1.2
print(f'{val1:<17.15f}', end = " ")
print(f'{val1:<7.5f}', end = " ")
print(f'{val2:<4.2g}')
print(f'{val1:<17.15f}')
print(f'{val1:<7.5f}')
print(f'{val2:<4.2g}')
I am new to programming in python and am trying to design a calendar that starts the month depending on the selected start day.
However, I don't know how to stop the print once the number of days has been exceeded(e.g breaks at days=31 when month=="January")
The printed values must be right-aligned additionally.
Here is how I first approached it:
month=input("Enter the month: ")
if month=="January" or month=="March" or month=="May" or month=="July" or month=="August" or month=="October" or month=="December":
days=31
else:
days=30
if month=="February":
days=28
Start_day=input("Enter the start day: ")
print(month)
print("Mo","Tu","We","Th","Fr","Sa","Su")
if Start_day == "Monday":
i=1
if Start_day == "Tuesday":
i=0
if Start_day == "Wednesday":
i=-1
if Start_day == "Thursday":
i=-2
if Start_day == "Friday" :
i=-3
if Start_day == "Saturday":
i=-4
if Start_day == "Sunday":
i=-5
j=1
for j in range(i,days,7):
print(str(j).rjust(2," "),str(j+1).rjust(2," "),str(j+2).rjust(2," "),str(j+3).rjust(2," "),str(j+4).rjust(2," "),str(j+5).rjust(2," "),str(j+6).rjust(2," "))
You could encode it instead as
j=1
for j in range(i,days,7):
for i in range(0,7):
if j+i>days: break
print(str(j+i).rjust(2," "),end=' ')
print('')
This would be called "breaking out of a loop" rather than "breaking from a range function." There is no way to "break from a range function."
Can I suggest overhauling this a bit to be more efficient? You can use dicts and define a custom function to handle the date formatting to prevent some repetition.
To answer your question, you can evaluate the date number during the final loop:
for j in range(i,days,7):
# add to j value via range() and adjust()
# (defined above) to prevent repetition
for k in range(7):
if j + k > 0 and j + k <= days:
print(adjust(j + k), end = ' ') # don't print new line
else:
# print spaces if the number is <1 or >days
print(' ', end = '')
# print new line for a new week
print('\n', end = '')
Full example:
# function to format dates later
def adjust(val):
return str(val).rjust(2," ")
# get inputs
month=input("Enter the month: ")
start_day=input("Enter the start day: ")
# map months to days in a dict
month_to_days={"january":31,
"march":31,
"may":31,
"july":31,
"august":31,
"october":31,
"december":31,
"february":28,
"april":30,
"june":30,
"september":30,
"october":30
}
# map weekdays to int
days_to_int={"monday":1,
"tuesday":0,
"wednesday":-1,
"thursday":-2,
"friday":-3,
"saturday":-4,
"sunday":-5
}
# get the day amount based on the entry, ignoring case
days=month_to_days[month.lower()]
# get the int based on the entry, ignoring case
i=days_to_int[start_day.lower()]
# print month and day headers
print(month)
print("Mo","Tu","We","Th","Fr","Sa","Su")
for j in range(i,days,7):
# add to j value via range() and adjust()
# (defined above) to prevent repetition
for k in range(7):
if j + k > 0 and j + k <= days:
print(adjust(j + k), end = ' ') # don't print new line
else:
# print spaces if the number is <1 or >days
print(' ', end = '')
# print new line for a new week
print('\n', end = '')
Output:
Enter the month: january
Enter the start day: monday
january
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
>>>
Enter the month: june
Enter the start day: wednesday
june
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Before you print after your for loop just have an if statement to check for your condition and before you print add a break statement.
Something like:
if statement:
break
I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.
Here is my code:
tourist_attractions = []
distance = []
entry_cost = []
for i in range(3):
tourist_attractions.append (input("Enter Tourist place: "))
tourist_distance =(int(input("Enter distance: ")))
if tourist_distance > 50:
print("Invalid Entry")
continue
if tourist_distance <= 50:
distance.append(tourist_distance)
cost = (float(input("Enter cost: ")))
if cost > 100:
print("cost must be between 1-100")
continue
if cost > 0 or cost <= 100:
entry_cost.append(cost)
print()
for line in tourist_attractions:
print("Place:", line)
for line in distance:
print("Distance:", line)
for line in entry_cost:
print("Cost:", line)
print()
number_of_places_to_visit = int(input("Total number of places to visit: "))
x = 1
while x <= number_of_places_to_visit:
select_tourist_place = input("select tourist place, 0-3: ")
x = x + 1
if select_tourist_place == "0":
print(tourist_attractions[0], distance[0], entry_cost[0])
elif select_tourist_place == "1":
print(tourist_attractions[1], distance[1], entry_cost[1])
elif select_tourist_place == "2":
print(tourist_attractions[2], distance[2], entry_cost[2])
elif select_tourist_place == "3":
print(tourist_attractions[3], distance[3], entry_cost[3])
elif select_tourist_place == "4":
print(tourist_attractions[4], distance[4], entry_cost[4])
print("total cost: " , sum(entry_cost))
Result I am getting:
Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20
Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0
Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost: 50.0
>>>
I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?
print("total cost: " , sum(entry_cost))
definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.
I want to write a bill program where i want the cgst, sgst from the bill as output. All was going fine but i got stuck on a problem. I want separate names of product from the result of dataframe's output but i am getting only the name of only one product but the amount was sum of two...
Here's my code:
import pandas as pd
count = 0
num = int(input("Type number of items: "))
while count < num:
count += 1
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = pd.DataFrame({
'Item ': [item],
'Price': [SP],
'CGST': [cgst],
'SGST': [sgst],
'Amount payable': [amount],
})
print(data)
what i am getting is this example output:
Type number of items: 2
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 2341
Enter GST rate: 34
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1234567
Enter GST rate: 15
Item Price CGST SGST Amount payable
0 iphone 1234567 92592.525 92592.525 1419752.05
```
What i want the output to be:
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0
As you can see, i am getting only name samsung not iphone and samsung saparatley
In each iteration of your loop you are creating a new data frame with only this loops data and overwitting any data that was in the last data frame. So when you finish your loops and print the dataframe all thats in it is the data from the last iteration of the loop since you created a new dataframe on each iteration.
Instead you could create the data frame before the loop and then just append to the data frame on each iteration of the loop
import pandas as pd
items = []
columns = ['Item', 'Price', 'CGST', 'SGST', 'Amount payable']
df = pd.DataFrame(columns=columns)
num = int(input("Type number of items: "))
for _ in range(num):
print("-----------------------")
item = input("Enter Item Name: ")
SP = int(input("enter selling price of " + item + ": "))
gstrate = float(input("Enter GST rate: "))
cgst = SP * ((gstrate/2)/100)
sgst = cgst
amount = SP + cgst + sgst
data = [item, SP, cgst, sgst, amount]
df_row = dict(zip(columns, data))
df = df.append(df_row, ignore_index=True)
print(df)
OUTPUT
Type number of items: 2
-----------------------
Enter Item Name: iphone
enter selling price of iphone: 1000
Enter GST rate: 18
-----------------------
Enter Item Name: samsung
enter selling price of samsung: 1000
Enter GST rate: 18
Item Price CGST SGST Amount payable
0 iphone 1000 90.0 90.0 1180.0
1 samsung 1000 90.0 90.0 1180.0