简体   繁体   English

Python3 - 我在这里做错了什么?

[英]Python3 - What am I doing wrong here?

Started programming today. 今天开始编程。 Really interested in getting a head start in my degree next year. 真的有兴趣明年获得我的学位。

I'm using newboston to teach myself and it's going OK so far. 我正在使用newboston教我自己,到目前为止一切顺利。 struggling with a real simple snippet of code though. 尽管如此,还是要用一段真正简单的代码来挣扎。

I want a message to come up saying "What is 1+1." 我想要一条消息说“什么是1 + 1”。 The user inputs an anwser and IF it's 2, print a correct message. 用户输入anwser,如果是2,则打印正确的消息。 If not, print incorrect. 如果没有,打印不正确。

input ("What is 1 + 1\n")
if input is 2:
    print ("correct")
else:
    print("incorrect")

C:\Python31\python.exe "C:/Users/JoeNa/Desktop/Python Study/Experimenting.py"
What is 1 + 1

incorrect

Process finished with exit code 0

Write it as follows: 写如下:

result = input ("What is 1 + 1\n")
if int(result) == 2:
    print("correct")
else:
    print("incorrect")

If you want to handle the result from input(), you have to store it in a new variable. 如果要处理input()的结果,则必须将其存储在新变量中。 After that, if you expect it to always be an integer, cast it using the int keyword. 之后,如果您希望它始终是一个整数,请使用int关键字进行强制转换。

Also, try not to use a variable name that is the same as the input() keyword. 另外,尽量不要使用与input()关键字相同的变量名。

Also, as an additional note, use == instead of is in this case scenario. 另外,作为附加说明,在这种情况下使用==而不是。 I would suggest reading up on the usage of the is keyword vs the equals operator. 我建议阅读is关键字vs equals运算符的用法。

my_val = int(input("What is 1 + 1\n"))

if my_val == 2:
    print ("correct")
else:
    print("incorrect")

input returns a string so you have to cast it to an int . input返回一个字符串,因此您必须将其强制转换为int

Also, don't name your variables after built-in keywords or functions in Python as you could override them and lose access to them when you want to use them later on in your code. 此外,不要在Python内置关键字或函数之后命名变量,因为您可以覆盖它们,并在以后想要在代码中使用它们时失去对它们的访问权限。 Consider this: 考虑一下:

>>> input = 'hello'
>>> s = input('enter your name')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> 

You can't call the input function again in your program because you have set input to a string, that's why the Python interpreter brings up that error. 您无法在程序中再次调用input函数,因为您已将input设置为字符串,这就是Python解释器提出该错误的原因。

The ZetCode Python website has a list of keywords in Python. ZetCode Python网站在Python中有一个关键字列表。

is is used to compare objects by their identity, while == compares two objects by their values. is用于按对象比较对象,而==按其值比较两个对象。 You have to understand these as it could lead to complex errors when you interchange them. 您必须了解这些,因为当您交换它们时可能会导致复杂的错误。

Consider this: 考虑一下:

>>> a = [1,2]
>>> b = [1,2]
>>> a is b
False
>>> a == b
True

>>> id(a)
140109265441288
>>> id(b)
140109265454472
>>> 

a and b are two different objects so they are not the same by their identity but are equal by their values. ab是两个不同的对象,因此它们的身份不同,但它们的值相等。

Several things: 几件事:

  1. input() is a function which reads user input from the keyboard as string input()是一个从键盘读取用户输入为字符串的函数
  2. you call input() but never save the value it returns to a variable 你调用input()但从不保存它返回给变量的值
  3. you compare with "is" instead of "==" (although these may be equivalent in some cases check out the differences and learn when to use which) 你用“是”而不是“==”进行比较(尽管在某些情况下这些可能是等价的,可以查看差异并了解何时使用哪些)
  4. when comparing make sure you don't compare apples with oranges (string with int) 比较时请确保不要将苹果与橙子进行比较(带有int的字符串)

When you use input ("What is 1 + 1\\n") , the user's input is stored as a String (Text). 当您使用input ("What is 1 + 1\\n") ,用户的输入存储为字符串(文本)。 Therefore, you need to convert the String into a integer in order to compare it to another integer. 因此,您需要将String转换为整数,以便将其与另一个整数进行比较。

try the following: 尝试以下方法:

userInput = input ("What is 1 + 1\n")
if int(userInput) == 2 
    print("correct")
else:
    print("incorrect")

int(userInput) will convert string into an integer int(userInput)将字符串转换为整数

Here are a few tips, some of which are a matter of opinion: 以下是一些提示,其中一些是意见问题:

input ("What is 1 + 1\n")

Becomes: 变为:

user_input = input("What is 1 + 1? ")

Where did user_input come from? user_input来自哪里? I just made it up. 我刚刚完成了。 It is just a name which now refers to the answer entered by the user. 它只是一个名称,现在指的是用户输入的答案。 The input() function returns a string, which you must give a name (otherwise its a bit of a waste of time). input()函数返回一个字符串,你必须给它一个名字(否则它有点浪费时间)。 Don't use the name input though, that will replace the built-in input() function! 不要使用名称input ,这将取代内置的input()函数! Personally I don't put a newline (\\n) at the end of the question, but I always put a space. 就个人而言,我没有在问题的最后添加换行符(\\ n),但我总是放一个空格。

So, user_input is of class str (a text string) whereas 2 is of class int (an integer). 因此, user_inputstr类(文本字符串),而2int类(整数)。 You are trying to compare objects of different classes - usually that is not allowed. 您正在尝试比较不同类的对象 - 通常是不允许的。 However, you are not comparing the values, is compares references . 但是,您没有比较这些值, is比较参考 Usually (9 times out of 10) you want to find if values are equal, so use == instead. 通常(10次中的9次)你想要找到值是否相等,所以使用==代替。

if input is 2:
    print ("correct")
else:
    print("incorrect")

Becomes: 变为:

if int(user_input) == 2:
    print("correct")
else:
    print("incorrect")

Notice as well that I have paid attention to being consistent with things like spacing before parentheses. 另请注意,我注意与括号前的间距保持一致。 This is just style, but is worth noting. 这只是风格,但值得注意。 At some point look at PEP008 , which is the style guide for Python. 在某些时候看看PEP008 ,这是Python的风格指南。

You have multiple points of confusion here. 你在这里有多个困惑点。 Let's look at the docs for input : 让我们看一下输入的文档:

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. 然后,该函数从输入中读取一行,将其转换为字符串(剥离尾部换行符),然后返回该行。

So, input() returns a string. 所以, input()返回一个字符串。 You're calling the function in your code, but you're not actually storing the return value anywhere. 您正在调用代码中的函数,但实际上并没有将返回值存储在任何位置。 Good variables are descriptive names. 好的变量是描述性的名称。 In your code you're looking for an answer , so that's a good choice. 在您的代码中,您正在寻找answer ,因此这是一个不错的选择。 That makes the start of your code look like this: 这使得代码的开头如下所示:

answer = input('What is 1+1?\n')

Now if you remember from the documentation, input() returns a string . 现在,如果您记得文档, input()将返回一个字符串

'2'
"2"
'''2'''

These are all representations of strings. 这些都是字符串的表示。

2

As others have mentioned, you can check the type of a variable or value by using the type() function: 正如其他人所提到的,您可以使用type()函数检查变量或值的type()

>>> type(2)
<class 'int'>
>>> type('2')
<class 'str'>

That is a number. 这是一个数字。 If you try to compare a number to a string, they're not equal: 如果您尝试将数字与字符串进行比较,则它们不相等:

>>> 2 == '2'
False

So if we want to get a proper comparison, we'll need to either compare strings or convert the answer to a number. 因此,如果我们想要进行适当的比较,我们需要比较字符串或将answer转换为数字。 While technically either option works, since 1+1 is math and math is about numbers, it's probably better to convert it to a number: 虽然从技术上讲两种选择都有效,但由于1+1是数学而数学是关于数字的,所以将它转换为数字可能更好:

>>> int('2') == 2
True

Aside 在旁边

Currently you're using is . 目前你正在使用的is If you check the python documentation on comparisons , you'll see that is compares object identity. 如果你查看有关比较的python文档,你会看到它is比较对象标识。 But what does that mean ? 但这意味着什么? You can find the identity of an object in Python by using the id() function. 您可以使用id()函数在Python中找到对象的id() You were checking if input is 2: -- which *does** make sense in English, but not in python --and what does that actually check? 你正在检查if input is 2: - 哪个*用英语有意义,但在python中没有用 - 这实际上检查了什么? Well, first off: 好吧,先关闭:

>>> input
<built-in function input>

input is a function. input是一个功能。 So what you're checking is if the input function is the number 2 (not the value two, but the actual object). 所以你要检查的是输入函数是否为数字2 (不是 2,而是实际对象)。 The id is pretty accidental and will probably change between runs of Python. id非常偶然,可能会在Python运行之间发生变化。 Here's what mine reports: 这是我的报告:

>>> id(input)
140714075530368
>>> id(2)
140714073129184

An interesting note - CPython does some interesting things with small numbers , so it's possible that 2 is 2 returns True, but that's not necessarily guaranteed. 一个有趣的注意事项 - CPython使用小数字做一些有趣的事情 ,所以2 is 2 可能返回True,但这不一定能保证。 But this is: 但这是:

val = 2
other_val = val
val is other_val  # Will be true

Putting it all together 把它们放在一起

Well, now that we know what to do, here is what your program looks like: 那么,既然我们知道该怎么做,这就是你的程序的样子:

answer = input('What is 1+1?\n')
if int(answer) == 2:
    print('Correct!')
else:
    print('Incorrect')

What if someone provides an input that isn't a number, though? 但是,如果某人提供的输入不是数字呢? Depending on how robust you want your program, you can approach it one of two ways. 根据您对程序的强大程度,您可以采用以下两种方式之一。 The first, ensuring that the string is just digits: 第一个,确保字符串只是数字:

if answer.isdigit() and int(answer) == 2:
    print('Correct!')

Or, you can catch the exception that's raised: 或者,您可以捕获引发的异常:

try:
    if int(answer) == 2:
        print('Correct!')
    else:
        print('Incorrect!')
except ValueError:
    print('***ERROR*** {!r} is not a number!'.format(answer))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM