Append items to list in another file - Python - python

I'm trying to append inputs to a list in another python file. I think I have the order correct but the error message I get is AttributeError: module 'inventory' has no attribute 'pick' when I try it out.
main.py:
import inventory
choice = input("--> ")
if "inv pick" in choice:
inventory.pick()
inventory.py:
import main
backpack = []
def pick():
"""
Function for picking up things
"""
backpack.append(main.choice)
print(backpack)
If I make write the string "inv pick flower" end hit enter I get the error message instead of the printed content of the list 'Backpack'. Maybe I should use .extend instead of .append but neither of it works right now.
Any pointers perhaps?
Regards

The following is a much better way to implement what you're trying to achieve without any problematic circular imports.
main.py:
import inventory
choice = input("--> ")
inventory.pick(choice)
inventory.py:
backpack = []
def pick(choice):
backpack.append(choice)
print(backpack)

Related

Python - Going over a list of words in python with for loop

Getting back into programming, I've been messing with this for a while now sure it's something super simple or maybe I have things set-up completely wrong.
It's an issue with it not iterating over the rest of the list.
So whenever you run the code you enter a file extension i.e. "File.jpg" and it comes back with image, but if you enter any of the other image types it returns application.
def main():
file = input("File name:")
extension(file)
def extension(s):
split = (s.split("."))
join_s = (''.join(split[1]))
image_e = ['jpg', 'gif', 'jpeg', '.png']
for i in image_e:
print(image_e)
if i == join_s:
return print("Image/")
else:
return print("Application")
main()
I haven't got to the part of implementing the application formats just yet, but I am sure once I figure this bit out it shouldn't be any sort of issue.
Change your if statement to "if join_s in image_e:" should work. Also,"png" inside image_e should not have a "." infront of it

why do i get a circular import error on whichever module that comes first but not on the second?

I am making a simple inventory program for college assignment. however i keep getting a circular import error on one of the module. i get the error on the module import that comes first and not on the second. but the strange thing is, if i were to switch the import order, the previous erroneous import works and the previously working import returns an error.
Elaboration:
when running as this, import A has circular import error and import B works fine.
import A
import B
But if i run the program as this, import B has circular import error and import A works fine
import B
import A
why is this happening? what is the problem here?
This is the main module.
import purchase
import addition
def choices():
print("Press any of following number for a course of action")
print("1. To Purchase Bikes")
print("2. To Add Bikes in the Stock")
print("3. Exit the program\n")
value = 0
while not value in range(1, 5):
try:
value = int(input("Enter your desired number: "))
except:
print("\n\nPlease enter a valid number between 1-5:\n")
if value > 3 or value < 1:
print("\nInvalid Input!! Please select from the given.\n")
choices()
elif(value == 1):
purchase.purBikes()
elif(value == 2):
addition.addStock()
elif(value == 3):
quit()
choices()
The whole program is available here. i know its a lot to look through but i didn't know what parts to remove to make a minimalized reproduceable example.
https://filebin.net/zgr985zo5wao5c0e
You have to rethink the design.
addition.py:
import Main
def addStock():
# The 2 last lines
Main.choices()
return shipCost
A module is a library of reusable components, so they can not depend on some "Main", they must work anyhere, specially on unit tests.
Also, you call addition.addStock() in Main.choices(), so there is a circular call. When does it return shipCost?
First off, your welcome function is not defined(I dont see it if it is)
Second, module purchase doesnt exist publicly so it may be the problem

can i define k elem in random.sample function as an variable?

I am begginer in Python. And what I am trying to do is make a random text from the list generator, in which you can choose how many things from the list you want to print out. When im trying to make k=var in which var=Entry(...). It gives me this error: TypeError: '<=' not supported between instances of 'int' and 'NoneType'. If you can give me tips to improve my skills and knowledge Id be really happy.
k determines how many items from the list I wanna print out:
def nahodny_generator():
list = ["more", "more1", "more3"]
sampling = random.sample(list, k=2)
oklbl = Label(root, text=sampling)
oklbl.grid(row=6, column=0)
I got your code into a state where I was able to run it and I didn't see any errors:
import random
from tkinter import Label, Widget
from typing import Optional
root: Optional[Widget] = None
def nahodny_generator() -> None:
words = ["more", "more1", "more3"]
sampling = random.sample(words, k=2)
oklbl = Label(root, text=sampling)
oklbl.grid(row=6, column=0)
nahodny_generator() # no exceptions raised?
One probable bug I noticed is that sampling is a List[str] (note that list is the name of Python's list class, and you probably don't want to name your own variables that) and you're passing it as a parameter called text, which I would assume expects a str (tkinter doesn't have type declarations though so it's not obvious that's the case).
Nothing in the code you shared uses the <= operator so the specific error you saw is coming from some other piece of it. When you get an error, the message will include the exact file and line number that it came from; you can use that to narrow down the source of the bug.
The function nahodny_generator is referenced in Button command, and I want to push that button with the entry inside and print out the amount of things in a list determined by the entry. Also I am using tkinter GUI and if you could give me some tips where to continue after overcoming the beginner level I would be very happy.

returning a specific type in Python

The quick version:
I'm trying to figure out how to pass either a list or tuple from a function in one script, to a function in another script. The issue I run into, is that it always becomes a NoneObjectType in the second script, and then I can't do anything with it other than print it out as a long string.
The long version:
I use a 3d program called Poser, that allows the use of Python to auto mate tasks. Because of this I made a nice little script called SelectMultiple that gives me a nice wxPython window were I can choose the items I want to modify. Because I can see using this over and over, I wanted it to be it's own script.
Here is the function I'm calling from SelectMultiple:
def MyApp():
title = "Select from list"
# Make the selection window pop up
mydialog = userInput(title, lst)
popupwindow = mydialog.ShowModal()
# If the user cancels win = 0
if popupwindow == wx.ID_CANCEL:
print "User canceled"
return
# Get the selected actors
selected = mydialog.GetSelectedActors()
# We are finished with the dialog
mydialog.Destroy()
return lst(selected)
by default selected is a tuple, as you can see I tried casting it as a list before returning it, but it doesn't show up that way in my other script. The file does import, and I can print it and get a string that shows the content, but it's always NoneType and I can't do much with it. Here's the script I'm calling from:
import poser
import os
scene = poser.Scene()
pathname = os.path.split(poser.AppLocation())[0]
pathname = os.path.join(pathname, 'Runtime', 'Python', 'poserScripts', 'ScriptsMenu', 'GadgetGirl')
sys.path.append(pathname)
try:
import SelectMultiple
except:
print "Could not import SelectMultiple script"
def ChoiceWindow():
title = "SuperFly Node Fixer"
message = "Choose the operation to preform"
list_of_operations = ["Delete Node", "Detach Node", "Re-Link Node"]
drop_down_window = poser.DialogSimple.AskMenu(title, message, list_of_operations)
return drop_down_window
def Controller():
script_to_run = ChoiceWindow()
#Need to call multiple so that we can know on what figures
list_of_figures = SelectMultiple.MyApp()
print type(list_of_figures)
Controller()
So yeah, how do I get something other than a NoneType back.
So I created my own issue with a typo. After I discovered that selected wasn't a list but a tuple, I mistyped the list cast as lst and then couldn't figure out why it wasn't a list. Thanks for the help
Loop thru the selected tuple and add the items into a list.
l = list()
for item in selected:
l.append(item)
return l
Also I'm not sure what version of Python you're using but the cast for list is list() not lst()

How to append function to a list then print it

I am creating a basic recipe viewer in python, I stumbled across a problem of which when I try to print my saved recipe it displays [None], as seen the recipe is firstly a function, then it is appended onto a list then I try to print it when loading it.
The code below can explain more. How do I stop the [None, None] from appearing? The code below is a sample I made which I could easily adapt to resolving my issue in my recipe rather than posting my entire code on here.
b = [] #this is meant to resemble my list
def function(): # this is meant to resemble my recipe
print("hi")
function()
a = input('write 1 = ') # this is meant to resemble the user to saving the recipe
if a == '1':
b.append(function()) # this is meant to resemble me saving the recipe onto a list
print(b) # this is meant to resemble me loading the recipe
When I run my code , sorry don't have enough reputation points to post an image but this is what comes up in the python shell
hi
write '1' = 1 #user input
hi
[None]
You are not returning anything from your function. You are printing, but that's not the same thing.
Use return to return the value:
def function():
return "hi"
print() writes to your terminal, the caller of the function is not given that output.
You can always use print() to print the return value:
print(function())

Categories

Resources