首页 > 解决方案 > Python 没有正确调用函数

问题描述

    import os
import random
import time
import math

def stringmanipulator(xy, y=40):
    xy= xy.lower()
    x = []
    x = list(xy)
    length = len(x)
    y = int(math.floor(length * (y/100)))
    while(y):
        r =int(random.random()*(length-1))
        if(x[r] != '_' and x[r] != ' '):
            x[r] = '_'
            y = y-1
            
    return x

def printcomplement():
    x = int(random.random()*11)
    if(x == 0):
        print("well done!!")
    elif(x == 1):
        print("keep going!!")
    elif(x == 2):
        print("YOU can save him!!")
    elif(x == 3):
        print("You are the hero no one wanted but everyone deserves.")
    elif(x == 4):
        print("Genius kid.")
    elif(x == 5):
        print("You are Smart, not kidding.")
    elif(x == 6):
        print("You are one who will destroy my carrer  using your intellect.")
    elif(x == 7): 
        print("The most kind hearted person I have ever seen till now. Yes I am talking about you")
    elif(x == 8):
        print("You nailed  it.")
    elif(x == 9):
        print("AND I thought the game was hard.")
    elif(x == 10):
        print("I will find more difficult words to challenge you with.")
    elif(x == 11):
        print("How about you put another life on risk after this round.")
        
        
def printdis():
    x = int(random.random()*11)
    if(x == 0):
        print("Fool")
    elif(x == 1):
        print("You will end up killing the fool and then I will hang you next.")
    elif(x == 2):
        print("What a piece of shit you are.")
    elif(x == 3):
        print("Hey disgrace to humanity.")
    elif(x == 4):
        print("Don't cry after the man is dead. You killed him, I gave you a chance to save him.")
    elif(x == 5):
        print("Dumbass!!")
    elif(x == 6):
        print("You know what it was my mistake to let such an idiot play.")
    elif(x == 7): 
        print("This is your last game. I don't want fools playing this game.")
    elif(x == 8):
        print("I see you are already crying.")
    elif(x == 9):
        print("Even the guy who's life is line is laughing at your  stupidity.")
    elif(x == 10):
        print("My 120 years old grandma has a sharper brain than yours.")
    elif(x == 11):
        print("Get lost, YOU useless, moronic, unworthy pile of garbage.")


def hangman(i = 0):
    if(i == 0):
        print("___________")
        print("|         |")
        print("|         |")
        print("|      ")
        print("|      ")
        print("|        ")
        print("|       ")
        print("|       ")
        print("|")
    
    elif(i == 1):
        print("___________")
        print("|         |")
        print("|         |")
        print("|        ( ) ")
        print("|        ")
        print("|        ")
        print("|       ")
        print("|       ")
        print("|")
        
    elif(i == 2):
        print("___________")
        print("|         |")
        print("|         |")
        print("|        ( ) ")
        print("|         |  ")
        print("|         | ")
        print("|       ")
        print("|       ")
        print("|")
    
    elif(i == 3):
        print("___________")
        print("|         |")
        print("|         |")
        print("|        ( ) ")
        print("|       \\ | / ")
        print("|         | ")
        print("|        ")
        print("|       ")
        print("|")
        
    elif(i == 4):
        print("___________")
        print("|         |")
        print("|         |")
        print("|      \\ ( ) /")
        print("|       \\ | / ")
        print("|         ")
        print("|        ")
        print("|       ")
        print("|")
        
    elif(i == 5):
        print("___________")
        print("|         |")
        print("|         |")
        print("|      \\ ( ) /")
        print("|       \\ | / ")
        print("|         | ")
        print("|        / \\")
        print("|       ")
        print("|")
        
    elif(i == 6):
        print("___________")
        print("|         |")
        print("|         |")
        print("|      \\ ( ) /")
        print("|       \\ | / ")
        print("|         | ")
        print("|        / \\")
        print("|       /   \\")
        print("|")
        print("\n\nGAME OVER. You have succesfully killed a person. Better luck next time")

def game(xy, y):
    x=[]
    i = 0
    letter = ''
    x = stringmanipulator(xy, y)
    xy = xy.lower()
    # os.system('cls')
    
    for index in range(len(x)):
        
        if(x[index] == '_'):
            
            while(letter != x[index]):
                _= os.system('cls')
                hangman(i)
                
                for char in range(len(x)):
                    print(x[char], end=' ')
                print("\n")
             
                letter = input("Enter the letter in the first blank: ")
                print(letter+str(i))
                if(letter == xy[index]):
                    print("complement")
                    x[index] = letter
             
                else:
                    printdis()
                    i+=1
                    
                    


dictionary ={}

dictionary["films"] = ["A Space OdysseY", "The GodFather", "Citizen Kane", "Raiders of the lost Ark", "Seven Samurai", "There will be Blood", "Casablanca", "Vertigo", "Notorious", "City Lights"]

dictionary["cities"] = ["Tokyo", "Mecca", "Beijing", "London", "Kolkata", "Washington DC", "Mumbai", "Mexico City", "Delhi", "Shanghai"]

dictionary["fruits"] = ["Damson Plum", "Pomelo", "Blood Orange", "Kumquat", "Blackcurrant", "Acerola", "Avocado", "Pomegrenate", "Apple", "Mango"]

dictionary["country"] = ["Djibouti", "Azerbaijan Azerbaijan,", "Venzuela", "Armenia", "Khazakhstan", "Bangladesh", "Saudi Arabia", "United Kingdom", "United States of America", "India"]

dictionary["flowers"] = ["Monkey Face Orchid", "Naked Man Orchid", "Dancing Girls", "Chamber Maids", "Hibiscus", "Marigold", "Tulip", "Lilies", "Daisy", "Hydrangea"]

print("WELCOME TO THE GAME HANGMAN.\n TAKE THE GAME SERIOUSLY SINCE THE LIFE OF A MAN IS DEPENDING ON YOUR KNOWLEDGE. \n\nI DON'T KNOW HOW MANY CHANCE YOU WILL GET, NOT MANY THAT I CAN CONFIRM.\n SO TRY TO SAVE YOUR FELLOW HUMAN OR LET IT BE MY FOOD. HAHAHAHAHAHAHAHAHAH!!!!!!!")

# x = input("Press 1 for films, 2 for cities, 3 for fruits, 4 for country and 5 for flowers (The most beautiful are usually the hardest): ")
# x = int(x)
x = int(input("Enter a number between 1 and 5: "))
if((x < 1) or(x > 5)):
    print("What a moron you are. You couldn't even choose one of the option properly game over good bye, tata, cya")
    x = random.randint(1,5)
    time.sleep(10)
    print("Just kidding you still get to play the game but now I will decide what kind of object you have to guess.")

y = int(input("Enter 40 for easy, 60 for medium and 80 for hard: "))

i = 0
xy = ""
 
r = random.randint(0,9)

if(x == 1):
    xy = dictionary["films"][r]
    print("FILMS:")
elif(x == 2):
    xy = dictionary["cities"][r]
    print("CITIES:")
elif(x == 3):
    xy = dictionary["fruits"][r]
    print("FRUITS:")
elif(x == 4):
    xy = dictionary["country"][r]
    print("COUNTRY:")
elif(x == 5):
    xy = dictionary["flowers"][r]
    print("FLOWERS:")
# hangman(0)    
game(xy, y)

伙计们,我刚刚开始学习python。在下面的代码中,我要求用户输入一个字母并检查该字母是否与字符串中的字母匹配,xy然后我打算通过调用该函数来打印一个补码。然而,代码的行为超出了我的理解。printcomplement()直到整个循环完成(最外层的for循环),代码才完全调用。现在,当字母不等于字符串的预期字母时,xy它甚至不会打印 dis(我正在通过调用来执行此操作printdis())。当条件被满足时,甚至print("complement")语句也没有执行。也不是print(letter+str(i))语句执行。这里的这个函数只是更大源代码的一部分。如果有人想查看完整代码,请告诉我。任何帮助将不胜感激。(我已经添加了完整的源代码)我已经单独检查了除 之外的所有功能game(),因为这是控制所有其他功能的功能。(ps:-代码中写了一些苛刻的语句,因为这对我来说只是一个有趣的项目。请不要介意)

标签: pythonfunction

解决方案


运行代码 os.system('cls') 在循环中读取输入之前清除屏幕。这使得它看起来在真正被覆盖时没有显示输出。

循环播放

可以进行快速测试以确认这是问题所在。为此,我们在游戏函数中添加另一个输入读取。像这样:

def game(xy, y):
    x=[]
    i = 0
    letter = ''
    x = stringmanipulator(xy, y)
    xy = xy.lower()
    # os.system('cls')
    
    for index in range(len(x)):
        
        if(x[index] == '_'):
            
            while(letter != x[index]):
                _= os.system('cls')
                hangman(i)
                
                for char in range(len(x)):
                    print(x[char], end=' ')
                print("\n")
             
                letter = input("Enter the letter in the first blank: ")
                print(letter+str(i))
                if(letter == xy[index]):
                    print("complement")
                    x[index] = letter
             
                else:
                    printdis()
                    i+=1

                input("Press any key to continue: ")

这应该将循环更改为现在如下所示:

改变循环

现在,如果您运行应用程序时进行了微小的更改,输出应该会开始显示,因为它不会立即被清除。

一旦您可以确认这是问题所在,应该可以通过简单地将打印语句移动到输入行上方来修复问题。

一种方式你可能是这样的:

重构dis和complement方法返回一个字符串,而不是直接打印出来

补码方法重构:

complements = [
    "well done!!",
    "keep going!!",
    "YOU can save him!!",
    "You are the hero no one wanted but everyone deserves.",
    "Genius kid.",
    "You are Smart, not kidding.",
    "You are one who will destroy my carrier using your intellect.",
    "The most kind hearted person I have ever seen till now. Yes I am talking about you",
    "You nailed  it.",
    "AND I thought the game was hard.",
    "I will find more difficult words to challenge you with.",
    "How about you put another life on risk after this round."
]


def complement() -> str:
    return "\n" + complements[int(random.random() * len(complements))] + "\n"

    

Dis方法重构:

sick_burns = [
    "Fool",
    "You will end up killing the fool and then I will hang you next.",
    "What a piece of shit you are.",
    "Hey disgrace to humanity.",
    "Don't cry after the man is dead. You killed him, I gave you a chance to save him.",
    "Dumbass!!",
    "You know what it was my mistake to let such an idiot play."
    "This is your last game. I don't want fools playing this game."
    "I see you are already crying."
    "Even the guy who's life is line is laughing at your  stupidity."
    "My 120 years old grandma has a sharper brain than yours."
    "Get lost, YOU useless, moronic, unworthy pile of garbage."
]


def dis() -> str:
    return "\n" + sick_burns[int(random.random() * len(sick_burns))] + "\n"

重构游戏方法以在输入前打印出反馈

 def game(xy, y):
    x=[]
    i = 0
    letter = ''
    feedback = ''
    x = stringmanipulator(xy, y)
    xy = xy.lower()
    # os.system('cls')
    
    for index in range(len(x)):
        
        if(x[index] == '_'):
            
            while(letter != x[index]):
                _= os.system('cls')
                hangman(i)
                
                for char in range(len(x)):
                    print(x[char], end=' ')
                print("\n")
             
                print(feedback) # prints feedback of the previous loop

                letter = input("Enter the letter in the first blank: ")
                print(letter+str(i))
                if(letter == xy[index]):
                    feedback = complement()
                    x[index] = letter
             
                else:
                    feedback = dis()
                    i += 1

请记住反馈来自上一个循环,但它是在 for 循环擦除输出后打印的。有问题可以给我留言


推荐阅读