The user is asked to input a, b, c, and n. n must be greater than 2, so I am checking for that in checkn(). There's probably a far simpler method in doing this; if there is please let me know!
Traceback says "Error: name 'n' is not defined'. I am assuming I am having some confusion with local and global variables but I am unsure of how to get around this mistake of mine.
What am I misunderstanding?
Here is my code:
import math
def fermat():
if (a**n) + (b**n) == (c**n):
print('Holy smokes, Fermat was wrong!')
else:
print("No, that doesn't work")
def checkn():
print('insert n, must be greater than 2')
n = int(input())
if n <= 2:
print('n must be greater than 2')
checkn()
else:
fermat()
a = int(input('input a\n'))
b = int(input('input b\n'))
c = int(input('input c\n'))
checkn()
Yes. You are trying to access the n variable that is locally scoped to the checkn function. The easiest way to solve this, is for your fermat function to take an argument, and then in your checkn function, pass n to fermat.
Defining fermat to take an argument:
I changed the argument to be x just to help isolate the fact that the n variables are not the same. You are passing the value to the function.
def fermat(x):
if (a**x) + (b**x) == (c**x):
print('Holy smokes, Fermat was wrong!')
else:
print("No, that doesn't work")
In the checkn function, pass n to fermat (relevant part shown only):
else:
fermat(n)
Just to add for the sake of completion. (By restructuring your code, you do not have to pass any variable to the function call)
def fermat():
N = powN;
while N <= 2:
N = int(input("Please enter pow > 2: \n"));
if (a**N) + (b**N) == (c**N):
print("Fermat is wrong my holy!!");
else:
print("That doesn't work");
a = int(input("Enter x: \n"));
b = int(input("Enter y: \n"));
c = int(input("Enter z: \n"));
powN = int(input("Enter pow: \n"));
fermat();
Related
def Factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
def Fibonacci(num):
i=0
present=1
previous=0
while i<=num:
nextterm=present+previous
present=previous
previous=nextterm
i=i+1
print("The fibonacci number for", i, 'is', nextterm)
def CallFibOrFac(x):
num = 10
if x == 'Fib':
Fibonacci(num)
if x == 'Fac':
print (Factorial(n))
x = input('enter fibonacci or factorial')
num = input('enter value for fibonacci')
Fibonacci(num)
n = input('enter value for factorial'
print(Factorial(n))
I defined all my functions and wrote an if statement, but when I enter Factorial, when it asks for x=input(‘enter fibonacci or factorial’), it gives me the input to ‘enter value for fibonacci’ when I need the n=input(‘enter value for factorial’) to display when I put in "factorial".
Although you have a function to choose whether to call Fib or Fact, you never call that deciding function. Instead, what I take to be your main program utterly ignores the user's first input and proceeds to call both functions.
Back up a few steps. Learn to recognize the user's input and call -- or do not call -- a single function.
I am trying to get my function to take two arguments, and return their sum. Am I going about this the right way? This is what I have so far:
def my_sum(a, b):
sum = a + b
def main():
a = input(int("enter a number: ", a)
b = input(int("enter a number: ", b)
sum = a + b
return sum
print(" result: ", sum)
main()
So it looks good, but the main problem is that you aren't actually calling your function :) Once you get your two numbers, you can then make the call to your function (which you have properly set up):
def main():
# When you assign variables here, make sure you are putting the int outside
# You also don't need to reference the variable twice
a = int(input("enter a number: "))
b = int(input("enter a number: "))
# Here is where your call goes (try to avoid using variable names that
# are the same as Python keywords, such as sum)
s = my_sum(a, b)
print(" result: ", s)
Now, one other thing you'll have to do is modify your function to return a value. You're already almost there - just add a return (note that since you are just returning the sum of the two numbers, you don't have to assign it to a variable):
def my_sum(a, b):
return a + b
This now means that when you run s = my_sum(a, b), your function will return the sum of those two numbers and put them into s, which you can then print as you are doing.
One other minor thing - when you use the setup you are (with def main(), etc.), you usually want to call it like this:
if __name__ == '__main__':
main()
At this stage, don't worry too much about what it means, but it is a good habit to get into once you start getting into fun stuff like modules, etc. :)
You Have written Wrong coding Style
If you want to do some by using sum method than do this
def my_sum(a, b):
sum = a + b
return sum
def main():
a = int(raw_input("enter a number: "))
b = int(raw_input("enter a number: "))
sum = my_sum(a,b)
print" result: ", sum
main()
I hope this will work as per your requirement.
Regards,
Anil
I am not sure of the purpose of the first function you have defined there (my_sum). However, there are a few things wrong in main as well. The return function always exits the function it is in, and zooms out to a higher level scope. This is very similar to break, except that it returns a value as well. Also, your syntax when you ask for user input is incorrect. It should be:
def main():
a = int(raw_input("Enter a number: "))
b = int(raw_input("Enter a number: "))
return "Result" + (a+b)
main()
Also, if you wanted my_sum to automatically return the sum, you should use return or print:
def my_sum(a, b):
return a + b
doing a print function after return sum won't work because when returning a return value, the execution will exit the scope, the orders should be reversed.
your input function is not implemented correctly.
The correct code should be:
def main():
a = input("enter a number: ")
b = input("enter a number: ")
sum = a + b
print(" result: ", sum)
return sum
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am having a problem with my python school assignment and I can't figure out what I am doing wrong. I either get a global name not defined or if I change things around I get different sythax errors. I am hoping that someone will be able to assist me in what I am doing wrong.
Here is a image of the assignment details:
def main():
x = int(input("Give me integer #1: "))
y = int(input("Give me integer #2: "))
z = input("Give me a string: ")
print("min:",min(x,y))
print("max:",max(x,y))
print("equal:",equal(x,y))
print("is_even:",is_even(x))
print("is_odd:",is_odd(x))
print("format_dollar:",format_dollar(x))
print("lab_grade:",lab_grade(x))
print("is_unlucky:",is_unlucky(x))
print("is_lucky:",is_lucky(x))
print("pluralize:",pluralize(z))
#1 This function will figure out the min of 2 integer arguments and return the smaller one
def min(num1,num2):
if num1 >= num2: return num1
else: return num2
#2 This function will figure out the max of 2 integer arguments and return the smaller one
def max(num1,num2):
if num1 <= num2: return num1
else: return num2
#3 This function will figure out if the 2 numbers are equal
def equal(x,y):
if x == y: True
else: False
#4 This function will find out if the number is even
def is_even(num1,num2):
is_even = x
if x % 2 == 0: return ("True")
else: return ("False")
#5 This function will find out if the number is odd
def is_odd(num1,num2):
is_odd = x
if x % 2 == 1: return ("True")
else: return even
#6 This function will format the returned string
def format_dollar(num1,num2):
x**('.2f')
#7 This function will fin out a lab grade
def lab_grade(x):
lab_grade = int(raw_input("Enter the student's grade: "))
if grade >= 90:
return 'A'
if grade >= 80:
return 'B'
if grade >= 70:
return 'C'
if grade >= 60:
return 'D'
else:
return 'F'
#8 This will determine if the function is un_lucky
def is_unlucky(x):
if x == 4:
return ('True')
if x == 13:
return ('True')
if x == 7:
return ('True')
else: ('False')
print()
#9 This will determine if the function is lucky
def is_lucky(x):
if x == 3:
return ('True')
if x == 4:
return ('True')
if x == 8:
return ('True')
if x == 7:
return ('True')
else:
return ('False')
print('')
#10 This function will pluralize
def pluralize(z):
if not z:
return plural
print('')
main()
Your is_even() and is_odd() functions look evenly-odd..
Well, that was just a joke.. Sorry.. But you are taking two different parameters num1, and num2 whereas you are using a variable x getting assigned to an unknown variable is_even which I don't understand what is doing there??
change even from:
def is_even(num1,num2):
is_even = x
if x % 2 == 0: return ("True")
else: return ("False")
to:
def is_even(num1):
if num1 % 2 == 0:
return ("True")
else:
return ("False")
why?:
You only need one input
you shouldn't use the global x
you shouldn't set is_even, a function, to a value.
is odd and format_dollar suffer from similar problems.
If I had to guess, I'd say that what you did was write all 10 functions at one sitting then fired the whole mess up to see if it worked. After the first half hour of banging your head against it you probably got to the point where you were just randomly changing things to see if by a miracle the smoke would clear.
Since this appears to be a very basic assignment I'll refrain from suggesting things like using test driven development, but you could make your life much easier by taking a more incremental approach.
First off start with your main and get it running so that all your function calls work without generating errors, something like:
def main():
x = int(input("Give me integer #1: "))
y = int(input("Give me integer #2: "))
z = input("Give me a string: ")
print("min:", min(x, y))
print("max:", max(x, y))
print("equal:", equal(x, y))
print("is_even:", is_even(x))
print("is_odd:", is_odd(x))
print("format_dollar:", format_dollar(x))
print("lab_grade:", lab_grade(x))
print("is_unlucky:", is_unlucky(x))
print("is_lucky:", is_lucky(x))
print("pluralize:", pluralize(z))
def min(x, y):
return x
def max(x, y):
return x
# Fill in all the other functions here in the same fashion.
main()
Do the same for all the functions, just return the first parameter passed in. Once you get it so that your code runs without generating any errors. Go function by function fixing each one to return the correct results. A trick to make your life even easier is to hack main() (just for testing) to be:
def main():
#x = int(input("Give me integer #1: "))
#y = int(input("Give me integer #2: "))
#z = input("Give me a string: ")
x = 5
y = 8
z = 'foobar'
print("min:", min(x, y))
print("max:", max(x, y))
print("equal:", equal(x, y))
print("is_even:", is_even(x))
print("is_odd:", is_odd(x))
print("format_dollar:", format_dollar(x))
print("lab_grade:", lab_grade(x))
print("is_unlucky:", is_unlucky(x))
print("is_lucky:", is_lucky(x))
print("pluralize:", pluralize(z))
This way you can run your program quickly without having to enter input each time. Once you get it working well, you can then remove the comments from in front of the inputs and remove your hard-coded values and turn it in with main() unchanged.
When returning True/False, you should use the actual Boolean values True and False, not their string representations. Also as the assignment specifically called out elif, you should probably use if/elif/else statements rather than a bunch of discreet ifs as your code had.
#9 This will determine if the function is lucky
# x = number to test
# returns True if number is lucky, else False
def is_lucky(x):
if x == 3:
return True
elif x == 4:
return True
elif x == 8:
return True
elif x == 7:
return True
else:
return False
This is kind of a double-barreled question, but it's got me puzzled. I currently have the following code:
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
Now, I'd like to have some kind of loop (I'm guessing it's a for loop, but I'm not entirely sure) so that after a function has been completed, it'll return to the top, so the user can enter a new function number and do a different equation. How would I do this? I've been trying to think of ways for the past half hour, but nothing's come up.
Try to ignore any messiness in the code... It needs some cleaning up.
It's better to use a while-loop to control the repetition, rather than a for-loop. This way the users aren't limited to a fixed number of repeats, they can continue as long as they want. In order to quit, users enter a value <= 0.
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
while function > 0:
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer = b/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
print 'Enter a value <= 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
You can tweak this (e.g., the termination condition) as needed. For instance you could specify that 0 be the only termination value etc.
An alternative is a loop that runs "forever", and break if a specific function number is provided (in this example 0). Here's a skeleton/sketch of this approach:
function = int(raw_input("Type function no.: "))
while True:
if function == 1:
...
elif function == 2:
...
elif function == 0:
break # terminate the loop.
print 'Enter 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
Note: A for-loop is most appropriate if you are iterating a known/fixed number of times, for instance over a sequence (like a list), or if you want to limit the repeats in some way. In order to give your users more flexibility a while-loop is a better approach here.
You simply need to wrap your entire script inside a loop, for example:
from __future__ import division
import math
for _ in range(10):
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
This will run your if statement 10 times in a row.
I'd try this:
while True:
function = ...
if function == 0:
break
elif ...
Here is what i wrote:
number = raw_input('Enter an integer= ')
if number < 0:
print 'Invalid number'
else:
for k in range(1,(number)):
number *= k
print number
I want to be able to input any number (that is greater than 0), but when i input a number say 4 (the factorial of 4 is 24) i get this error:
Traceback (most recent call last):
File "problem.py", line 6, in <module>
for k in range(1,(number)):
TypeError: range() integer end argument expected, got str.
I don't understand what it means and as far as i know the code should be working, Please Help!
This works perfectly: factorial.py
#!/usr/bin/env python
# imports go here
__author__ = 'Michael O. Duffy'
__status__ = "Development"
def factorial(n):
""" Calculate a factorial of an integer """
factorial = 1
if n < 0:
print 'Invalid number'
else:
for k in range(1,n+1):
factorial *= k
return factorial
if __name__ == '__main__':
for number in range(1, 20):
print 'n: ', number, 'n!: ', factorial(number)
You should know that this is an inefficient, academic implementation that shouldn't be used in any serious application. You'll be a lot better off using a gamma or lngamma implementation and a dictionary cache to save on calculations if you use values repeatedly:
http://mathworld.wolfram.com/GammaFunction.html
What about recursion?
def factorial(n):
if n < 0:
print("ERROR!") # throw error, return -1, or whatever
elif n <= 1:
return 1
else:
return n * factorial(n - 1)
raw_input returns a string, not an integer. Create an integer this way:
number = int(raw_input('Enter an integer= '))
The user might type something besides an integer, in which case you might want to handle that possibility.
while True:
try:
number = int(raw_input('Enter an integer= '))
except ValueError:
print "That wasn't an integer"
else:
break
using xxxxx.py
num=int(raw_input("Enter a number"))
n=1
while num>=0:
n=n*num
num=num-1
print "Factorial of the given number is: ",n