您如何比较2个变量与不同类型的数据?

比较两个名为target的变量,并使用Python 3猜测一个是整数,一个是字符串。


import random

import sys

target = random.randint(1, 20)

name = input ('Hello, what is your name?')

print ('Hello, %s. I am thinking of a number from 1 to 20. You will have 3 tries, and after each try, I will tell you if the number that I am thinking of is lower or higher. Try to guess it!' % name) 

guess = input ('What number do you think I am thinking of?')

if guess == target:

    print ('Congratulations! You won! Please play again!')

    sys.exit()

else:

    print ('You did not guess the number correctly.')

    if target < guess:

        print ('The number that I am thinking of is smaller than your guess. Try again')

    else:

        print ('The number that I am thinking of is larger than your guess. Try again!')


慕工程0101907
浏览 134回答 1
1回答

慕后森

您可以通过以下方式简单地将输入从字符串解析为整数:guess&nbsp;=&nbsp;int(input('What&nbsp;number&nbsp;do&nbsp;you&nbsp;think&nbsp;I&nbsp;am&nbsp;thinking&nbsp;of?'))然后,您可以将其自由地与所需的任何整数进行比较。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python