猜数字是对还是错? Python [英] Guessing a number, true or false? Python

查看:165
本文介绍了猜数字是对还是错? Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给某物分配一个值,然后尝试让某人猜测该值.我已经尝试了一些类似的方法,但是似乎无法使其工作……:

I want to assign something a value and then try and get someone to guess that value. I have tried something along the lines of this but I can't seem to get it to work...:

   foo = 1
   guessfoo = input('Guess my number: ')
   if foo == guessfoo:
       print('Well done, You guessed it!')
   if foo != guessfoo:
       print('haha, fail.')

为什么这行不通?我应该怎么做呢?我是初学者,请帮忙!

Why doesn't this work? And how should I be doing it? I am a beginner at this, please help!

推荐答案

使用python 版本3 :

input()返回一个"str"(字符串)对象.字符串与整数比较将返回False:

input() returns a 'str' (string) object. A string compares to an integer returns False :

1 == '1'
False

您必须像这样投射您的输入:

You must cast your input like that :

guessfoo = int(input('Guess my number: '))

别忘了尝试...除非输入结果无法转换为整数.

Don't forget to try...except if the result of the input cannot be casted into an int.

完整的示例代码:

try:
    foo = 1
    guessfoo = int(input('Guess my number: '))
    if foo == guessfoo:
        print('Well done, You guessed it!')
    else:
        print('haha, fail.')
except ValueError:
    # cannot cast your input
    pass



使用python 版本2 :

感谢您的评论:

在以前的版本中,输入将评估字符串,因此,如果用户键入1,则输入将返回一个整数.

In previous versions, input would eval the string, so if the user typed in 1, input returned an int.

输入或您的原始代码:

$ python2 test.py 
Guess my number: 1
Well done, You guessed it!

这篇关于猜数字是对还是错? Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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