python - 您如何将 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!')
解决方案
您可以通过以下方式简单地将输入从字符串解析为整数:
guess = int(input('What number do you think I am thinking of?'))
然后你可以自由地将它与你想要的任何整数进行比较。
推荐阅读
- python - 将 xarray 数据变量重新分配给 xarray 坐标
- java - jsoup 在尝试抓取 google 时返回太多请求错误
- r - flow_images_from_directory 保存增强图像
- javascript - 在 mongoose 中查询超过 X 分钟的文档
- jquery - jQuery - 仅允许数字和限制字符 - 突出显示文本时不起作用
- angular - Angular删除特定的表单验证器,而不是Formbuilder中的所有验证器
- reactjs - 反应组件中的 Typscript 可选参数
- salesforce - 使用 force:recordData 将记录添加到 Salesforce 中的 Campaign 对象
- excel - 如何将单元格或范围传递到 InStr?
- excel - .copy 在将当前工作簿复制到新工作簿时工作不一致