I am a beginner. My error is UnboundLocalError: local variable 'n' referenced before assignment. I have looked for answers but I dont understand most of the code.
def numberOfSquares(n):#This is where I get the user input.
n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
while n < 0:
print("Please try another number.")
n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
print("Thanks for your contribution!")
def main():# I call the other function in this one, and draw n number of squares. I have not even put #the different colors on it yet.
numberOfSquares(n)
import turtle
for i in range(n):
turtle.circle(40,steps= 4)
turtle.left(45)
turtle.forward(50)
n-=1
turtle.write("Colors of the Rain")
main()
It seems that you are misusing method variables. You are passing n to numberOfSquares while you really want to get a return value instead.
def number_of_squares():
# Your code here, and finally
return n
Then in your main():
n = number_of_squares()
As to the second error, you have a typo. The method turtle.cicrle receives steps argument not step.
turtle.circle(40, steps=4)
And finally, there is a strong naming convention in python. All methods should be lower-case with underscores like number_of_squares, not camel-case (numberOfSquares).
Related
for my coding course we had to make a lottery odds calculator, which has to include 2 functions and a main function. However, when I am trying to call one funtion to the main one I get the unresolved reference error. I don't know why it is doing it, this is the first exercise where I have 2 functions and a main. It might be that I have 2 bad/useless functions, since the instructions said to choose whatever functions seem logical.
from math import factorial
def fraction(prob):
frac=1/prob
return frac
def winProb(total, drawn):
facTot=factorial(total)
facDraw=factorial(drawn)
facBoth=factorial(total-drawn)
prob = float(facTot/(facBoth*facDraw))
return prob
def main():
total=int(input("Enter the total number of lottery balls: "))
drawn=int(input("Enter the number of the drawn balls: "))
if total < 0:
print("The number of balls must be a positive number.")
elif drawn <0:
print("The number of balls must be a positive number.")
elif drawn > total:
print("At most the total number of balls can be drawn.")
else:
print("The probability of guessing all", drawn, "balls correctly is 1/", fraction(prob))
if __name__ == "__main__":
main()
Unresolved reference comes when I try to call fraction(prob) in the last line
The full error probably tells you that prob is undefined. While you may have defined it within winProb it is out of the scope of main so it doesn't exist there yet. You need to define prob right after total and drawn within main:
prob = winProb(total, drawn)
Alternatively, replace fraction(prob) with fraction(winProb(total, drawn))
I need to make a python function where i can find the surface with the riemann sum. This is what i have , and with the feedback of my teacher i am very close to it, but it does not work as properly as i want. the teacher said also something about try-catch what means that i need to make an extra code to control the answer (if im not wrong) To find the surface the uppper and the lower limits are asked and how many rectangles you want under the line like in the program.
(edit) I have made a new program , could you guys check if this is correct.
import math
def f(x): return math.sqrt(x) #Function in the left!
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
n = int(input("How many division intervals do you want?:"))
dx = (b-a)/n;
xi = 0;
sum = 0;
for i in range(n):
xi = xi+dx;
sum = sum + f(xi)
print("The surface under the line is ", (sum*dx))
#einde programma!
import math
def f(x):
return math.sqrt(x) #Function in the left!
def positiveinput(message):
while True:
try:
c = int(input(message))
if c <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?: ")
b = positiveinput("What is the upperlimit?: ")
c = positiveinput("How many division intervals do you want?: ")
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
c = int(input("How many division intervals do you want?:"))
dx = float((b-a)/c)
xi = a
Sum = dx
for i in range(0,c):
xi = a - dx
Sum = Sum + f(xi)
print("The surface under the line is ", (sum*dx))
There are a few issues with the code above:
1) Most importantly, You don't actually calculate the correct answer because you are assuming that the lower limit is equal to 0. Instead of writing xi=0 you should be writing xi=a!!! (Note that this will use the far end of each rectangle to calculate the height - if you want to use the lower end, and don't want to change any other code you will need to write xi = a - dx so you start on a. (Having said that, I wouldn't do it this way, but this is how to fix this without changing anything else).
2) Validation errors: There are a few things you should check:
That the values of a, b are valid numbers (note they shouldn't really have to be integers, just numbers). You can use float() to convert something to a number, just as you would use int() to convert to an integer.
that n is an integer and is not equal to 0, as that will raise an error, when you try and divide by n,
that n is not negative, as this will result in you getting the wrong value (with the code as it is).
Having said that, I would not write the code as it is. Using a for-loop and then incrementing your value is not a very pythonic thing to do. You might be interested to learn you can actually specify a lower bound and an upper bound using the range function. Experiment with:
for i in range(3,11,0.5):
print(i)
See what happens. I'm not going to give you a full solution, as this is a homework assignment, and it will benefit you most to work it out yourself, but hopefully this points you these things will point you in the right direction.
As #Sadap said, you can try something like this:
def positiveinput(message):
while True:
try:
n = int(input(message))
if n <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?:")
b = positiveinput("What is the upperlimit?:")
n = positiveinput("How many division intervals do you want?:")
Having this code as a guide, you can complete the list of errors verification that #tim-mccurrach have written in an answer to this post. Also you can check out this link where they make the Riemann Sum in a different way. For documentation about try-catch you can enter this link.
I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?
Here is my code:
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
print ('Wrong')
else:
print ('Correct')
You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."
import random
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
print('Wrong')
else:
print('Correct')
Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.
Here is the mistake,
random = print(random.randint(1,9))
You need to do something like this.
random = random.randint(1,9)
print(random)
Also, you have already converted the input to int so, you can do just this.
if x != random:
As pointed out your mistake is the line
random = print(random.randint(1,9))
But why?
functions (like print() take something, do something (with it) and give something back.
Example:
sum(3,4) takes 3 and 4, may add them and returns 7.
print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").
You then assign None to the name random and test if it equals your number, which it (of course) doesn't.
I'm currently in a python coding class and this is an assignment. I apparently have an infinite loop somewhere in my code, yet I can't seem to find it.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# At this point the program should take your now factorial and give you the fibonacci sequence
# takes your factorial and makes it the fibonacci
nterms = factorial
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
I've used both the debugging tool and attempted to find the problem myself by running the programming and attempting various break sequences but I'm just not grasping it.
There is no infinite loop in your code, both loops will finish in finite time. What is happening is that your teacher, without looking at your code, has discovered that the finite time is very, very long and mistaken this for an infinite loop.
The reason it's taking so long is that you have misunderstood the question - "I was asked to make a program that took an integer and gave me said factorial of an integer. Then give the Fibonacci sequence of the integer" - means find the factorial and Fibonacci sequence of the same integer rather than feeding the first result into the second. Simply replace the line nterms = factorial with the line nterms = num to fix the problem.
(See comments on question for additional information used in this answer)
First, you already know what a loop is and how it works. You should review the loop in your code and make sure any variable used is defined. Since this is an assignment, this is the best I can do for you, to be honest your problem is already solved.
Maybe try enclosing your code in a function with arguments/input-variables, this way your code might run smoother and better. Hope this helps.
I am working in python 2.7.8.
I'm currently learning about parameters and methods. What I'm trying to accomplish is have a user enter two different variables then pass them to an argument within different methods, sum() and difference().
My following code is something like this:
def computeSum(x, t):
x = int(raw_input('Please enter an integer: '))
t = int(raw_input('Please enter a second integer: '))
x+t
return Sum
def computeDif(y, j):
y = int(raw_input('Please enter an integer: '))
j = int(raw_input('Please enter a second integer: '))
y+j
return Dif
def main():
raw_input('Would you like to find the sum of two numbers or the difference of two numbers?: ')
answer = 'sum'
while True:
computeSum()
else:
computeDif()
For some reason my compiler (pyScriptor) isn't running and I cannot see any output nor error messages, its just blank. Can anyone possibly help me with any syntax/logic errors?
There are a few problems with your code
Your indentation is way off
computeSum and computeDif expect the two numbers as parameters, but then also ask for them from the terminal
You return the variables Sum and Dif, but never assign values to them
You call either computeSum or computeDif, but never do anything with the returned value
You never call main. Do you know that you don't need a main function? You can just put the code in line after the function definitions
This is probably a little closer to what you had in mind
def computeSum(x, t):
return x + t
def computeDif(y, j):
return y - j
def main():
while True:
answer = raw_input('Would you like to find the "sum" of two numbers or the "dif"ference of two numbers? ')
a = int(raw_input('Please enter an integer: '))
b = int(raw_input('Please enter a second integer: '))
if answer == 'sum':
print(computeSum(a, b))
elif answer == 'dif':
print(computeDif(a, b))
else:
print('Please enter "sum" or "dif"')
main()
The problem is that you don't need a main() function. Just put the code, unindented, by itself, and it will run when you run the program.