Call to a variable that is inside another function - python

def HOME():
""" The first screen
"""
print ('Welcome to my program!')
input_grocery_list = input('Hello, please enter here a list of groceries: ')
def input_to_list():
""" This f takes the input
and put it inside a list
without the: ','
and print the list
"""
new_grocery_list = []
separator = ", "
while ',' in input_grocery_list:
d = input_grocery_list.index(',')
y = input_grocery_list[:d]
new_grocery_list.append(y)
input_grocery_list = input_grocery_list[(d+1):]
if ',' not in input_grocery_list:
new_grocery_list.append(input_grocery_list)
print(separator.join(new_grocery_list))
def the_groceries_list():
""" Do somthing to the first input
accord to the next choice
"""
print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
grocery_list = input('please enter here your choice : ')
if grocery_list == '1':
input_to_list(input_grocery_list)
if len(input_grocery_list) != 0:
the_groceries_list()
HOME()
The error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 37, in HOME
File "<stdin>", line 34, in the_groceries_list
TypeError: input_to_list() takes 0 positional arguments but 1 was given
My problem is probably in the second function called "input_to_list ()"
  While I am trying to read / change the "input_grocery_list" variable that is inside the first function (HOME)
It does not recognize him.
I tried to fix it using global or self but I probably don't really know where exactly to put them because in the meantime it didn't work for me.
Anyone know how I can fix this?

As I can see, you try to have a main function, but you should use a class instead of a function, so more like this.
class Home():
def __init__(self):
"""
define your class wide variables here as following
"""
# example
# self.your_name = 'hello'
# to access it in an function IN this class, type: self.your_name
pass
def get_items(self):
print('Welcome to my program!')
input_grocery_list = input('Hello, please enter here a list of groceries (sep with comma): ')
self.input_to_list(input_grocery_list)
# you forgot this
# ||
# \/
def input_to_list(self, grocery_list: str):
""" This f takes the input
and put it inside a list
without the: ','
and print the list
"""
new_grocery_list = grocery_list.split(',')
# to print as list
print(new_grocery_list)
# to print every item in list
for item in new_grocery_list:
print(item)
# print('List End') # if you want to
# I don't really know what that is supposed to do, but whatever it is it wont
"""
def the_groceries_list(self):
# Do somthing to the first input
# accord to the next choice
print("You can chose a number betwen 1 - 9 n/ and we do the rest..")
grocery_list = input('please enter here your choice : ')
if grocery_list == '1':
input_to_list(input_grocery_list)
if len(input_grocery_list) != 0:
the_groceries_list()
"""
# to use this class and it's functions first create an object
home = Home()
# than call a function
home.get_items()
I wont go into details of Classes and Object but here is a link for you.
Read this, it should explain the basics pretty good.

You need to change definition of your nested function so it can take args:
def input_to_list(input_grocery_list):

Related

create multipe telephone directory records in python using list and dict

I'm creating Telephone Directory program by using python, first of all i'm new to python here i created class and declare global list and dict, because i want to store when i call testcreate function we enter name and phone that will stored in list and that list will be stored in dict through save function. To show telephone directory data just call getdata function, but its not working any help thank in advance
class testdl():
testlist=[]
testdic={}
def testcreate():
name = input("enter name : ")
phone = input("enter phone : ")
testdl.save(name,phone)
def save(n,p):
testdl.testlist[n]=p
testdl.testdic = testdl.testlist
def getdata():
print(testdl.testdic)
>>> tdll = testdl()
>>> tdll.testcreate()
**Error Message :**
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
tdll.testcreate()
TypeError: testcreate() takes 0 positional arguments but 1 was given
>>> testdl.testcreate()
enter name : srikanth
enter phone : 1234567890
**Error Message :**
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
testdl.testcreate()
File "<pyshell#79>", line 7, in testcreate
testdl.save(name,phone)
File "<pyshell#79>", line 9, in save
testdl.testlist[n]=p
TypeError: list indices must be integers or slices, not str
Apparently,your function can be a staticmethod and there is no need create a class.If you really want to create a class:
class Testdl:
def __init__(self): # initialize the value
self.testlist=[]
self.testdic={}
self.name = None
self.phone = None
def testcreate(self):
self.name = input("enter name : ")
self.phone = input("enter phone : ")
self.save()
def save(self):
self.testdic[self.name] = self.phone # maybe you need a dict to save them not a list
self.testlist.append(self.testdic) # then you append it in the list
def getdata(self):
print(self.testdic)
testdl = Testdl() # create a instance
testdl.testcreate() # call the function
testdl.getdata() # print the data
If you want to record three groups of data,use:
testdl = Testdl()
for i in range(3):
testdl.testcreate()
testdl.getdata()
Error 1:
Every method in a class needs self as first argument, which refers to the current instance
def testcreate(self):
name = input("enter name : ")
phone = input("enter phone : ")
self.save(name,phone)
Error 2:
def save(self, n,p):
self.testlist[n]=p
lists accept only ints as indices
Errors you will get
Error 3:
self.testlist is empty => IndexError: Index not found
Error 4:
a list is not a dictionary
(in save())
testdl.testdic = testdl.testlist
Possible solution
class testdl():
testdic={}
def testcreate(self, ):
name = input("enter name : ")
phone = input("enter phone : ")
self.save(name,phone)
def save(self, n,p):
self.testlist[n]=p
def getdata(self, n):
print(self.testdic[n])

Autocorrect python library throwing error instead of correcting the word

I'm not really sure why this autocorrect isnt working, but every time i try to use the Speller() function i get this error:
TypeError: '>' not supported between instances of 'str' and 'int'
and here is my code:
import time
from autocorrect import Speller
def main(consoleMode):
if consoleMode:
# beg fur input :D
inputVar = input("Console Mode input: ")
if Speller(inputVar.lower()) == "hi" or Speller(inputVar.lower()) == "hello" or Speller(inputVar.lower()) == "wassup" or Speller(inputVar.lower()) == "sup":
if name == None:
name = int(input("Hello!\nI'd like to get to know you.\nWhat's your name?\n> "))
if ("not" in Speller(name) and "tell" in Speller(name)) or ("not" in Speller(name) and "say" in Speller(name)):
print("Alright, I'll just call you Bob for now :)")
name = "Bob"
else:
print("Hey " + name + "!")
while True:
main(True)
edit: I also tried doing int(disisastringvariable) but it just doesnt even work as it also throws an error
you might want to check out the documentation for the autocorrect module the speller class inits signature is def __init__(self, threshold=0, lang='en'): So when creating an instance of the class and passing in a single argument it will assume you are passing in a threshold.
So calling Speller("something") will pass a string in that will be stored as the threshold. then on line 27 of the init method. if threshold > 0 this string will be compared to an int. Hence the error. Since you cannot do > between a string and an int.
I would suggest first read any documentation for this module. The example from the documenation suggest to use it like
>>> spell = Speller(lang='en')
>>> spell("I'm not sleapy and tehre is no place I'm giong to.")
"I'm not sleepy and there is no place I'm going to."
You are trying to pass the code you want to check to the Speller constructor.
Instead, you should create the object once, and then it is callable and checks input. Read the examples here: https://github.com/fsondej/autocorrect
import time
from autocorrect import Speller
my_speller = Speller(lang='en')
name = None
def main(consoleMode):
global name
if consoleMode:
# beg fur input :D
inputVar = input("Console Mode input: ")
if my_speller(inputVar.lower()) == "hi" or my_speller(inputVar.lower()) == "hello" or my_speller(inputVar.lower()) == "wassup" or my_speller(inputVar.lower()) == "sup":
if name == None:
name = input("Hello!\nI'd like to get to know you.\nWhat's your name?\n> ")
if ("not" in my_speller(name) and "tell" in my_speller(name)) or ("not" in my_speller(name) and "say" in my_speller(name)):
print("Alright, I'll just call you Bob for now :)")
name = "Bob"
else:
print("Hey " + name + "!")
while True:
main(True)
You also had a problem with the variable name being used before declaration - I think you want to have a global instance of this and use it in all calls to your main function.

How do I use raw_input with classes in a definition

Problem
I'm writing a script in Python 2.7 that has the user input the atomic symbol for an element. The script then prints out information about the element.
However, I'm not sure how to have a class use a variable from the raw_input. Here is the code with a couple of the 118 elements gone for readability:
Code
class PTable(object):
def __init__(self, name, atom_num, atom_sym, atom_mass,period, group, atom_type,state):
self.name = name
self.atom_num = atom_num
self.atom_sym = atom_sym
self.atom_mass = atom_mass
self.period = period
self.group = group
self.atom_type = atom_type
self.state = state
h = PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas")
he = PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas")
li = PTable("Lithium",3,"Li",6.941,2,1,"Alkali metal","Solid")
be = PTable("Beryllium",4,"Be",9.0121831,2,2,"Alkaline earth","solid")
og = PTable("Oganesson",1,"H",1.008,1,1,"Nonmetal","Gas")
def results(name, num, sym, mass, per, gro, typ, state):
print "Name:", name
print "Atomic number:", num
print "Atomic symbol:", sym
print "Atomic mass:", mass
print "Period:", per
print "Group:", gro
print "Type:", typ
print "State:", state
# results(h.name, h.atom_num, h.atom_sym, h.atom_mass, h.period, h.group, h.atom_type, h.state)
def hub():
x = raw_input("What element? ")
results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)
hub()
hub()
Errors
The code that gives me the syntax error is:
results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)
The error is obvious; syntax is wrong, so I tried another way:
results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)
That, too, did not work, and I got the error
Traceback (most recent call last):
File "C:/Users/NAME/Desktop/PTable.py", line 146, in
hub()
File "C:/Users/NAME/Desktop/PTable.py", line 143, in hub
results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)
AttributeError: 'str' object has no attribute 'name'
Question
Do you know how I can make it so the user is able to type in the name of the element (the atomic symbol) and the code prints out the information?
Recovering an element
The line x = raw_input("What element? ") provides you with a string, say 'he', so when you call x.name you are attempting to access an attribute of that string and not of the variable he.
What you should do is store your elements in a dictionary instead of having them as variables and access them with the key provided by your user.
periodic_table = {
'h': PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas"),
'he': PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas"),
...
}
symbol = raw_input("What element? ")
try:
element = periodic_table[symbol]
except KeyError:
print('This element does not exist')
Printing the element
As for printing the element, I would suggest a more object-oriented approach by implementing the PTable.__str__ method.
class PTable(object):
...
def __str__(self):
# Add in the format and information that you want to be printed
return "Name: {}".format(self.name)
You can then directly print your elements.
print periodic_table['he']
# prints: 'Name: Helium'

Python 3.x: User Input to Call and Execute a Function

There are many questions similar to this out there but none of the answers solved my issue.
I have defined several functions that parse large data sets. First I call the data, then I organize the data (represented as rows and columns in a .txt) into lists which I will index for individual data entries. After that I establish my functions that will work through the lists one at a time. The code looks like:
f = open(fn)
for line in iter(f):
entries = [i for i in line.split() if i]
def function_one():
if entries[0] == 150:
# do something
def function_two():
if entries[1] == 120:
# do something else
def function_three():
if len(entries) > 10:
# do something else
etc. etc.
I have attempted to prompt the user asking what function they would like to execute as each function returns different things about the data set. My attempt is as follows:
f_call = input('Enter Function Name: ')
if f_call in locals().keys() and callable(locals()['f_call']):
locals()['f_call']()
else:
print('Function Does Not Exist')
When I run the script, I am prompted to 'Enter Function Name:' and if I type in 'function_one' and return, it prints 'Function Does Not Exist'. I want to see that, if entered correctly, the script will execute only the function that the user entered. If the user input is correct, the function should run and print the parsed data.
I have also attempted using a dict to store the functions but I have not had success.
Any help would be greatly appreciated.
Based on your comments, I think you're trying to achieve something like this:
def function_one(data):
if data[0] == 150:
pass # do something
def function_two(data):
if data[1] == 120:
pass # do something else
def function_three(data):
if len(data) > 10:
pass # do something entirely different
This defines your functions that accept arguments so you can re-use them later on. Then you'd like to ask the user which function to use when processing the data, so:
while True: # loop while we don't get a valid input
user_function = input('Enter a function name to use: ') # ask the user for input
if user_function in locals() and callable(locals()[user_function]): # if it exists...
user_function = locals()[user_function] # store a pointer to the function
break # break out of the while loop since we have our valid input
else:
print('Invalid function name, try again...')
Finally, you can load your file, read it line by line, split it up and process it by the function decided by the user:
with open(file_name, "r") as f:
for line in f:
entries = line.split() # no need to check for empty elements
user_function(entries) # call the user selected function and pass `entries` to it
Of course, you can do further processing afterwards.
UPDATE - Here's a simple test for the above code, given the file test_file.txt containing:
tokenized line 1
tokenized line 2
tokenized line 3
and file_name = "test_file.txt" defined in the file, while the functions are defined as:
def function_one(data):
print("function_one called: {}".format(data))
def function_two(data):
print("function_two called: {}".format(data))
def function_three(data):
print("function_three called: {}".format(data))
If you execute the code this is the output/trace:
Enter a function name to use: bad_name_on_purpose
Invalid function name, try again...
Enter a function name to use: function_two
function_two called: ['tokenized', 'line', '1']
function_two called: ['tokenized', 'line', '2']
function_two called: ['tokenized', 'line', '3']
to make your code work, just keep the variable f_call without '' when you call it
f_call = input('Enter Function Name: ')
if f_call in locals().keys() and callable(locals()[f_call]):
locals()[f_call]()
else:
print('Function Does Not Exist')
It may not be the most efficient way to fix it, but you could use something like this:
f_call = raw_input('Enter Function Name: ')
if f_call == "function_one":
function_one()
if f_call == "function_two":
function_two()
if f_call == "function_three":
function_three()
else:
print('Function Does Not Exist')

name not defined errors

I continue to try nd run this program but keep getting this error:
Traceback (most recent call last):
File "C:\Users\bwhite3500\Documents\School\Spring 2011\CITP 110 - Intro to Computer Programming\pet_list.py", line 57, in <module>
main()
File "C:\Users\bwhite3500\Documents\School\Spring 2011\CITP 110 - Intro to Computer Programming\pet_list.py", line 15, in main
display_list(pets)
NameError: global name 'display_list' is not defined*
Here is my code:
import pet_class
def main():
#get list of pet objects
pets = make_list()
#Display the data in a list.
print 'Here is the data you entered:'
display_list(pets)
#The make_list function gets data from the user for three pets. The function
# returns a list of pet objects containing the data.
def make_list():
#create empty list.
pet_list = []
#Add three pet objects to the list.
print 'Enter data for three pets.'
for count in range (1, 4):
#get the pet data.
print 'Pet number ' + str(count) + ':'
name = raw_input('Enter the pet name:')
animal=raw_input('Enter the pet animal type:')
age=raw_input('Enter the pet age:')
print
#create a new pet object in memory and assign it
#to the pet variable
pet = pet_class.PetName(name,animal,age)
#Add the object to the list.
pet_list.append(pet)
#Return the list
return pet_list
#The display_list function accepts a list containing pet objects
#as an argument and displays the data stored in each object.
def diplay_list(pet_list):
for item in pet_list:
print item.get_name()
print item.get_animal_type()
print item.get_age()
print
#call main function
main()
I am new to this and very confused. Please help
Check your spelling:
def diplay_list(pet_list):
You're calling your function diplay_list, not display_list.

Categories

Resources