Trying to apply a function to a user input - python

I'm trying to use an external function and apply it to a basic user input. Basically the external function (Code 1) makes the text in (Code 2) print out slowly, like a video game dialog. However the first variable called "intro" is not affected by this function, only the "response" variable is. I don't know how to fix that.
Code 1:
import sys,time,os
def typewriter(self):
for char in message:
sys.stdout.write(char)
sys.stdout.flush()
if char !="\n":
time.sleep(0.1)
else:
time.sleep(1)
os.system("cls")
Code 2:
from typewriter import *
intro = input("What is your name?\n")
typewriter(intro)
response = ("Nice to meet you " + intro + ".\n\
My name is Program.")
message = intro and response
typewriter(response)

You almost got it! As it has been mentioned, your typewriter function should be receiving the text it should print. But also, "What is your name?" is now being printed by input, not by your function.
This works:
import sys
import time
def typewriter(message):
for char in message:
sys.stdout.write(char)
sys.stdout.flush()
if char !="\n":
time.sleep(0.1)
else:
time.sleep(1)
intro = "What is your name?\n"
typewriter(intro)
name = input()
response = ("Nice to meet you " + name + ".\n\
My name is Program.")
typewriter(response)

Clearly function typewriter is not taking any argument to process the data. When you have called the typewriter(intro) the first time the message variable is not defined. I think you need to change the typewriter function as follows.
def typewriter(message):
for char in message:
sys.stdout.write(char)
sys.stdout.flush()
if char !="\n":
time.sleep(0.1)
else:
time.sleep(1)

first of all I tried to rename the input in the typewrite function instead of self i wrote message:
import sys,time,os
def typewriter(message):
for char in message:
sys.stdout.write(char)
sys.stdout.flush()
if char !="\n":
time.sleep(0.1)
else:
time.sleep(1)
os.system("cls")
i would also change the second code to this:
from typewriter import *
typewriter("What is your name?\n")
intro = input()
response = ("Nice to meet you " + intro + ".\n\
My name is Program.")
message = intro and response
typewriter(response)
have fun with coding!

Related

Python typewriter function returning none when used within input?

import random,sys,time,os
os.system("cls")
def dialogue(passage): # Function for dialogue to type slowly
for letter in passage:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
name = input(dialogue("Hi, WHat is your name?"))
the input would pop up in the terminal as "Hi, WHat is your name?"NONE.
is there any way I can change this to just return the input without it stating NONE where the output should be?
Just add return '' to the end of the dialogue function:
def dialogue(passage):
for letter in passage:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
return ''
name = input(dialogue("Hi, What is your name? "))

I want to add tkinter to this code and will do that but i don't know where to place the tkinter variables?, they will eventually be in the while true

my code should be looking for search options and appending to a list that compares to the search, all im trying to figure out is how to get tkinter in the loop, because i dont know where to put things such as the if name == "main":
stuff
from tkinter import *
ideas = ["pooop", "pooop", "yaaah"]
describe = ["A software that provides poop images", "Fart noises", "kid on crack"]
window = Tk()
window.title("Exists?")
while True:
function = input("Append or Search: ").lower().strip()
if function == "append":
appending = input("What would you like to append enter keywords/possible names..... ")
ideas.append(appending)
appending2 = input("Describe what you would like to append, please do not enter blank values as that will make "
"your software harder to find ")
describe.append(appending2)
print(ideas.index(str(appending)))
print(describe.index(str(appending2)))
searcher = input("What would you like to search for, enter keywords/possible names")
if searcher in ideas:
print(ideas)
print("description: " + describe[ideas.index(searcher)])
print(searcher in ideas)
numberOfResults = str(ideas.count(searcher))
print("0 results found")
if searcher not in ideas:
print(ideas)
print(searcher in ideas)
of = str(len(ideas))
print("0 results found of " + of)
if function == "search":
searcher = input("What would you like to search for, enter keywords/possible names")
if searcher in ideas:
print(ideas)
print("description: " + describe[ideas.index(searcher)])
print(searcher in ideas)
numberOfResults = str(ideas.count(searcher))
print(numberOfResults + " results found")
if searcher not in ideas:
print(ideas)
print(searcher in ideas)
of = str(len(ideas))
print("0 results found of " + of)
if __name__ == "__main__":
window.mainloop()
Put the code in an infinite loop and exit when a word other than append or search is entered
ideas = ["pooop", "pooop", "yaaah"]
describe = ["A software that provides poop images", "Fart noises", "kid on crack"]
while True: # infinity loop
function = input("Append or Search: ").lower().strip()
if function == "append":
pass # ... you code instead
elif function == "search":
pass # ... you code instead
else: # other input
print("That's all!")
break # exit loop

How to make a variable contain a string from a dictionary via input

Im making an AI/Chat Bot from scratch and I want to make code where the bot uses dictionaries of its known stuff and uses them to talk to the user. However, when I try to make the answer appear on the screen using a variable, an error appears
Ive tried making the code so that when the user writes down something in the greetings dictionary, the bot will say "Hello!". But when i run the code, this error comes up: 'set' object is not callable' on line 7 of the code.
MY_NAME = input("What is my name? \n")
Greeting = {"Hi", "Hello", "Hey"}
while True:
input = input("Talk to " + MY_NAME + "\n")
if input == Greeting():
print ("Hello!")
I want the fixed code to this. Thankyou!
Problems:
Greeting is a set. You use it like calling a function which results in your error.
Change variable input because it conflicts with the original input function. In the next iteration, it will throw error as "str object is not callable".
You need a membership check:
while True:
inp = input("Talk to " + MY_NAME + "\n")
if inp in Greeting:
print ("Hello!")
Try using in, and rename input to inp since input will override the default input keyword:
MY_NAME = input("What is my name? \n")
Greeting = {"Hi", "Hello", "Hey"}
while True:
inp = input("Talk to " + MY_NAME + "\n")
if inp in Greeting:
print ("Hello!")

When I try to call a function, it says there is an error

To sum it up, I have little understanding in what I am doing so I will write a portion of the code so maybe anyone can see what's going on.
import sys
start = input("Continue? y/n ")
if start == "y":
startp()
elif start == "n":
print("Party pooper")
def startp():
text = 'text\n'
text2 = 'text2'
for char in text:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
for char in text2:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
startp()
If this is run, you can enter a letter/word, but the out come is
Traceback (most recent call last):
File "C:/Users/-/Desktop/--.py", line 4, in <module>
startp()
NameError: name 'startp' is not defined
I think what I need to do is call the function after the user has typed y or n - but I have no idea how to, any help would be greatly appreciated.
As python create the functions in run time you can not call it before define the function.
if start == "y":
startp()
^
The error is produced here:
if start == "y":
startp()
because startp is defined below those lines of code.
You should always define the functions first (unless you have a reason to not do so). Also, text and text2 aren't returned by the function, maybe you wanted to include the loops inside it?
import sys
def startp():
text = 'text\n'
text2 = 'text2'
for char in text:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
for char in text2:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.1)
start = input("Continue? y/n ")
if start == "y":
startp()
elif start == "n":
print("Party pooper")
When you're reading a book, should you start with they lived happily ever after or once upon a time? Just as you would read a book, the compiler reads starting at the beginning and thus your function should be declared before it is used.
You should define your function before calling it.
As the output says,startp() is not defined in the line 4 when you're trying to call it. Define your function before calling it and your code will be cleaner and probably will work better ;)

python: using a class to keep track of data used by another class

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?

Categories