使用int()将用户的输入从raw\u input()转换为

2024-03-29 09:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python2.7.x中的函数,我正在使用的书中的一个建议是征求用户的输入以获取脚本的值。关于如何在函数中使用raw_input的建议如下:

You need to use int() to convert what you get from raw_input()

我还不知道如何使用int()。到目前为止,我一直在努力:

def cheeses_and_crackers(cheeses, crackers):
    print "You have %d types of cheeses." % cheeses
    print "You have %d types of crackers." % crackers
    print "That is a lot of cheese and crackers!\n"

print "How many cheeses do you have?"
cheeses1 = raw_input("> ")
int(cheeses1)

print "How many types of crackers do you have?"
crackers1 = raw_input("> ")
int(crackers1)

cheeses_and_crackers(cheeses1, crackers1)

尝试运行此命令时,出现的错误如下:

TypeError: %d format: a number is required, not str

我在猜测如何使用int(),因此我也希望能在基本语法方面得到一些帮助。在


Tags: andof函数youinputrawhaveint
1条回答
网友
1楼 · 发布于 2024-03-29 09:21:56

int不改变用户输入(字符串,实际上是不可变的),而是构造一个整数,然后返回它。在

由于没有为返回值指定任何名称,因此返回值将丢失。在

演示:

>>> user_input = raw_input('input integer > ')
input integer > 5
>>> type(user_input)
<type 'str'>
>>> input_as_int = int(user_input)
>>> input_as_int
5
>>> type(input_as_int)
<type 'int'>
>>> type(user_input) # no change here
<type 'str'>

相关问题 更多 >