How to implement a class (function) upon pressing a key? - python

I have a function in my code:
X = []
Y = [1,2,3,4]
class DATA():
def __init__(self):
X.append(Y)
DATA()
print (X)
When I run my code, I want this class (named DATA) to be implemented only when I press the Enter key. Any idea how I can do it? (A simple example is appreciated!).

This was hard to answer for a couple reasons:
You keep using the word "implement", but I'm pretty sure you mean "call" instead. I'm going to assume that here, since conditionally implementing something is rarely needed.
Your use of the class here is confusing. It isn't actually needed in this case, so it's just complicating things. I'm going to reduce it down to just:
def DATA():
X.append(Y)
Since that does the same thing as your existing code.
To ask for user input, use input. input waits until the user presses Enter, then returns the typed text. You can use it here to wait for Enter to be pressed:
x = []
y = [1,2,3,4]
def data():
x.append(y)
print("x before Enter is pressed:")
print(x)
input("Type Enter to continue...")
data() #Call DATA similar to your original code
print("x after Enter is pressed:")
print(x)
A couple extra notes:
Function and variables names should be in lower case. Uppercase is reserved for class names, and even in those cases, only the first letter is uppercase.
Ideally, you shouldn't be mutating global variables like x and y. They should be passed into the function, then the result should be returned.

Related

How to write multiple conditions in one line

Is there a way that we can add multiple conditions in a single line? this is not working atm, but if it were separated into different sequences, it would work.
Just to mention, I used and/or and still not working
user_input = remove_punct(user_input), remove_spaces(user_input), user_input.lower
return user_input
Just nest all the operations! Your approach doesn't work as a tuple is being created on the right hand side and the value of user_input doesn't get updated.
Try this
user_input = remove_punct(remove_spaces(user_input.lower()))
Edit:
As pointed out by #S3DEV, the above solution assumes that the functions remove_punct, remove_spaces return the updated value of the input after performing the operation
You could create a list of your functions you want to use, and then iterate over them storing the result back into the input string. Alternativly if your functions are just using string methods then you can just keep chaining them. Lastly if you want to chain them like in string but need your own methods you could write your own class.
def remove_space(some_string: str):
return some_string.strip()
def remove_punct(some_string: str):
return some_string.replace("!", "")
def clean(some_string):
functions = remove_space, remove_punct, str.lower
for fun in functions:
some_string = fun(some_string)
return some_string
def clean2(some_string: str):
return some_string.strip().replace("!", "").lower()
print(clean(" hello world! "))
print(clean2(" hello world! "))

Dictionary - printing result multiple times?

I'm coding this program but running it and typing "2" when I type a subject it doesn't print the result once but nine times. Where is the problem? 9 is the number of subjects in the list named mat so it's strictly connected. Now to check some files .txt as placeholder but I'd like also using the module json.
import os
def spat():
a=len(list(os.listdir('C:/Users/SUINO/Desktop/python/prob/cache/'+y)))
print(a)
b=100/(25-a)
print(b)
mat=["latino","greco","storia","latino","scienze","matematica","grammatica",
"promessi sposi,","eneide"] #mat means subject
c=input("Do you want to add a placeholder or calculate probabilties? 1|2: ")
if c == "1":
c=input("Insert a subject: ")
c=c.lower
if c in mat:
name=input("Insert the name of the student: ")
open('C:/Users/SUINO/Desktop/python/prob/cache/'+c+'/'+name+".txt")
else:
print("Materia non esistente!")
if c == "2":
y=input("Materia: ")
y=y.lower()
x={"latino":spat(),"greco":spat(),"eneide":spat(),"promessi sposi":spat(),
"mate":spat(),"grammatica":spat(),"storia":spat(),"scienze":spat(),
"inglese":spat(),}
The objective of the program is to calculate the probabilities of being interrogated using the files .txt that have as name the name of the student interrogated yet.
If I understand your question correctly, you're basically trying to create a CLI for accessing homework or other school work that students can interact with and access their files.
I just noticed you are also trying to access var y within function spat(). You need to pass this value into the function call. If you want to map each key to the function.
If you want the key to be a reference, you need to structure your dict like this:
x = {
'latino': spat,
'greco': spat,
...
}
Then when the user enters in a value, you simply declare a new variable to be the value of the key, which in turn, creates a variable which is a reference to that function.
So if you receive input y with
y = input("Materia: ")
Then you should create a new variable like such
func = x[y]
This will find the key value entered in from the above input function and assign that reference to the variable func. Essentially, func now is equal to the function and you can execute func like any other normal function as well as pass in variables.
func(y)
This will execute the function referenced (spat) and pass in variable y. You also need to rewrite spat() as such:
def spat(y):
a = len(list(os.listdir('C:/Users/SUINO/Desktop/python/prob/cache/'+y)))
print(a)
b = 100/(25-a)
print(b)
Essentially the same except you're now passing in y from the input below.
You also need to move the declaration of the dictionary to the top so that your reference to this dictionary will be recognized when you declare func.
So whole code:
import os
def spat(y):
a = len(list(os.listdir('C:/Users/SUINO/Desktop/python/prob/cache/'+y)))
print(a)
b=100/(25-a)
print(b)
x = {"latino":spat,"greco":spat,"eneide":spat,"promessi sposi":spat,
"mate":spat,"grammatica":spat,"storia":spat,"scienze":spat,
"inglese":spat,} # x moved up from bottom
mat = ["latino","greco","storia","latino","scienze","matematica","grammatica",
"promessi sposi,","eneide"] #mat means subject
c = input("Do you want to add a placeholder or calculate probabilties? 1|2: ")
if c == "1":
c = input("Insert a subject: ")
c = c.lower
if c in mat:
name = input("Insert the name of the student: ")
open('C:/Users/SUINO/Desktop/python/prob/cache/'+c+'/'+name+".txt")
else:
print("Materia non esistente!")
if c == "2":
y=input("Materia: ")
y=y.lower()
func = x[y] # creates reference to the key which is a ref to a function
func(y)
However, since every key value is executing the same function, you might be better served not writing new dictionary entries for each new key and just simply making a list of recognized subjects that the student may enter:
subjects = ['latino', 'greco', 'grammatica', ...]
Then you can simply check whether the input exists within this list and, if it does, run spat() and pass in y.
if y in subjects:
spat(y)
else:
print("Unrecognized command...")
Mapping functions within a dictionary is useful for creating an 'interface' that can route the various inputs to a function that will be executed for that given option. You can check whether or not their command works by simply checking for their input within a list/dict and if it doesn't exist, then you can skip running the function and output an error message--if the command exists, then you can reference it to a key value (which in turn, references it to the value of that key) and then it will run the proper function.
The short answer is it's printing nine times because of all the calls to spat() you put in the statement:
x={"latino":spat(),"greco":spat(),"eneide":spat(),"promessi sposi":spat(),
"mate":spat(),"grammatica":spat(),"storia":spat(),"scienze":spat(),
"inglese":spat(),}
There are a number of other issues with your code, but since I don't completely understand everything it's trying to accomplish, I'm not going to attempt to tell you what to do other than not to call it some many times like that.

Input as a default value for a function

Is it possible to have input as a default value for a function?
For example,
f(x=input('>')):
print(x)
The problem is, it makes me input a value even when I supply an x value. How would I do this correctly?
Python will evaluate the default arguments you define for a function, you'll get the prompt during definition either you like it or not. The value entered at the input prompt will then be assigned as the default for x.
If you want a default value that will use input if no other meaningful value is provided, use the common idiom involving None and drop input in the body of the function, instead:
def f(x=None):
if x is None:
x = input('> ')
print(x)
Now, if you're thinking, I still want to somehow do this with default arguments, then you'll need to create a function that re-creates your function with every invocation:
def f():
def _(x = input('> ')):
print(x)
return _()
I don't see what benefit this would bring other than appeasing your curiosity, though :-)
May be this is what you want.
def f(x=None):
if not x:
x = input('>')
print(x)

Do Python functions modify their arguments?

I was in my computer science class today and the teacher put a piece of python coding on the board and said he couldn't figure out why it wasn't working. He was showing us functions and said:
def app(x):
x.append(" ")
print(x)
def ext(x,y):
x.extend(y)
print(y)
nums = [1,2,3,4,5,6]
numbers = [7,8,9,10]
app(nums)
ext(nums,numbers)
print("End of program")
The code was meant to show how when you don't type
return x
in the function then the variable doesn't change when you return to the main program however when he ran the program, the first function added the space and kept it there when it returned resulting in the following text being printed...
['1','2','3','4','5','6',' ']
['1','2','3','4','5','6',' ','7','8','9','10']
End of program
Please help me out.
You say that the point was to demonstrate that a list won't be changed unless it is returned. That is false. The list is a mutable object. When you pass it (by name) to a function and change it, it will be changed. If you don't want the change, you need to work with a copy.
def app(x):
return x + [" "]
def ext(x,y):
return x + y
might be what you are trying to do ... im not sure, this will not alter either of the original lists, but will return a new list as the result

Add multiple numbers taken from user input and append it to a list

I just have this little program here that I want to use to take an input from a user (as if entering a password). I have a list with the password in it, I then take the users input and place it in an empty class. Then compare that class to the one with the password in it, if it matches it will return "good". However I've only been able to do this using one digit. How would allow for the user to use multiple integers? And is this an efficient way of doing this sort of thing? Is there are quicker more efficient method? Thanks.
class KeyCode(object):
def access(self):
room_code = [1]
print "Before you enter you must provide the room code: "
attempt = []
code = int(raw_input('>>'))
attempt.append(code)
if attempt == room_code:
print "Good"
else:
return 'death'
class Boxing_room(KeyCode):
def enter(self):
print "This is the boxing studio"
return 'Gymnast_room'
Lists aren't necessarily needed. You can just compare strings, or if your code is only numbers, integers.
Also, a class isn't really helpful here (unless it's here just to learn a bit about them). A function will suffice:
def access():
room_code = 12534
code = int(raw_input('Enter the code: '))
if code == room_code:
return 'good'
return 'death'
You can use a dictionary to store the keycodes:
code_dict = {'Boxing':'12345', 'Locker':'00000'}
and test
if code_input == code_dict['Boxing']:
...
I agree with Haidro's answer, but it seems to me you may want to allow more than one password?
If that is the case you would just need to do an 'IN' check.
For example.
def access():
room_code = [12345,54321]
code = int(raw_input('Enter the code: '))
if code in room_code:
return 'good'
return 'death'

Categories

Resources