来自用户的输入 [英] input from user

查看:47
本文介绍了来自用户的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中获取用户输入是一个非常基本的疑问,Python 是否将任何输入作为字符串并将其用于计算,我们必须将其更改为整数还是什么?在以下代码中:

It's a very basic doubt in Python in getting user input, does Python takes any input as string and to use it for calculation we have to change it to integer or what? In the following code:

a = raw_input("Enter the first no:")
b = raw_input("Enter the second no:")


c = a + b
d = a - b
p = a * b
print "sum =", c
print "difference = ", d
print "product = ", p  

Python 出现以下错误:

Python gives following error:

Enter the first no:2
Enter the second no:4

Traceback (most recent call last):
File "C:\Python27\CTE Python Practise\SumDiffProduct.py", line 7, in <module>
d=a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'

谁能告诉我为什么我会收到这个错误?

Can someone tell please why am I getting this error?

推荐答案

是的,每个输入都是字符串.但是试试吧:

Yes, every input is string. But just try:

a = int(a)
b = int(b)

在你的代码之前.

但请注意,用户可以使用 raw_input 传递他喜欢的任何字符串.安全的方法是 try/except 块.

But be aware of the fact, that user can pass any string he likes with raw_input. The safe method is try/except block.

try:
    a = int(a)
    b = int(b)
except ValueError:
    raise Exception("Please, insert a number") #or any other handling

所以它可能是这样的:

try:
    a = int(a)
    b = int(b)
except ValueError:
    raise Exception("Please, insert a number") #or any other handling
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p  

来自文档:

该函数然后从输入中读取一行,将其转换为字符串(去掉尾随的换行符),然后返回.

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

这篇关于来自用户的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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