简体   繁体   English

学习编码,我有一个关于 IF on python 的问题

[英]Learning to code, I have a question about IF on python

So I'm learning to code on Python and have some questions about how the IF statement works here since it seems to be ignoring my elif's.所以我正在学习在 Python 上编写代码,并且对 IF 语句在这里的工作方式有一些疑问,因为它似乎忽略了我的 elif 语句。

The only result I get is the last one so I tried putting other options and erasing that last one and the result is I just get no answer at all.我得到的唯一结果是最后一个,所以我尝试添加其他选项并删除最后一个,结果是我根本没有得到任何答案。

print('name:')
name=input()
if name=='John':
  print('Sup John')
elif name!='John':
  print('Sup stanger')

print('age?')
age=input()
if (age.isdigit())==26:
  print('Yup')
elif (age.isdigit())<=0:
  print('WUT?!')
elif (age.isdigit())>=100:
  print('Are you inmortal?')
elif (age.isdigit())<=25: #Only result I get no matter what
  print('Too young')

It's not ignoring your elifs.这不是忽略你的 elifs。 You have just misunderstood what isdigit is.你只是误解了isdigit是什么。

isdigit tells you whether all the characters in a string are digits or not. isdigit告诉您字符串中的所有字符是否都是数字。 It does not convert a string to a digit;它不会将字符串转换为数字; it returns True or False.它返回 True 或 False。

To convert to an integer, use int .要转换为整数,请使用int

if int(age) == 26:
   ...

Since you've mentioned you're trying to learn Python, I'll be a little explicit with my answer.既然您已经提到您正在尝试学习 Python,那么我的回答会稍微明确一点。 isdigit checks if a string is numeric or not. isdigit检查字符串是否为数字。 Let's take an example.让我们举个例子。

>>> s = "23"
>>> k = "abc"
>>> type(s)
<class 'str'>
>>> type(k)
<class 'str'>
>>> s.isdigit()
True
>>> k.isdigit()
False

In your case, the first if checks the string and gets a True and the code exists the conditional.在您的情况下,第一个if检查字符串并获得 True 并且代码存在条件。 So your code should look something like this.所以你的代码应该是这样的。

print('name:')
name = input()
if name=='John':
  print('Sup John')
else:
  print('Sup stanger')

print('age?')
age = input()
if int(age) == 26:
  print('Yup')
elif int(age) <= 0:
  print('WUT?!')
elif int(age) >= 100:
  print('Are you inmortal?')
elif int(age) <= 25: #Only result I get no matter what
  print('Too young')

Hope this helps.希望这可以帮助。

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

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