如何让用户只在Python程序中输入整数值 [英] How to make users only enter integer values in Python program

查看:200
本文介绍了如何让用户只在Python程序中输入整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份我非常困惑的家庭作业。我必须编写一个程序,允许用户输入他们购买的鸡蛋数量。然后程序将告诉他们可以填充多少个盒子(六个鸡蛋)以及剩下多少个鸡蛋。

I have a homework assignment that I am very confused about. I have to write a program allowing users to input the number of eggs that they are buying. The program will then tell them how many boxes (of six eggs) that they can fill and how many eggs are left over.

我需要确保如果用户输入非整数值,将显示错误消息。我无法弄清楚如何做到这一点,任何帮助将不胜感激!是否与while循环有关或我完全错了?

I need to make sure that if the user enters a non integer value, an error message will be displayed. I can't figure out how to do this and any help would be much appreciated! Is it something to do with while loops or am I completely wrong?

推荐答案

让用户输入他想要的任何内容,并仅警告如果它不是整数:

Let the user enter anything he wishes, and warn only if it wasn't an integer:

try:
    num = int(input("enter number: "))
except ValueError:
    print("you must enter an integer")

这是Pythonic的方法,毕竟它是更容易请求宽恕而不是许可

This is the Pythonic way to do it, after all it's "Easier to ask forgiveness than permission".

这篇关于如何让用户只在Python程序中输入整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆