如何接受像“2.0"这样的整数但例如“2.1"作为浮点数?Python [英] How to accept something like '2.0' as an integer but eg '2.1' as float? Python

查看:67
本文介绍了如何接受像“2.0"这样的整数但例如“2.1"作为浮点数?Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户在输入字母或非整数时收到错误消息,当输入一个整数时,程序将继续显示这个整数的平方和立方.我的老师不希望代码中出现任何中断"或任何 ValueErrors.

print("Squaring and Cubing integer program has started") #用户程序介绍UserNumber=input("Enter an integer to 2 and 3的幂:") #要求用户输入一个整数,然后将其提高到2和3的幂尽管 '.'在 UserNumber 或 UserNumber.isalpha(): #Error-trap 测试输入是否包含字母或小数点print("你没有输入一个整数.再试一次,输入一个整数!") #提醒用户他们的输入是无效的(不是一个整数)UserNumber=input("Enter an integer to be raise to 2 and 3的幂:") #再次要求用户输入一个整数,如果他们以前没有.print(int(UserNumber), " 是您输入的整数.") #向用户显示他们的初始整数print(int(UserNumber), " squared is ", int(UserNumber)**2) #向用户显示他们输入的整数平方print(int(UserNumber), " cubed is ", int(UserNumber) **3 ) #向用户显示他们输入的整数立方print("计算完成.") #输出显示程序已经结束

解决方案

2.0 is not an integer;它是一个浮点数.Python 中的 float 类似于标准的 IEEE 754 浮点(如果平台支持 IEEE 754 浮点,那么 Python 可能会使用它),但精度有限.Python 中的整数具有无限精度(直到内存不足):

<预><代码>>>>我 = 123456789012345678901234567890>>>我 == 123456789012345678901234567890真的>>>f = i * 1.0 # 使它成为一个浮点数>>>f.is_integer() # 检查是否为整数真的>>>f == 123456789012345678901234567890错误的

切勿混合 float 和 int,除非您知道它不会改变您的情况下的结果,例如 2 == 2.0 但正如示例所示,对于较大的数字,它可能为假.

您的老师可能希望您找到 .is_integer() 方法:

<预><代码>>>>2.0 .is_integer()真的>>>2.1 .is_integer()错误的

另请参阅如何检查浮点值是否为整数.

要将 '2.0' 转换为浮点数,可以调用 float() 函数:

#!/usr/bin/env python3为真:尝试:f = float(input('请输入一个数字:'))除了值错误:print('再试一次')别的:break # 得到一个数字

这是在 Python 中从 stdin 获取数字的正确方法.如果您的老师禁止使用 ValueErrorbreak 那么您可以使用正则表达式:
if re.match("^[+-]? *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$", input_string): 接受 20e-1 == 2.0 == 2.请参阅提取浮点/双精度值.

要测试输入是否为空且只包含十进制数字,即检查是否为非负整数,可以使用input_string.isdecimal()方法如果调用 int(input_string) 并捕获 ValueError 是被禁止的.请参阅如何在 Python 中检查字符串是否为数字?.

I am trying to make it that the user will get an error message back if they enter alphabetical letters or non-integer numbers, and when an integer is entered the program will proceed to show this integer number being squared and cubed. My teacher doesn't want any 'breaks' in code or any ValueErrors.

print("Squaring and cubing integer program has started") #Introduction of program for user
UserNumber=input("Enter an integer to be raised to the power of 2 and 3: ") #Asks user to input an integer, that will then be raised to the power of 2 and 3
while '.' in UserNumber or UserNumber.isalpha(): #Error-trap to test if input contained letters of the alphabet or contains decimal point
  print("You have not entered an integer. Try again and enter an integer!") #Alert for user to inform that their entry was invalid (not an integer)
  UserNumber=input("Enter an integer to be raised to the power of 2 and 3: ")  #Asks user again to enter an integer, if they did not previously.
print(int(UserNumber), " is the integer you entered.") #Displays to user their inital integer
print(int(UserNumber), " squared is ", int(UserNumber)**2) #Displays to user their input integer squared
print(int(UserNumber), " cubed is ", int(UserNumber) **3 ) #Displays to user their input integer cubed
print("Calculations are now finished.") #Output to show program has ended

解决方案

2.0 is not an integer; it is a float. float in Python is similar to the standard IEEE 754 Floating Point (if platform supports IEEE 754 Floating Point then Python probably uses it) that have limited precision. Integers in Python have infinite precision (until you run out of memory):

>>> i = 123456789012345678901234567890
>>> i ==  123456789012345678901234567890
True
>>> f = i * 1.0 # make it a float
>>> f.is_integer() # check whether it is a whole number
True
>>> f ==  123456789012345678901234567890
False

Never mix float and int unless you know that it won't change the result in your case e.g., 2 == 2.0 but as the example shows it can be false for larger numbers.

Your teacher probably expects that you find .is_integer() method:

>>> 2.0 .is_integer()
True
>>> 2.1 .is_integer()
False

See also, How to check if a float value is a whole number.

To convert '2.0' to a float, you could call float() function:

#!/usr/bin/env python3
while True:
    try:
         f = float(input('Enter a number: '))
    except ValueError:
         print('Try again')
    else:
         break # got a number

It is the correct way to get a number from stdin in Python. If your teacher forbids using ValueError and break then you could use a regular expression:
if re.match("^[+-]? *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$", input_string): that accepts 20e-1 == 2.0 == 2. See Extract float/double value.

To test whether the input is not empty and contains only decimal digits i.e., to check whether it is a nonnegative integer, you could use input_string.isdecimal() method if calling int(input_string) and catching ValueError is forbidden. See How do I check if a string is a number in Python?.

这篇关于如何接受像“2.0"这样的整数但例如“2.1"作为浮点数?Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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