【问题标题】:basic python what is wrong with this script基本的python这个脚本有什么问题
【发布时间】:2017-03-11 00:14:36
【问题描述】:

我开始学习 Python。我写了这个脚本,但是当我输入 Kevin 和 0 时,它显示“Hello world”而不是“Kevin 很棒”。

print ("hello world")
myName = input("what is your name?")
myVar = input("Enter a number: ")

if( myName == "Kevin"  and myVar == 0): 
   print ("Kevin is great!")
elif(myName == "Bob"):
   print("You are not great")
else:
   print("Hello world")

【问题讨论】:

  • 您需要先将myVar 转换为int。或者检查myVar == '0' 而不是myVar == 0。因为input() 返回的是str(字符串)而不是int
  • 在我看来,首先从 Python 2 开始。此外,出于安全原因,请使用 raw_input 而不是 input。
  • @Ambitions 我不会向刚开始学习 python 的人推荐 python 2。 Python 2 很快就会停止支持,所以无论如何你都必须学习 Python 3。
  • 非常感谢@Farhan.K

标签: python-3.x


【解决方案1】:

input() 函数返回一个字符串(在这种情况下,当您输入 0 时,它将返回“0”),因此您可以使用 int() 函数将其解析为字符串,如下所示:

print ("hello world") 
myName = input("what is your name?") 
myVar = input("Enter a number: ")

myVar = int(myVar)
if (myName == "Kevin" and myVar == 0):
    print ("Kevin is great!") 
elif (myName == "Bob"): 
    print("You are not great") 
else: 
    print("Hello world")

有关更多信息,您可以查看文档:

Input() Documentation

Int() Documentation

【讨论】:

    【解决方案2】:

    您的第二个变量将提示用户输入字符串而不是整数。您需要在 "input(" 之前添加 "int(" 或 "float(") 以将字符串更改为整数。例如:

    print ("hello world") myName = input("what is your name?") myVar = int(input("Enter a number: ")) if( myName == "Kevin" and myVar == 0): print ("Kevin is great!") elif(myName == "Bob"): print("You are not great") else: print("Hello world") code here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多