PS2020 发表于 2020-10-27 22:11:29

已经转换整型,为什么输入小数后报错

import random
secret = random.randint(1,10)
print('-------我爱python----------')
temp = input("猜数字:")
guess = int(temp)
while guess != secret:
    temp = input("错了,继续:")
    guess = int(temp)
    if guess == secret:
      print("我艹!!!")
      print("哼")
    else:
      if guess > secret:
            print("你大了")
      else:
            print("你小了")
print("无聊,不玩了")

昨非 发表于 2020-10-27 22:13:35

本帖最后由 昨非 于 2020-11-8 12:50 编辑

input返回值是字符型,含有小数点时,强制转换为int时会报错
语法规则
用eval
secret = random.randint(1,10)
print('-------我爱python----------')
temp = eval(input("猜数字:"))
guess = int(temp)
while guess != secret:
    temp = eval(input("错了,继续:"))
    guess = int(temp)
    if guess == secret:
      print("我艹!!!")
      print("哼")
    else:
      if guess > secret:
            print("你大了")
      else:
            print("你小了")
print("无聊,不玩了")

笨鸟学飞 发表于 2020-10-27 22:36:10

>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.The trailing newline is stripped.
   
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
   
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
=======input()函数是获取并返回用户输入的字符串,返回值类型是字符串===========
>>> help(int)
Help on class int in module builtins:

class int(object)
|int() -> integer
|int(x, base=10) -> integer
|
|Convert a number or string to an integer, or return 0 if no arguments
|are given.If x is a number, return x.__int__().For floating point
|numbers, this truncates towards zero.
|
|If x is not a number or if base is given, then x must be a string,
|bytes, or bytearray instance representing an integer literal in the
|given base.The literal can be preceded by '+' or '-' and be surrounded
|by whitespace.The base defaults to 10.Valid bases are 0 and 2-36.
|Base 0 means to interpret the base from the string as an integer literal.
==========int()函数说明文档已经写的很清楚了,字符串只接受‘+’‘—’号和纯数字==========
>>> int('-3')
-3
>>> int('+3')
3
>>> int('1.2')
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
    int('1.2')
ValueError: invalid literal for int() with base 10: '1.2'

因此报错,错误在参数字符串型‘1.2’
页: [1]
查看完整版本: 已经转换整型,为什么输入小数后报错