Python变量不打印

时间:2017-01-04 05:25:39

标签: python

我的编程课中有一个项目用python创建一些东西,我决定制作一个pokedex。但是不确定为什么当我要求它输入1时,它会返回没有的pokenumber。

import random
import time

print "Hello new Trainer!"
time.sleep(1.6)
print "I am your Kanto region Pokédex"
time.sleep(2.3)
print "Please enter your name below so I may know what to call you."
time.sleep(2)
name = raw_input("Name:")
time.sleep(1)
print "Hello %s, it is nice to meet you" % (name)
time.sleep(2)
print "I am a Pokédex, a Pokédex is a database of Pokémon."
time.sleep(3)
print "This  Pokédex is specific for Pokémon in the Kanto region."
time.sleep(3.5)
print "All Pokémon have an assigned number that corresponds to that         certain Pokémon species"
time.sleep(4)
print "For example, Pikachu is the 25th entry in the Pokédex!"
time.sleep(3)
print "When you enter a Pokémon's # it will bring up all available    information on that Pokémon"
time.sleep(5)
print "Please enter a number between 1 and 151 to learn about the Pokémon associated to that number."
Bulbasaur = "Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger."

userpoke = raw_input("Pokémon #:")
def userpoke():
  if userpoke == 1:
    print (Bulbasaur)

3 个答案:

答案 0 :(得分:1)

raw_input()解析您键入的字符串。您需要使用int()将其强制转换为整数,或者您可以轻松将其与字符串"1"进行比较,而不仅仅是整数1

编辑:作为一个刚刚指出的评论者,你还有一个变量和一个同名的函数:

userpoke = raw_input("Pokémon #:")
def userpoke():
  if userpoke == 1:
    print (Bulbasaur)

在这种情况下,userpoke语句中的if实际上是指函数,而不是变量。我建议你做这样的事情:

def userpoke():
  pkmn_num = raw_input("Pokémon #:")
  if pkmn_num == "1":
    print (Bulbasaur)

答案 1 :(得分:0)

最后几行有几个问题:

userpoke = raw_input("Pokémon #:")

这将从用户输入中读取一个字符串,并将其保存在变量userpoke中。

def userpoke():
  if userpoke == 1:
    print (Bulbasaur)

这将覆盖先前创建的变量userpoke,并将其替换为检查其自身的函数对象是否等于整数1的函数。此函数也从不被调用。

请尝试以下方法。这为函数使用了不同的名称,以便不覆盖先前创建的变量,在尝试将其与整数进行比较之前将userpoke转换为整数,然后实际调用该函数。

userpoke = raw_input("Pokémon #:")

def print_userpoke_details():
  if int(userpoke) == 1:
    print (Bulbasaur)

print_userpoke_details()

更好的方法是避免使用全局变量:

def print_userpoke_details(userpoke):
  if int(userpoke) == 1:
    print (Bulbasaur)

userpoke = raw_input("Pokémon #:")
print_userpoke_details(userpoke)

答案 2 :(得分:0)

你应该有diff函数名。函数名称和变量名称相同,请尝试以下更改:

def _userpoke():
  if userpoke == '1':
    print (Bulbasaur)

_userpoke()

可能会对你有帮助。