how this example comes UnboundLocalError? - python

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!

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

Repeating a function with another function

for an assignment we needed to make a function that flipped a coin and another to flip it 100 times. I was able to make a function that flipped a coin, but got stuck when trying to call it a 100 times with another function. This is what I have right now:
import random
def TC():
face = random.randint(0,1)
if face == 1:
return "head"
else:
return "tail"
print TC()
def ply(flips):
for i in range(flips):
return TC()
print ply(100)
When I run it it just says 'none.' Please tell me where I am going wrong. Thank You!
Just to start, your method naming is very bad. I doubt this is how your professor is teaching you to name methods and variables. It's ugly, against Python standards and hard to read I suggest you take some time and read PEP 8 it's how python was intended to be written.
So instead of TC you should use something like flip_coin and instead of ply use something like play_coin_flip or even simply play.
Next I don't know if I'm stepping outside of what you have learned but instead of using randon.randint you can use randon.choice.
And finally, as others have said, when you return you quit any other execution in a function and return whatever variable you retrun in that statement thus nullifying any other iterations of the loop you're performing. I suggest something like the below as a better program with corrections applied to make it function as intended.
from random import choice
faces = ['head', 'tail']
def flip_coin():
face = choice(faces)
return face
def play_coin_flip(flips = 1):
for i in range(flips):
print(flip_coin)
if __name__ == "__main__":
play_coin_flip(100)

Shuffle not working (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

Generate random floating point number

Right now I'm working on making Python "type" on your screen (I was feeling bored and experimental), and I got this far on my own, but I can't find any way to use decimals in my script, as Python only accepts whole numbers for randint().
#include <stdio.h>;
import sys;
import time;
import os;
import random;
os.system("clear");
script = "I just really need to type something right now. I'm not sure why, but I really feel like typing on the Chromebook right now. It seems kinda weird, but I like doing this. It helps me practice what I'm doing. I've noticed that I'm a lot worse at typing lately, and I don't know why. Maybe it's because I've been working with a chunky keyboard, and these Chromebook keyboards are extremely thin. Yup, this is actually entertaining for me. I'm not exactly sure why I want to do this, but I just do. It's almost addicting to me, and I don't know why.\n";
for i in range(0, 587):
sys.stdout.write(str(scripti));
sys.stdout.flush();
time_num = random.randint(0.1, 0.4);
time.sleep(time_num);
The output I get is:
ITraceback (most recent call last):
File "main.py", line 11, in <module>
time_num = random.randint(0.1, 0.4);
File "/usr/lib64/python2.7/random.py", line 242, in randint
return self.randrange(a, b+1)
File "/usr/lib64/python2.7/random.py", line 187, in randrange
raise ValueError, "non-integer arg 1 for randrange()"
ValueError: non-integer arg 1 for randrange()
Any ideas?
EDIT: Don't tell me how to make this simpler, as this was just for learning.
Why don't you use the random uniform distribution instead? In this case you can get non integer number values. Use:
import random
random.uniform(0.1,0.4)
If you have to use randint, you could do time_num = randint(1, 4)/10.
for i in range(0, 587):
... nothing is indented there (unless you didn't post the indents in the question).. so it's practically useless
For the time_num Variable you could cast it like this:
time_num = double(random.randrange(1, 4) \ 10
you must be trying to get it in milliseconds because python uses Seconds for the time import
but you could also rephrase it like instead of using randint use random.randrange(#1, #2)
And I don't know the sys import but you used this -> sys.stdout.write(str(scripti));
BUT your variable is named "script".........

How to use IPython.parallel for functions with multiple inputs?

This is my first attempt at using IPython.parallel so please bear with me.
I read this question
Parfor for Python
and am having trouble implementing a simple example as follows:
import gmpy2 as gm
import numpy as np
from IPython.parallel import Client
rc = Client()
lview = rc.load_balanced_view()
lview.block = True
a = 1
def L2(ii,jj):
out = []
out.append(gm.fac(ii+jj+a))
return out
Nloop = 100
ii = range(Nloop)
jj = range(Nloop)
R2 = lview.map(L2, zip(ii, jj))
The problems I have are:
a is defined outside the loop and I think I need to do something like "push" but am a bit confused by that. Do I need to "pull" after?
there are two arguments that are required for the function and I don't know how to pass them correctly. I tried things like zip(ii,jj) but got some errors.
Also,, I assume the fact that I'm using a random library gmpy2 shouldn't affect things. Is this correct? Do I need to do anything special for this?
Ideally I would like your help so on this simple example the code runs error free.
If you think it would be beneficial to post my failed attempts at #2 let me know. I'm in the dark with #1.
I found two ways that make this work:
One is pushing the variable to the cores. There is no need to pull it. The variable will simply be defined in the namespace of each process-engine.
rc.client[:].push({'a':a})
R2 = lview.map(L2, ii, jj)
The other way is as to redefine L2 to take a as an input and pass an array of a's to the map function:
def L2(ii,jj,a):
out = []
out.append(gm.fac(ii+jj+a))
return out
R2 = lview.map(L2, ii, jj, [a]*Nloop)
With regards to the import as per this website:
http://ipython.org/ipython-doc/dev/parallel/parallel_multiengine.html#non-blocking-execution
You simply import the required libraries in the function:
Note the import inside the function. This is a common model, to ensure
that the appropriate modules are imported where the task is run. You
can also manually import modules into the engine(s) namespace(s) via
view.execute('import numpy')().
Or you can do as per this link
http://ipython.org/ipython-doc/dev/parallel/parallel_multiengine.html#remote-imports

Categories

Resources