Shuffle not working (Python) - python

I am trying to make a simple program which makes a name for the user. This is what I have. But when I run it, it says that ncpnames is not defined, but it is, I defined it at the start. Please help!
import time
import random
from random import shuffle
ncpnames = ["Rulf","Isabel","William","Alice","Eleanor","Dimia","Aleida","Farfelee"]
shuffle(ncpnames)
npcname1 = npcnames[0]
print("Hello my name is", npcname1)

You misspelled your variable:
npcname1 = npcnames[0]
You should have:
npcname1 = ncpnames[0]
Honestly, you should have caught this on your own by simply reading over your code.

import random
NPC = ["Rulf","Isabel","William","Alice","Eleanor","Dimia","Aleida","Farfelee"]
chosenName = random.choice(NPC)
print("Hello my name is", chosenName)
Slighly neater

Related

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

How do i import/use an image in my python code? preferably without an external module

My code is this and im trying to make a coin flipper
(The code might look weird because i recycled the script from a random joke selector i coded)
coinside = ['heads.png',
'tales.png',]
from random import randint
def pick(words):
num_words = len(words)
num_picked = randint(0, num_words - 1)
word_picked = words[num_picked]
return word_picked
print(pick(coinside))
while True:
print(pick(coinside))
input()
If all you want is a command-line coin flipper, you don't need that much code.
import random
coins = ['heads', 'tails']
while True:
print(random.choice(coins))
input()
Since it is impossible to do this without external modules, if you want to work with images in python you need pillow.
you can find more information here:
https://www.geeksforgeeks.org/working-images-python/

Append items to list in another file - 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)

how this example comes UnboundLocalError?

When I try to learn more about python, I found this page:http://python.jobbole.com/88045/ . Ok,I must say it was wrote by Chinese.
Here is a example:
import random
def func(ok):
if ok:
a = random.random()
else:
import random
a = random.randint(1, 10)
return a
func(True)# UnboundLocalError: local variable 'random' referenced before assignment
The words, referenced before assignment, I could not understand, in my thought, I had import the random at the top.
Through I import random the second time in else, but I had import random before use,is yet?
So, anyone can help me about the UnboundLocalError when I import more than once?
I am new to python, and my English is not good enough, so please point out what I had not explain enough or the words that not polite enough.
Thanks!

How to split python script in parts and to import the parts in a loop?

First, sorry for my stupid title :) And here is my problem.. Actually it's not a problem. Everything works, but I want to have better structure...
I have a python script with a loop "looped" each second.
In the loop there are many many IFs. Is it possible to put each IF in a separate file and then to include it in the loop? So this way every time the loop is "looped", all the IFs will be passed, too..
There are too many conditions in my script and all of them are different generally from the otheres so I want to have some kind of folder with modules - mod_wheather.py, mod_sport.py, mod_horoscope.py, etc..
Thanks in advance. I hope I wrote everything understandable..
EDIT:
Here is a structural example of what I have now:
while True:
if condition=='news':
#do something
if condition=='sport':
#so something else
time.sleep(1)
It will be good if I can have something like this:
while True:
import mod_news
import mod_sport
time.sleep(1)
And these IFs from the first example to be separated in files mod_news.py, mod_sport.py...
perhaps you wonder how to work with your own modules in general.
make one file named 'weather.py' and have it contain the appropriate if-statements like:
""" weather.py - conditions to check """
def check_all(*args, **kwargs):
""" check all conditions """
if check_temperature(kwargs['temperature']):
... your code ...
def check_temperature(temp):
-- perhaps some code including temp or whatever ...
return temp > 40
same for sport.py, horoscope.py etc
then your main script would look like:
import time, weather, sport, horoscope
kwargs = {'temperature':30}
condition = 'weather'
while True:
if condition == 'weather':
weather.check_all(**kwargs)
elif condition == 'sport':
sport.check_all()
elif condition == 'horoscope':
horoscope.check_all()
time.sleep(1)
edit: edited according to the edit in your question. Note that I suggest importing all modules only one time, at the beginning of the script, and using its functions. This is better than executing code by importing. But if you insist, you could use reload(weather), which actually performs a reload including code execution. But I cannot stress too much that using functions of external modules is a better way to go!
Put them in functions in separate files and then Import them:
"""thing1.py
A function to demonstrate
"""
def do_things(some_var):
print("Doing things with %s" % (some_var))
``
"""thing2.py
Demonstrates the same thing with a condition
"""
def do_things(some_var):
if len(some_var) < 10:
print("%s is < 10 characters long" % (some_var))
else:
print("too long")
``
"""main_program.py"""
import thing1, thing2
myvar = "cats"
thing1.do_things(myvar)
thing2.do_things(myvar)
I believe you are looking for some kind of PHP-like include() or C prepocessor #include. You would have a file such as the included.py below:
a = 2
print "ok"
and another file which has the following code:
for i in values:
import included
and you want the result to be equivalent to
for i in values:
a = 2
print "ok"
Is it what you are looking for? If so... no, it is not possible. Once Python imports a module, the code of the module is executed and following imports of the same mode only retrieve the already imported instance of the module. The code of a module is not executed everytime it is imported.
I can invent some crazy ways of doing it (let us say, file.read() + eval(), or calling reload() in an imported module.) but it would be a bad idea anyway. I bet we can think of a better solution to your real problem :)
Perhaps all you need is to call functions in your loop; and have those functions in other modules, which you import as needed.
while true:
if condition:
from module_a import f
f()
if condition2
from module_b import g
g()
Though the above is legal Python, and so answers your question, you should in practice write all the imports at the top of your file.
You could import the needed modules if they're needed, for example:
if condition:
import weather
... do something
However I'm not sure if that's what you really want.
I have a python script with a loop "looped" each second. In the loop
there are many many IFs.
Then you must optimize the repeatedly executed tests. Suppose there are 50 IFs blocks in your code and that in a turn of the for-loop, the N th condition is True: that means that the N-1 other conditions must be tested before the N th is tested and triggers the execution of the corresponding code.
It would be preferable to do so:
# to_include.py
def func_weather(*args,**kwargs):
# code
return "I'm the weather"
def func_horoscope(*args,**kwargs):
# code
return "Give me your birth'date"
def func_gastronomy(*args,**kwargs):
# code
return 'Miam crunch'
def func_sports(*args,**kwargs):
# code
return 'golf, swimming and canoeing in the resort station'
didi = {'weather':func_weather, 'horoscope':func_horoscope,
'gastronomy':func_gastronomy, 'sports':func_sports}
and the main module:
# use_to_include.py
import to_include
x = 'sports'
y = to_include.didi[x]()
# instead of
# if x =='weather' : y = func_weather()
# elif x=='horoscope' : y = func_horoscope()
# elif x=='gastronomy': y = func_gastronomy()
# elif x=='sports' : y = func_sports()
print y
result
golf, swimming and canoeing in the resort station

Categories

Resources