Python is not calling fucntions properly
Posted By: Anonymous
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 bad guy 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("nnGAME 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. nnI 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)
Guys I have just started on learning python. In the code below I am asking the user for inputting a letter and checking if the letter matches with the letter in a string xy
then I intend to print a complement by calling the function. However the code is acting beyond my understanding. The code is not at all calling the printcomplement()
until the entire loop is completed(The outermost for loop). Now when the letter is not equal to the intended letter of the string xy
it is not even printing the dis(which I am doing by calling printdis()
). Even the print("complement")
statement is not executing when the condition is hit. Neither is the print(letter+str(i))
statement executing. This function over here is just a part of a larger source code. If any body wants to take a peek at the full code please let me know. Any help will be really appreciated. (I have added the full source code) I have individually checked all the functions except the game()
, since that is the fucntion which controls all the other functions. (ps:- There are some harsh statements written into the code, since this was just a fun project for me. Please don’t mind)
Solution
Running your code os.system(‘cls’) is clearing the screen before the input is read in the loop. This makes it seem that there is no output is being displayed when it’s really being overwritten.
A quick test can be done to confirm that this is the problem. To do this we add another input read in the game function. like so:
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: ")
This should change the loop to now look like this:
Now if you run your application with that small change, the output should start showing up because it’s not being immediately cleared.
Once you can confirm the this is the problem it should be possible to repair the problem by simply shifting the print statement to be above the input line.
One way you could be like this:
Refactor the dis and complement methods to return a string rather than printing it out directly
Complement method refactored:
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 method refactored:
sick_burns = [
"Fool",
"You will end up killing the fool and then I will hang you next.",
"What a bad guy 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"
Game method refactored to print out feedback just before input
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
Remember feedback is from the previous loop, but it’s printed after the for loop wipes the output. You can message me if you have any questions
Answered By: Anonymous
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.