NameError: name 'recPower' is not defined - python

I am working on a assignment and am encountering this error. NameError: name 'recPower' is not defined
Write a recursive function called pow(base, power) that takes in two numbers. First number is a base and the second number is a power. The function will return the number raised to the power. Thus, if the number is 2 and the power is 4, the function will return 16. (75 points).
Write a main() function that asks for a number and a power. Then calls the recursive function created in step 1 (15 points).
DO NOT use the algorithm on page 432 of your book:
def: recPower (a, n):
if n == 0:
return 1
else:
factor = recPower (a, n//2)
if n%2 == 0:
return factor * factor
else:
return factor * factor * a
My current code is as follows
def main():
a=input("enter base :")
n=input("enter power :")
print ("Total = ",recPower(a,n))
main()
def recPower (a,n):
if n == 0:
return 1
else:
return a*recPower(a,n-1)
`
The error I get when I run it is :
Traceback (most recent call last):
File ".py", line 7, in
main()
File ".py", line 5, in main
print ("Total = ",recPower(a,n))
NameError: name 'recPower' is not defined

Functions are stored in identifiers. You have to define it first. Try this one:
def recPower(a, n):
if n == 0:
return 1
else:
return a * recPower(a, n - 1)
def main():
a = int(input("enter base :"))
n = int(input("enter power :"))
print ("Total = ", recPower(a, n))
main()

Define your 'run' function after 'recPower'.
As also mentioned you need to convert the strings that are returned from input() into integers or floats, using either int() or float(). When you try to operations like division you'll get TypeError exceptions.

write your method above the main code, because if you write at under the main code method is undefinied

functions must be defined before any are used.
try this code
def recPower(a, n):
# or just a, n = int(a), int(n) is fine
if isinstance(a, str):
a = int(a)
if isinstance(n, str):
n = int(n)
if n == 0:
return 1
else:
return a * recPower(a, n - 1)
def main():
a = input("enter base :")
n = input("enter power :")
print ("Total = ", recPower(a, n))
main()

Related

How to show that using 'cache' in a Python program is more efficient?

The program uses two ways to calculate the Collatz Conjecture sequence, I want to show that the method using cache, rather than starting from scratch is more efficient - uses fewer processes. I have tried using the time module and it keeps giving inconsistent results - sometimes the cache method appears to be slower than calculating the sequence from scratch.
cache = {}
def in_cache(n):
if n in cache.keys():
return True
else:
return False
def calculate_collatz(n):
count = 0
collatz_sequence = "N: " + str(n)
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = (3 * n) + 1
count += 1
collatz_sequence += " -> {}".format(n)
return (collatz_sequence, count)
def collatz(n):
if in_cache(n):
print("Using cache...")
return cache[n]
else:
print("Calculating from scratch...")
result = calculate_collatz(n)
cache[n] = result
return result
choice = ""
while choice != 'Q':
#print('The cache: ', cache)
choice = input("Enter an integer to calculate the Collatz Conjecture sequence. Enter Q to quit\n")
try:
n = int(choice)
print(collatz(n))
except:
print("You did not enter a whole number")

UnboundLocalError: local variable 'sumOfOdd' referenced before assignment in Python3

I'm trying to run this code:
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
def main():
print(f"Your credit card number is {number}, it's third digit is {number[2]}")
print(f'sum of odds: {sumOfOdd}')
validation(number)
main()
But I get this error:
Traceback (most recent call last):
File "credit.py", line 15, in <module>
validation(number)
File "credit.py", line 8, in validation
sumOfOdd += i
UnboundLocalError: local variable 'sumOfOdd' referenced before assignment
I'm able to run, but when I input any number it gives me this error
This error occurs because the variable sumOfOdd is not accessible from within the function. You could declare the variable global in the function, but you should be careful using the global statement.
In my opinion, a better way to do this is to supply sumOfOdd as an argument to the function and return the updated variable:
def validation(credit_num, sumOfOdd):
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
return sumOfOdd
validation(number, 0)
# Returns the correct sum.
Or, if you know that the sumOfOdd should always be initialized by zero, you could define the variable locally:
def validation(credit_num):
sumOfOdd = 0
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
return sumOfOdd
Here's a working version of your code.
Note that it now iterates through credit_num as for num in credit_num. If you use for i in range(len(credit_num)) you are iterating through a list of indexes and would need to use if int(credit_num[i]) % 2 != 0, reason being that range(N) returns a list [0, 1, 2... N-1] where for num in credit_num iterates through [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4] if your input string was 1111222233334444
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
global sumOfOdd
for num in credit_num:
if int(num) % 2 != 0:
sumOfOdd += 1
def main():
print(f"Your credit card number is {number}, it's third digit is {number[2]}")
print(f'sum of odds: {sumOfOdd}')
validation(number)
main()
Note that validation(number) is called in global scope along with main(), hence the global sumOfOdd declaration inside to allow def validation to gain access to that variable.
A different way to write this code to make it more readable would be:
if __name__ == "__main__":
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
sumOfOddToReturn = 0
for num in credit_num:
if int(num) % 2 != 0:
sumOfOddToReturn += 1
return sumOfOddToReturn
sumOfOdd = validation(number)
print(f"Your credit card number is `{number}`, its third digit is `{number[2]}`.")
print(f'sum of odds: {sumOfOdd}')

Getting errors from my program that i cant understand

I am writing a Program for my beginner python class for Credit Card Validation using Luhn's Algorithm to output if a user entered credit card number is valid or not, and i am getting errors i don't know how to fix. Can anyone who is smarter than me see whats wrong with my code. Thanks so much all.
def main():
# user will input the credit card number as a string
# call the function isValid() and print whether the credit card number is valid or not valid
number = int(input("Enter a Credit Card Number as a Long Integer: "))
if isValid(number):
print(number, "is Valid.")
else:
print(number, "is Not Valid.")
def isValid(number):
# Return true if the card number is valid
# You will have to call function sumOfDoubleEvenPlace() and sumOfOddPlace()
return (str(number).startswith("4") or str(number).startswith("5") or str(number).startswith("37")) and \
(sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0
def sumOfDoubleEvenPlace(number):
# Sum of all single-digit numbers from step one
total = 0
for num in range(len(str(number)) -2, -1, -2):
total += getDigit(int(number[num]) * 2)
return total
def getDigit(number):
# Return the number if it is a single digit, otherwise return
# the sum of the two digits
return number % 10 + (number // 10 % 10)
def sumOfOddPlace(number):
total = 0
for num in range(len(number) -1, -1, -2):
total += int(number[num])
return total
main()
Fixed the code:
def main():
number = input("Enter a credit card number as a string: ").strip()
if isValid(number):
print(number, "is valid")
else:
print(number, "is invalid")
# Return true if the card number is valid
def isValid(number):
return (number.startswith("4") or number.startswith("5") or
number.startswith("6") or number.startswith("37")) and \
(sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0
# Get the result from Step 2
def sumOfDoubleEvenPlace(cardNumber):
result = 0
for i in range(len(cardNumber) - 2, -1, - 2):
result += getDigit(int(cardNumber[i]) * 2)
return result
# Return this number if it is a single digit, otherwise, return
# the sum of the two digits
def getDigit(number):
return number % 10 + (number // 10 % 10)
# Return sum of odd place digits in number
def sumOfOddPlace(cardNumber):
result = 0
for i in range(len(cardNumber) - 1, -1, -2):
result += int(cardNumber[i])
return result
main()
As you do elsewhere in this code, you need a string: str(number)[num] instead of number[num].

Importing a returned variable from a function (python 3)

I am trying to write a separate module that takes in a variable from the first module (the number entered) and finds all the prime numbers up to that entered number. I understand that you cannot call a variable from within a function into another file unless it is a global variable or unless it is returned. From what I understand and I am avoiding this issue by calling a returned variable 'prime' from the function 'get_number', but I'm still getting the errors: "function 'get_number' has no 'prime' member" on the fourth line of the second file and " and "no value for argument 'prime' in function cell" on the last line of the second file. It is this error that I was trying to get around by inputting some value for prime from the first file.
Traceback (most recent call last):
File "beginner_python_2.py", line 1, in <module>
from beginner_python_1 import get_number
File "/home/ubuntu/workspace/beginner_python_1.py", line 5, in <module>
prime = get_number()
NameError: name 'get_number' is not defined
These are my two files:
#a.py
import math
def main():
number = get_number()
is_it_prime = is_prime(number)
print(is_it_prime)
def get_number():
"""Function to ensure user inputs a positive integer"""
while True:
prime = input("enter a positive integer: ")
if prime.isdigit():
prime = int(prime)
return prime
def is_prime(number):
"""Function to determine if inputted integer is a prime number"""
if number % 2 == 0:
print("{} is not a prime number".format(number))
return False
if number != 2:
for i in range(3,int(math.sqrt(number))+1,2):
if number % i == 0:
print("{} is not a prime number".format(number))
return False
print("{} is a prime number".format(number))
return True
if __name__=="__main__":
main()
This is the second file:
#b.py
from a import get_number
def return_primes(prime):
for i in range(1,a.prime+1):
for j in range(2,i):
if i % j == 0:
break
else:
print("{}".format(i),end=" ")
if __name__=="__return_primes__":
return_primes()
Thank you very much for any guidance.
It looks to me like you want b.py to be something more like:
from a import get_number
def return_primes(limit):
if limit > 1:
print(2, end=" ")
for i in range(3, limit + 1, 2): # beyond 2, only odds are prime
for j in range(3, int(i ** 0.5) + 1, 2): # only odds to sqrt
if i % j == 0:
break
else: # no break
print(i, end=" ")
print()
if __name__ == "__main__":
return_primes(get_number())
The if __name__ == "__main__" only tests if this file is currently being used as a library or being excuted as a program. So it's fine to have the same test in both a.py and b.py.
USAGE
> python3 b.py
enter a positive integer: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
>

I am using a recursive function and need to print from within the function just once

I am using python 3 and need to print the final result from within the function(this is not optional). Instead it is printing every time it goes through the function.
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
print(result)
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplay(number)
main()
If you enter 12345 it prints out
21
321
4321
54321
I want it to print out 54321
The following worked for me (after I found a Python 3 interpreter online):
def reverseDisplay(n):
tmp = n % 10 # Determine the rightmost digit,
print(tmp, end="") # and print it with no space or newline.
if n == tmp: # If the current n and the rightmost digit are the same...
print() # we can finally print the newline and stop recursing.
else: # Otherwise...
reverseDisplay(n // 10) # lop off the rightmost digit and recurse.
If you need to return the reversed value in addition to printing it:
def reverseDisplay(n):
tmp = n % 10
print(tmp, end="")
if n == tmp:
print()
return tmp
else:
return int(str(tmp) + str(reverseDisplay(n // 10)))
You just need to move your print statement out of the reverseDisplay and into main:
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return result
def main():
number = 12345
print reverseDisplay(number)
main()
If you really need to print it in the recursive function, you'll have to add a parameter (called first in this example) to make sure you only print the first time:
def reverseDisplay(number, first=True):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10, False)))
if first:
print(result)
return result
Try this:
def reverseDisplayPrinter(number):
print reverseDisplay(number)
def reverseDisplay(number):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplayPrinter(number)
main()

Categories

Resources