简体   繁体   English

我在学习如何使用 STR、INT 和 ELIF 时遇到问题

[英]I am having troubles with learning how to use STR and INT and ELIF

age = str(input("how old are you?"))
if age >= 18:
  print("have a beer")
elif age == 17:
  print("have a car")
elif age == 16: 
  print("have a book")
else: print("go away")
 

the error that pops up says Typeerror: '>=' not supported between instances of 'str't 'int' i am starting this for school and i am confused, my teacher just left us and i dont know what to do.弹出的错误说 Typeerror: '>=' not supported 在 'str't 'int' 的实例之间我正在为学校开始这个,我很困惑,我的老师刚刚离开我们,我不知道该怎么做。 do i change the >= to a > or do i change the str to and int?我将 >= 更改为 > 还是将 str 更改为和 int?

Convert to int (or to numeric type in general) in order to do numeric comparisons later, such as >= :转换为int (或一般的数字类型)以便稍后进行数字比较,例如>=

age = int(input("how old are you?"))

What it means is that you're trying to compare a string with a number in a way that is not valid >= .这意味着您正在尝试以无效的方式将字符串数字进行比较>=

str converts the input to a string. str将输入转换为字符串。

int converts the input, where possible, to an integer. int在可能的情况下将输入转换为 integer。

So, yes, please , change str to int .所以,是的,请将str更改为int

Note笔记

age = str(input("how old are you?"))

that this is redundant, as input itself returns string这是多余的,因为input本身返回字符串

If the prompt argument is present, it is written to standard output without a trailing newline.如果存在提示参数,则将其写入标准 output 而不带尾随换行符。 The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. function 然后从输入中读取一行,将其转换为字符串(去除尾随换行符),然后返回。

ie this give same effect as writing即这给出了与写作相同的效果

age = input("how old are you?")

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

相关问题 我在弦上遇到麻烦 - I am having troubles with a string 我有这个错误 TypeError: &#39;&lt;&#39; not supported between &#39;str&#39; and &#39;int&#39; - i am having this error TypeError: '<' not supported between instances of 'str' and 'int' 我在写入文本文件时遇到问题,因为它说我的行应该是 str 而不是 int - I am having trouble writing into a text file because it says my line should be an str and not an int 我在 python 中的 if-elif 语句中遇到问题 - I am having trouble in if-elif statements in python 我不确定如何解决:'TypeError:只能将 str(不是“int”)连接到 str' - I am unsure how to fix: 'TypeError: can only concatenate str (not "int") to str ' 我在使用Python函数时遇到麻烦,有人可以帮我吗? - I am having troubles with Python functions, can someone help me? 我在 python 中的文件和目录上测试模块时遇到问题 - I am having troubles testing the module on file and on directory in python 我在获取列表而不是绑定方法时遇到问题 - I am having troubles getting the list instead of an bound method 为什么我无法使用 try-except 将 str 转换为 int? - Why am I unable to use try-except to convert str to int? 如何解决错误:只能将 str(不是“int”)连接到 str 但我正在将字符串添加到字符串 - How do I resolve error : can only concatenate str (not “int”) to str yet I am adding string to a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM