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].
Related
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")
I'm trying to create a program that checks whether the credit card number the user inputed is either invalid, or from AMEX, MASTERCARD, or VISA. I'm using Luhn's formula. Here is a site that contains the explanation to the formula I'm using: https://www.geeksforgeeks.org/luhn-algorithm/
It works with all credit card numbers, except credit cards from AMEX. Could someone help me?
Here is my code:
number = input("Number: ")
valid = False
sumOfOdd = 0
sumOfEven = 0
def validation(credit_num):
global sumOfOdd
global sumOfEven
position = 0
for i in credit_num:
if position % 2 != 0:
sumOfOdd += int(i)
else:
product_greater = str(int(i) * 2)
if len(product_greater) > 1:
sumOfEven += (int(product_greater[0]) + int(product_greater[1]))
else:
sumOfEven += int(product_greater)
position += 1
def main():
if (sumOfOdd + sumOfEven) % 10 == 0:
if number[0] == "3":
print("AMEX")
elif number[0] == "5":
print("MASTERCARD")
else:
print("VISA")
else:
print("INVALID")
print(f"{sumOfOdd + sumOfEven}")
validation(number)
main()
Here are some credit card numbers:
VISA: 4111111111111111
MASTERCARD: 5555555555554444
AMEX: 371449635398431
I've found many different ways to calculate this formula, but I'm not sure if mine is correct.
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()
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()
So I am trying to run a program on python3 that asks basic addition questions using random numbers. I have got the program running however, I wanted to know if there was a way I could count the occurrences of "Correct" and "Wrong" so I can give the person taking the quiz some feedback on how they did.
import random
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
else:
print ('Wrong.')
You could use a dict to store counts for each type, increment them when you come across each type, and then access it after to print the counts out.
Something like this:
import random
stats = {'correct': 0, 'wrong': 0}
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
stats['correct'] += 1
else:
print ('Wrong.')
stats['wrong'] += 1
print "results: {0} correct, {1} wrong".format(stats['correct'], stats['wrong'])
import operator
import random
def ask_float(prompt):
while True:
try: return float(input(prompt))
except: print("Invalid Input please enter a number")
def ask_question(*args):
a = random.randint(1,100)
b = random.randint(1,100)
op = random.choice("+-/*")
answ = {"+":operator.add,"-":operator.sub,"*":operator.mul,"/":operator.div}[op](a,b)
return abs(answ - ask_float("%s %s %s = ?"%(a,op,b)))<0.01
num_questions = 5
answers_correct = sum(map(ask_question,range(num_questions)))
print("You got %d/%d Correct!"%(answers_correct,num_questions))