python - 程序不升预定义 ZeroDivisionError
问题描述
我正在构建一个简单的 BMI 计算器程序,如果他们尝试零除,我希望它能够将用户带回输入字段。我定义了在那种情况下应该是什么输出,但它仍然打印出 ZeroDivisionError
def bmi_calculator():
user_height = float(input('Enter your height in cm: ')) # user height in cm
user_weight = float(input('Enter your weight in kg: ')) # user weight in kb
bmi = user_weight / (user_height / 100) ** 2 # BMI formula
while user_height <= 0 or user_weight <= 0:
try:
print("your weight or height can't be below or equal 0 \n enter your credentials again... ")
user_height = float(input('Enter your height in cm: '))
user_weight = float(input('Enter your weight in kg: '))
except ZeroDivisionError:
print("You can't divide by 0")
user_height = float(input('Enter your height in cm: ')) # user height in cm
user_weight = float(input('Enter your weight in kg: ')) # user weight in kb
print(f'Your BMI is: {bmi}')
print(bmi_calculator())
解决方案
那是因为您首先进行除法然后开始while
循环。这应该是这样的:
def bmi_calculator():
user_height = float(input('Enter your height in cm: ')) # user height in cm
user_weight = float(input('Enter your weight in kg: ')) # user weight in kb
while user_height <= 0 or user_weight <= 0:
print("your weight or height can't be below or equal 0 \n enter your credentials again... ")
user_height = float(input('Enter your height in cm: '))
user_weight = float(input('Enter your weight in kg: '))
bmi = user_weight / (user_height / 100) ** 2 # BMI formula
print(f'Your BMI is: {bmi}')
bmi_calculator()
毕竟,我建议在循环中使用if
语句以获得更多说明。while
推荐阅读
- objective-c - 是否有为 NSEnumerationOptions 指定顺序的选项?
- r - 将长数据框加入整齐的数据框
- ruby-on-rails - 我想为数据库中的所有记录在 created_at 列中添加 4 天。有没有办法在rails控制台中做到这一点?
- android - 如何使用 NFC 将文件从(Windows)PC 发送到 android/ios?
- node.js - Nodejs/Express 无法始终如一地从帖子中检索正文。快速连续多次调用成功
- python - Python Web 服务器没有响应 CORS 请求
- qlikview - 如何从 QlikView 连接 REST API (Java)?
- laravel - 使用 axios 时的 CORS 但使用 curl 可以正常工作
- cryptography - 有没有一种快速的方法可以使 IBM 的 vncipher 指令结果与 Intel 的 mm_aesdec_si128 相同?
- python - pypy3 - 读取 csv 文件时出现 UnicodeDecodeError