Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am making a program where the user inputs some text, and I wan't all the characters in that text that is not in the variable "alfabet" to be changed to "?". How can I do this? I also want a to do it in two functions, main and clean_text. My code looks like this now:
def clean_text():
for char in text:
if char in alfabeth:
continue
elif char not in alfabeth:
#don't know what to do here
#text[] = "?"
def main():
userInput = input("type in text: ")
text = list(userInput)
if__name__ == "__main__":
main()
clean_text(text)
This would be the basic code you need:
alfabeth = 'abcdefghijklmnopqrstuvwxyz'
text_in = list(input('What ever'))
for x in range(len(text_in)):
if text_in[x] in alfabeth:
continue
else:
text_in[x] = '?'
text_in = "".join(text_in)
print(text_in)
If you want you can define everything as one function or two or what ever you like.
Hope it helps
This is how it can look with functions. It worked for me.
alfabeth = 'abcdefghijklmnopqrstuvwxyz'
def clean_text(text_in, alfabeth):
for x in range(len(text_in)):
if text_in[x] in alfabeth:
continue
else:
text_in[x] = '?'
def main():
global UsrInput
UsrInput = list(input('type in text: '))
return UsrInput
if __name__ == "__main__":
main()
clean_text(UsrInput, alfabeth)
print("".join(UsrInput))
You have to return something to be able to assign that user_input to a variable to pass into clean_text(). Here is a working version of your project. This will handle multiple words separated by space as well.
def clean_text(word):
alphabeth = 'vshthstmpd'
for idx, item in enumerate(word):
if item == ' ':
pass
elif item not in alphabeth:
word[idx] = '?'
return ''.join(word)
def main():
user_input = input('Type in text: ')
text = list(user_input)
return text
if __name__ == '__main__':
text = main()
print(clean_text(text))
Type in text: vash the stampede
v?sh th? st?mp?d?
Related
I am working on a stupid yet funny practice program to improve my understanding of OOP in Python.
The program is meant to randomly generate some band names from a randomly selected adjective and another randomly selected noun - producing a lot of hilarious band names.
For the most part, the program works fine, but for some reason, there are some problems with the if-statements and the while loop in the menu(self)- method all the way down in the BandList class.
My hypothesis is that there is something wrong with the nesting of the else-if statements, or that the loop doesn't manage to advance the loop when I call on the self._generateBand() method in line 60 due to some technicality I'm not aware of. Either way, I'm not sure.
However, my question is:
Why does my loop stop at the line self._writeBand() and not continue executing the code that follows? (As shown below)
done = False
while done != True:
print("\n=============== BAND NAME GENEREATOR ==================")
start = input("\nDo you want to generate a list of bandnames? (y/n): ")
if start.lower() == "y":
self._generateBand()
self._writeBand() #The loop stops here for some reason and asks the same question over and over.
#The program won't execute this part of the code.
inp = ("\nDo you want to save these band names? (y/n): ")
if inp.lower() == "y":
outfile = input("What do you want to name the file?: ")
self._saveBand(f"{oufile}.txt")
If anyone can help me fix this, I would be super grateful.
In advance: Thank you for your help.
The complete program is pasted in below
import random
class Band:
def __init__(self, name):
self._Bandname = name
def __str__(self):
return f"{self._Bandname}"
def hentName(self):
return self._Bandname
class BandList:
def __init__(self):
self._BandList = []
def _readFile(self, filename1, filename2):
with open(filename1) as infile1, open(filename2) as infile2:
lineAdjective = infile1.read().splitlines()
lineNoun = infile2.read().splitlines()
adjective = random.choice(lineAdjective)
noun = random.choice(lineNoun)
return f"{adjective} {noun}"
def _saveBand(self, filename):
with open(filename, "w") as outfile:
for j, i in enumerate(self._BandList):
outfile.write(f"Nr: {j}\t-{i}\n")
def _generateBand(self):
num = int(input("\nHow many band names would you like to generate?: "))
for i in range(num):
bandname = f"The {self._readFile('adjective.txt', 'noun.txt')}s"
self._BandList.append(Band(name= bandname))
def _writeBand(self):
print("\n========= Genererte bandname =========")
for i in self._BandList:
print(i)
#print(i.hentName())
def _deleteBand(self):
self._BandList.clear()
def _writeGoodbyeMsg(self):
print("\n============ PROGRAM TERMINATING ================")
print("\t- thanks for using the program, goodbye!")
def menu(self):
done = False
while done != True:
print("\n=============== BAND NAME GENEREATOR ==================")
start = input("\nDo you want to generate a list of bandnames? (y/n): ")
if start.lower() == "y":
self._generateBand()
self._writeBand() #This is probably where the bug is...
inp = ("\nDo you want to save these band names? (y/n): ")
if inp.lower() == "y":
utfil = input("What do you want to name the file?: ")
self._saveBand(f"{utfil}.txt")
elif inp.lower() == "n":
self._deleteBand()
inp2 = input("Do you want to generate more band names? (y/n)?: ")
if inp2.lower() == "y":
self._generateBand()
elif inp2.lower() == "n":
done = True
self._writeGoodbyeMsg()
else:
print("Unknown command, please try again")
else:
self._writeGoodbyeMsg()
done = True
if __name__ == '__main__':
new = BandList()
new.menu()
You're missing an input call on your 2nd question for saving the band names. It should be:
inp = input("\nDo you want to save these band names? (y/n): ")
It does work. You just haven't given any values in self._BandList.
Its returning "BandList": null.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i have a short question, im trying to make a quiz program, however. i want a functions data to be shared across the program,
so how do i make so the ask function gen get the data from getQuestion?
import random
All_questions = ["whats obamas last name ","Riclug is snygg ","Are traps gay "]
questions_Right = ["care","no","no"]
points = 0
tries = 3
ListNumber = len(All_questions)
def getQuestion():
question_number = random.randint(0, ListNumber - 1)
right_anwser = questions_Right[question_number]
Question = All_questions[question_number]
def ask(Question,right_anwser):
print("The question is: ")
anwser = input(Question+": ").casefold()
if anwser == right_anwser:
print("yes,", right_anwser,"was right\n")
All_questions.remove(Question)
questions_Right.remove(right_anwser)
else:
print("Sorry, but the answer was", right_anwser,"\n")
while True:
if ListNumber == 0:
print("Game over")
break
else:
print(ListNumber)
getQuestion()
ask()
print(All_questions)
import random
All_questions = ["whats obamas last name ","Riclug is snygg ","Are traps gay "]
questions_Right = ["care","no","no"]
def getQuestion(All_questions, questions_Right):
question_number = random.randint(0, len(All_questions) - 1)
right_answer = questions_Right[question_number]
question = All_questions[question_number]
return question, right_answer # added this to return the data
def ask():
Question, right_answer = getQuestion(All_questions, questions_Right)
answer = input(f"The question is :\n{Question} :").casefold()
if answer == right_answer:
print(f"Yes, {right_answer} was right\n")
All_questions.remove(Question)
questions_Right.remove(right_answer)
else:
print(f"Sorry, but the answer was {right_answer}\n")
while True:
if len(All_questions) == 0:
print("Game over")
break
else:
ask()
1 - you can return the needed data by doing:
return question, right_answer
2 - since the questions list will change every round it is better to pass it to the getQuestion method instead of using the global one directly and use len(All_questions) to get the new length every round:
def getQuestion(All_questions, questions_Right)
3 - some advice :
use snake casing
get_question
# instead of :
getQuestion
don't use global variables inside functions:
A = 1
def add(a, b):
return a + b
add(A, 5)
# instead of
A = 1
def add_to_A(b):
return A + b
add_to_A(5):
format your code properly and make sure that you name variables correctly.
Just simply use return:
def getQuestion():
# ... your code
return (Question, rightAnswer)
#... your code
Question, rightAnswer = getQuestion()
And maybe try to use a dictionary, instead of an question and an answer-array. That would fit better.
I recommend you to do further reading and make some tutorials, before you go on with your quiz-game:
About functions:
https://www.programiz.com/python-programming/function
About dictionaries:
https://www.programiz.com/python-programming/dictionary
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a function that allows a user the ability to add data via input. I would like to add a confirmation step that will allow them to answer yes or no to continue. If they select no it should allow them to restart the function of adding data to the list. I also want to make sure they answer with Y, YES, y, yes, N, NO, n, no. What would be the best way to accomplish this? I've tried several solution I've found online but I end up not being able to get out of the loop of asking yes or no. Thanks in advance.
def item_list(): # Create a list
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
items = item_list()
print(items)
answer = input("Continue?")
if answer.lower() in ["y","yes"]:
# Do stuff
else if answer.lower() in ["n","no"]:
# Do other stuff
else:
# Handle "wrong" input
My answer would be extension of #B. Plüster but it allows slightly bigger range of the inputs and prevent rejections of case-sensitive typos:
answer = input("Continue?")
if answer.upper() in ["Y", "YES"]:
# Do action you need
else if answer.upper() in ["N", "NO"]:
# Do action you need
You could create a wrapper function which calls your other function. In the wrapper function, use another loop to confirm items.
# wrapper function
def item_list_wrapper():
while True:
# call your function at the start of each iteration
final_items = item_list()
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() in ('n', 'no'): # using this elif for readability
continue
else:
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
return final_items
# your original function
def item_list():
items = []
item_int = 0
while 1:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
if item == "":
break
items.append(item)
return items
Then call it as you'd normally call it.
items = item_list_wrapper()
print(items)
In the item_list_wrapper function, note that the line with items = item_list() will renew the list every time. If you want the user to continue adding existing items, you could switch the order of commands around.
def item_list_wrapper():
final_items = item_list() # call the function at the start
while True:
# confirm with the user
print('\nThese are your items:', ', '.join(final_items))
user_input = input('Confirm? [Y/N] ')
# input validation
if user_input.lower() in ('y', 'yes'):
break
elif user_input.lower() not in ('n', 'no'):
# ... error handling ...
print(f'Error: Input {user_input} unrecognised.')
break
# call your function at the start of each iteration
new_items = item_list()
# add new items to previous items
final_items += new_items
return final_items
Don't know whether this is efficient enough.
items = list()
tr = [" Y", "YES", "y", "yes"]
fs = ["N", "NO", "n", "no"]
item_int = 0
def item_list(): # Create a list
global item_int
global items
response = input("\nDo you want to enter data: ")
if response == "":
return
if response in tr:
item_int += 1
item = input("\nEnter item %d or Press Enter: " % item_int)
items.append(item)
elif response in fs:
item_int=0
print("List cleared!")
items.clear()
item_list()
item_list()
print(items)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
for attempt in range(5):
password = input("Password: ")
if password == "changeme":
print("Thou Shall Pass Into Mordor")
break
else:
print("Thou Shall Not Pass Into Mordor")
I need help so it displays the tries into password like this:
Password(1 attempts):
Your attempt variable holds the number of tries. Concatenate that with a print statement in your for loop.
Edit: Deleted Add 1, it is not necessary.
password_attempt = 0
for attempt in range(5):
password = input("Password: ")
if password == "changeme":
print("Thou Shall Pass Into Mordor")
break
else:
password_attempt += 1
print("Thou Shall Not Pass Into Mordor")
print(Password(%s attempt(s)) %password_attempt
I just made a little change to the code you posted to match yours needs.
for attempt in range(1, 5): # Change range to be 1 - 5.
password = input("Password (%d attempts): " % attempt) # Change input message showing attempt number.
if password == "changeme":
print("Thou Shall Pass Into Mordor")
break
else:
print("Thou Shall Not Pass Into Mordor")
I'm learning Python via book and internet. I'm trying to keep score of a game in a separate class. In order to test my idea, i've constructed a simple example. It looks too complicated for some reason. Is there a simpler/better/more Pythonic way to do this?
My code is as follows:
import os
class FOO():
def __init__(self):
pass
def account(self, begin, change):
end = float(begin) + float(change)
return (change, end)
class GAME():
def __init_(self):
pass
def play(self, end, game_start):
os.system("clear")
self.foo = FOO()
print "What is the delta?"
change = raw_input('> ')
if game_start == 0:
print "What is the start?"
begin = raw_input('> ')
else:
begin = end
change, end = self.foo.account(begin, change)
print "change = %r" % change
print "end = %r" % end
print "Hit enter to continue."
raw_input('> ')
self.play_again(end, game_start)
def play_again(self, end, game_start):
print "Would you like to play again?"
a = raw_input('> ')
if a == 'yes':
game_start = 1
self.play(end, game_start)
else:
print "no"
exit(0)
game = GAME()
game.play(0, 0)
Here's how I would format your code:
import os
class Game(object):
def play(self, end, game_start=None):
os.system("clear")
change = input('What is the delta? ')
# Shorthand for begin = game_start if game_start else end
begin = game_start or end
end = float(begin + change)
print "change = {}".format(change)
print "end = {}".format(end)
self.play_again(end, game_start)
def play_again(self, end, game_start):
raw_input('Hit enter to continue.')
if raw_input('Would you like to play again? ').lower() in ['yes', 'y']:
self.play(end, game_start)
else:
exit(0)
if __name__ == '__main__':
game = Game()
game.play(0, 0)
And a few tips:
I wouldn't create a new class that contains only code to perform one specific task. If the class doesn't take arguments or doesn't simplify your code, don't create it. Your Game class is an exception, however, as you would probably add more code to it.
In Python, classes are written in CamelCase. Global constants are usually written in UPPERCASE.
raw_input() returns a string. input() returns the string evaluated into a Python object.
I asked the question a better way and got what I was looking for here:
python: how do I call a function without changing an argument?