Zinsrechner von JavaScript nach Python umsetzen

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Golfo
User
Beiträge: 1
Registriert: Montag 17. Februar 2025, 12:56

Ich habe einen einfachen Zinsrechner mit HTML, CSS und JavaScript für meine prozentrechner-ass erstellt. Jetzt möchte ich ihn in Python implementieren. Kann mir jemand erklären, wie ich das am besten machen kann? Unten ist mein JavaScript-Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interest Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
}
.calculator {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
padding: 20px;
max-width: 600px;
margin: 0 auto;
}
h1 {
text-align: center;
color: #333;
}
.input-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input, select {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
width: 100%;
font-size: 16px;
margin-bottom: 10px;
}
button:hover {
background-color: #0056b3;
}
#result {
margin-top: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.tooltip {
position: relative;
display: inline-block;
cursor: help;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 200px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -100px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="calculator">
<h1>Interest Calculator</h1>
<div class="input-group">
<label for="principal">
Principal Amount:
<span class="tooltip">ℹ️
<span class="tooltiptext">Initial investment amount</span>
</span>
</label>
<input type="number" id="principal" placeholder="Enter principal amount" required>
</div>
<div class="input-group">
<label for="rate">
Annual Interest Rate (%):
<span class="tooltip">ℹ️
<span class="tooltiptext">Annual interest rate as a percentage</span>
</span>
</label>
<input type="number" id="rate" placeholder="Enter interest rate" step="0.01" required>
</div>
<div class="input-group">
<label for="time">
Time Period (years):
<span class="tooltip">ℹ️
<span class="tooltiptext">Investment duration in years</span>
</span>
</label>
<input type="number" id="time" placeholder="Enter time period" required>
</div>
<div class="input-group">
<label for="interestType">Interest Type:</label>
<select id="interestType">
<option value="simple">Simple Interest</option>
<option value="compound">Compound Interest</option>
</select>
</div>
<div class="input-group" id="compoundingFrequencyGroup" style="display:none;">
<label for="compoundingFrequency">Compounding Frequency:</label>
<select id="compoundingFrequency">
<option value="1">Annually</option>
<option value="2">Semi-annually</option>
<option value="4">Quarterly</option>
<option value="12">Monthly</option>
<option value="365">Daily</option>
</select>
</div>
<button onclick="calculateInterest()">Calculate Interest</button>
<button onclick="clearFields()" style="background-color: #dc3545;">Clear</button>
<div id="result"></div>
<canvas id="growthChart"></canvas>
</div>

<script>
document.getElementById('interestType').addEventListener('change', function() {
document.getElementById('compoundingFrequencyGroup').style.display =
this.value === 'compound' ? 'block' : 'none';
});

function calculateInterest() {
const principal = parseFloat(document.getElementById('principal').value);
const rate = parseFloat(document.getElementById('rate').value) / 100;
const time = parseFloat(document.getElementById('time').value);
const interestType = document.getElementById('interestType').value;
const compoundingFrequency = parseInt(document.getElementById('compoundingFrequency').value);

if (isNaN(principal) || isNaN(rate) || isNaN(time) || principal <= 0 || rate <= 0 || time <= 0) {
alert('Please enter valid positive numbers for all fields.');
return;
}

let totalAmount, interest;

if (interestType === 'simple') {
interest = principal * rate * time;
totalAmount = principal + interest;
} else {
totalAmount = principal * Math.pow(1 + rate / compoundingFrequency, compoundingFrequency * time);
interest = totalAmount - principal;
}

let result = `<h2>Interest Calculation Results</h2>`;
result += `Principal Amount: $${principal.toFixed(2)}<br>`;
result += `Interest Earned: $${interest.toFixed(2)}<br>`;
result += `Total Amount: $${totalAmount.toFixed(2)}<br>`;

result += `<h3>Yearly Breakdown</h3>`;
result += `<table><tr><th>Year</th><th>Beginning Balance</th><th>Interest</th><th>Ending Balance</th></tr>`;

let yearlyData = [];
let currentBalance = principal;
for (let year = 1; year <= time; year++) {
let yearlyInterest;
if (interestType === 'simple') {
yearlyInterest = principal * rate;
} else {
yearlyInterest = currentBalance * (Math.pow(1 + rate / compoundingFrequency, compoundingFrequency) - 1);
}
let endingBalance = currentBalance + yearlyInterest;

result += `<tr>
<td>${year}</td>
<td>$${currentBalance.toFixed(2)}</td>
<td>$${yearlyInterest.toFixed(2)}</td>
<td>$${endingBalance.toFixed(2)}</td>
</tr>`;

yearlyData.push({year: year, balance: endingBalance});
currentBalance = endingBalance;
}

result += `</table>`;

document.getElementById('result').innerHTML = result;

updateChart(yearlyData);
}

function updateChart(yearlyData) {
const ctx = document.getElementById('growthChart').getContext('2d');

if (window.growthChart) {
window.growthChart.destroy();
}

window.growthChart = new Chart(ctx, {
type: 'line',
data: {
labels: yearlyData.map(data => `Year ${data.year}`),
datasets: [{
label: 'Balance',
data: yearlyData.map(data => data.balance),
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Balance ($)'
}
},
x: {
title: {
display: true,
text: 'Year'
}
}
},
plugins: {
title: {
display: true,
text: 'Balance Growth Over Time'
}
}
}
});
}

function clearFields() {
document.getElementById('principal').value = '';
document.getElementById('rate').value = '';
document.getElementById('time').value = '';
document.getElementById('interestType').value = 'simple';
document.getElementById('compoundingFrequency').value = '1';
document.getElementById('compoundingFrequencyGroup').style.display = 'none';
document.getElementById('result').innerHTML = '';
if (window.growthChart) {
window.growthChart.destroy();
window.growthChart = null;
}
}
</script>
</body>
</html>
Benutzeravatar
noisefloor
User
Beiträge: 4149
Registriert: Mittwoch 17. Oktober 2007, 21:40
Wohnort: WW
Kontaktdaten:

Hallo,

... und wilkommen im Forum :-)
Kann mir jemand erklären, wie ich das am besten machen kann?
Na ja... programmieren halt. Also worauf zielt die Frage ab? Oder erwartest du, dass dir jemand eine fertige Lösung präsentiert?

Von der Programmierung her ist da ziemlich simple: die schreibst eine Funktion, die die notwendigen Ausgangsdaten als Argumente übergeben bekommst, rechnest dann vom Prinzip wie in JS das Ergebnis aus und lieferst es dann zurück. Das sind 8 Zeilen Code.

Hast du schon das Python Tutorial (Link, deutsche Übersetzung) durchgearbeitet? Danach sollte das Nachprogrammieren kein Problem sein.

BTW: das nächste Mal bitte nur den relevanten JS Code posten, dass ganze HTML und CSS Zeug braucht man für deine Fragestellung nicht und macht den Post nur unnötig unleserlich.

Gruß, noisefloor
Benutzeravatar
__blackjack__
User
Beiträge: 13919
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@Golfo: Python lernen, inklusive objektorientierter Programmierung; ein GUI-Rahmenwerk auswählen; den Umgang mit diesem Rahmenwerk lernen; und dann einen Zinsrechner damit umsetzen. So ganz grob.

Zu Python gibt es ein Grundlagentutorial in der Python-Dokumentation.
“Java is a DSL to transform big Xml documents into long exception stack traces.”
— Scott Bellware
Benutzeravatar
DeaD_EyE
User
Beiträge: 1205
Registriert: Sonntag 19. September 2010, 13:45
Wohnort: Hagen
Kontaktdaten:

Eine Option wäre PyScript. Damit kann man im HTML-Code Python nutzen. Um den Payload (Interpreter + Stdlib) gering zu halten, kann man Micropython als Implementierung verwenden.

https://pyscript.net/
sourceserver.info - sourceserver.info/wiki/ - ausgestorbener Support für HL2-Server
Benutzeravatar
noisefloor
User
Beiträge: 4149
Registriert: Mittwoch 17. Oktober 2007, 21:40
Wohnort: WW
Kontaktdaten:

@Golfo: willst du eigentlich nur die Rechnung an sich in Python programmieren oder die ganze Applikation inkl. User Interface? Meine "8 Zeilen" Code bezogen sich natürlich nur auf die Rechnung an sich.

Gruß, noisefloor
Antworten