How to better implement a history of user action? - python

I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break

I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()

Related

Variables not recorded in the while loop

my problem lies within the lines of #. I don't understand why the invalidDish is always True even after it is set to False in one of the if statement.
class dishes:
def __init__(self, serial_no, dish_name, price):
self.serial_no = serial_no
self.dish_name = dish_name
self.price = price
def show_menu(self):
print(str(self.serial_no) + '. ' + self.dish_name + '\t$' + self.price)
def errorMessage(code, range):
if code == 'outOfRange':
print('***Please enter number 1 - {} only***\n'.format(str(range)))
machineRunning()
plain_prata = dishes(1, 'Plain prata', '0.50')
egg_prata = dishes(2, 'Egg prata', '1.00')
cheese_prata = dishes(3, 'Cheese prata', '2.50')
garlic_prata = dishes(4, 'Garlic prata', '1.50')
ham_prata = dishes(5, 'Ham prata', '2.50')
menu = [plain_prata, egg_prata, cheese_prata, garlic_prata, ham_prata]
current_order = []
def machineRunning():
while True:
print('1. Menu')
print('2. Add order')
print('3. Checkout')
value = input('Please input:')
try:
value = int(value)
if value < 1 or value > 3:
errorMessage('outOfRange', 3)
except ValueError:
print('***Please enter number 1 - 3 only***\n')
continue
if value == 1:
print()
for x in range(len(menu)):
menu[x].show_menu()
elif value == 2:
dish = input('Dish name/number:')
try:
dish = int(dish) - 1
if dish < 0 or dish >= len(menu):
errorMessage('outOfRange', len(menu))
except ValueError:
loop = True
while(loop):
for x in range(len(menu)):
dish = dish.capitalize()
split_dish = dish.split()
if dish == menu[x].dish_name:
dish = int(x)
loop = False
break
else:
invalidDish = True
x = 0
############################################
while invalidDish and x < len(menu):
print (invalidDish)
print (x)
if split_dish[0] in menu[x].dish_name:
isDish = input('Are you ordering ' + menu[x].dish_name + '?')
print('isDish',isDish.lower())
if 'y' in isDish.lower(): #TurningPoint
print('Entered here')
invalidDish = False
print(invalidDish)
break
else: x += 1
else: x += 1
##########################################
if invalidDish:
print('***Invalid dish name***\n')
dish = input('Dish name/number:')
amount = input('Amount:')
current_order.append([menu[dish].dish_name, menu[dish].price, amount])
else:
print('***Please enter number 1 - 3 only***\n')
for x in current_order:
print (x)
machineRunning()
I tried to follow the code in terminal and still can't figure out the problem. This is the result from the terminal.
1. Menu
2. Add order
3. Checkout
Please input:2
Dish name/number:c
True
0
True
1
True
2
Are you ordering Cheese prata?y
isDish y
Entered here
False #It is set to False at this point
True #Why it becomes True again at the beginning of the loop?
0
True
1
PS. Am learning python by trying to make a cash register for a restaurant, with generating weekly, monthly summary, calculating profit etc. Any suggestion on what I can do next to make this more user-friendly? Like python talks to other software or code making the interface for easy to use?
You are breaking out of the while loop, then looping again using the outer for loop, which then sets invalidDish to True.

Making a loop to go on for as long as the number is

I want a program so I can enter a big integer and it will do a calculation like this:
62439 = (6 - 2 + 4 - 3 + 9)
Basically it splits them up and the first and third should be added and the second and the fourth should be subtracted. Please follow the loop sort of method. I can't have the elif and if working in the same run of the loop.
num = input("Input any number: ")
total = 0
p = 0
x= 0
q = 0
number = len(num)
if len(num) ==5 :
total = 0
for i in range(0,(number)):
p = p+2
q = q +1
if x == 2 and q == p:
total = total+(int(num[q]))
x=1
p=p-1
elif x == 1 and q == p :
total = total-(int(num[q]))
x=2
p=p-1
print("your number is: ",total)
I expect it to repeat the loop as many times as there are numbers in the integer that is entered e.g (333) executes 3 times
num = input("Enter a number: ")
sum = 0
do_add = True
try:
for digit in num:
if do_add:
sum += int(digit)
else:
sum -= int(digit)
do_add = not do_add
except Exception:
print("Invalid input")
else:
print("The result is", sum)
Why not just perform the calculation:
num = input("Input any number: ")
if len(num) == 5:
total = int(num[0])-int(num[1])+int(num[2])-int(num[3])+int(num[4])
print("your number is: ",total)
Maybe like this:
def main():
digits = input("Enter a number: ")
assert digits.isdigit()
result = sum(int(digit) * [1, -1][index%2] for index, digit in enumerate(digits))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Or like this if you wanna be more deliberate - also easier to extend:
def main():
from operator import add, sub
digits = input("Enter a number: ")
assert digits.isdigit()
operations = [add, sub]
result = 0
for index, digit in enumerate(digits):
result = operations[index%len(operations)](result, int(digit))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Or just go overkill (also known as "taking advantage of the standard library"):
def main():
from itertools import cycle
from operator import add, sub
from functools import reduce
while True:
digits = input("Enter a number: ")
if digits.isdigit():
break
operation_iter = cycle([sub, add])
def operation(a, b):
return next(operation_iter)(a, b)
result = reduce(operation, map(int, digits))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())

Why am I getting a Traceback (most recent call last):

I cannot create an object of class Animal. If I do so it gives me an error saying "Unresolved reference Animal" when the #FILE I/0 code is commented out.
And if the it isn't then it gives me the error as shown in the image. Traceback most recent call: last error
Can someone help me out with this? I'm making this complete file so that I can cover the basic syntax of PYTHON.
import random
import sys
import os
import math
#SIMPLE THINGS AND MATHS
print("STARTING SIMPLE THINGS AND MATHS!!!")
print("Hello World") #This is a code for printing hello world
#Comment
"""
This
is a
multiline
comment
"""
name = "Derek"
y="2"
print (y)
print(name)
#Numbers Strings List Tuples Dictionaries
#+ - * / % ** //
name=15
print(name)
print("5 + 2 =",5+2)
print("5 - 2 =",5-2)
print("5 * 2 =",5*2)
print("5 / 2 =",5/2)
print("5 % 2 =",5%2)
print("5 ** 2 =",5**2)
print("5 // 2 =",5//2)
print("1 + 2 - 3 * 2 =", 1 + 2 - 3 * 2)
print("(1 + 2 - 3) * 2 =", (1 + 2 - 3) * 2)
quote = "\"Always remember you are unique\""
print("Single line quote: ",quote)
multi_line_quote = "\"""""Just
like everyone else""""\""
print("Multi Line quote: ",multi_line_quote)
print("%s %s %s" %('I like the quote', quote, multi_line_quote))
print("I dont like ",end="")
print("newlines")
print('\n'*5)
print("LISTS!!!")
#LISTS
grocery_list = ['Juice','Tomatoes','Potatoes',
'Bananas']
print('First item: ',grocery_list[0])
grocery_list[0] = "Green Juice"
print('First item: ',grocery_list[0])
print(grocery_list[1:3])
other_events=['Wash Car', 'Pick Up Kids','Cash Check']
to_do_list = [other_events, grocery_list] #list within a list
print(to_do_list[1][1]) #2nd item of second list
grocery_list.append('Onions')
print(to_do_list)
grocery_list.insert(1,"Pickle") #Inserting item on second index
print(to_do_list)
grocery_list.remove("Pickle") #Removing pickle from grocery list
print(to_do_list)
grocery_list.sort() #Sorting grocery list alphabetically
print(to_do_list)
grocery_list.reverse() #Sorting grocery list in reverse order albhabetically
print(to_do_list)
del grocery_list[4] #Delete item from grocery list which is on index 4
print(to_do_list)
to_do_list2 = other_events + grocery_list
print(len(to_do_list2))
print(max(to_do_list2)) #Whatever comes last alphabetically
print(min(to_do_list2)) #Whatever comes first alphabetically
to_do_list2.insert(1,"Bananas")
print(min(to_do_list2))
print("\n"*5)
#Tuples
print("TUPLES!!!")
pi_tuple=(3,1,4,1,5,9)
new_tuple=list(pi_tuple) #Converting tuple to list
new_list=tuple(new_tuple) #Converting list to tuple
print(len(new_list))
print(max(new_list))
print(min(new_list))
print("\n"*5)
#Dictionaries
print("DICTIONARIES!!!")
super_villains={'Fiddler':'Isaac Bowin',
'Captain Cold': 'Leonard Snart',
'Weather Wizard': 'Mark Mardon',
'Mirror Master': 'Sam Scudder',
'Pied Piper':'Thomas Peterson'}
print(super_villains['Captain Cold'])
print(len(super_villains))
del super_villains['Fiddler']
super_villains['Pied Piper']='Hartley Rathway'
print(len(super_villains))
print(super_villains.get("Pied Piper"))
print(super_villains.keys())
print(super_villains.values())
print("\n"*5)
#IF ElSE ELIF == != > >= < <=
print("IF ElSE ELIF (== != > >= < <=)")
age=21
if age>16:
print("You are old enough to drive")
else:
print("You are not old enough to drive")
if age>=21:
print("You are old enough to drive a tractor trailer")
elif age>=16:
print("You are old enoguh to drive a car")
else:
print("You are not old enough to drive")
#LOGICAL OPERATORS (AND OR NOT)
age=30
if ((age>=1) and (age<=18)):
print("You get a birthday")
elif (age==21)or(age>=65):
print("You get a birthday")
elif not(age==30):
print("You don't get a birthday")
else:
print("You get a birthday party yeah")
print("\n"*5)
#LOOPS
print("LOOPS!!!")
print('\n')
print("FOR LOOPS!!!")
for x in range(0,10):
print(x,' ',end="")
print('\n')
grocery_list=['Juice','Tomatoes','Potatoes','Bananas']
for y in grocery_list:
print(y)
for x in [2,4,6,8,10]:
print(x)
print('\n')
num_list=[[1,2,3],[10,20,30],[100,200,300]]
for x in range(0,3):
for y in range(0,3):
print(num_list[x][y])
print('\n'*2)
print("WHILE LOOPS!!!")
random_num= random.randrange(0,16) #Generates a random number between 0 to 99
while(random_num!=15):
print(random_num)
random_num=random.randrange(0,16)
print('\n')
i=0;
while(i<=20):
if(i==0):
i += 1
continue
elif(i%2==0):
print(i)
elif(i==9):
break
else:
i+=1 #i=i+1
continue
i+=1
print('\n')
print('Finding prime numbers')
#FINDING PRIME NUMBERS BETWEEN 0 AND 20
max_num = 20
primes = [2] # start with 2
test_num = 3 # which means testing starts with 3
while test_num < max_num:
i = 0
# It's only necessary to check with the primes smaller than the square
# root of the test_num
while primes[i] <= math.sqrt(test_num):
# using modulo to figure out if test_num is prime or not
if (test_num % primes[i]) == 0:
test_num += 1
break
else:
i += 1
else:
primes.append(test_num)
test_num += 1
print(primes)
print('\n'*5)
#FUNCTIONS
print("FUNCTIONS")
def sum(fNum,lNum):
sumNum = fNum+lNum
return sumNum
sum_of_two = sum(1,2)
print(sum_of_two)
print("The sum of 1 and 2 is: ",sum(1,2))
print('\n'*5)
#TAKE INPUT FROM USER
print("TAKE INPUT FROM USER!!!")
print("What is your name: ")
#name = sys.stdin.readline()
#print("Hello ",name)
print('\n'*5)
#STRINGS
print("STRINGS!!!")
long_string="i'll catch you if you fall - The Floor"
print(long_string[0:4])
print(long_string[-5:])
print(long_string[:-5])
print(long_string[:4] + " be there")
print("%c is my %s letter and my number %d number is %.5f" %
('X','favorite',1,.14))
print(long_string.capitalize()) #Capitalizes first letter of the string
print(long_string.find("Floor"))
print(long_string.isalpha())
print(long_string.isalnum())
print(len(long_string))
print(long_string.replace("Floor","Ground"))
print(long_string.strip()) #Strip white space
quote_list = long_string.split(" ")
print(quote_list)
print('\n'*5)
#FILE I/0
print("FILE I/0!!!")
test_file = open("test.txt","wb") #Opens the files in write mode
print(test_file.mode)
print(test_file.name)
test_file.write(bytes("Write me to the file\n", 'UTF-8')) #Writes to the file
test_file.close()
test_file = open("test.txt","r+")
text_in_file = test_file.read()
print(text_in_file)
os.remove("test.txt") #Deletes the file
print('\n'*5)
#OBJECTS
print("OBJECTS!!!")
class Animal:
__name = None #or __name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self,name,height,weight,sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def set_height(self, height):
self.__height = height
def set_weight(self, weight):
self.__weight = weight
def set_sound(self, sound):
self.__sound = sound
def get_name(self):
return self.__name
def get_height(self):
return str(self.__height)
def get_weight(self):
return str(self.__weight)
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal")
def toString(self):
return "{} is {} cm tall and {} kilograms and say {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
cat = Animal('Whiskers',33,10,'Meow')
print(cat.toString())
It is an indentation problem. You are creating the instance of the Aninal class with in the class. Unindent last two lines out side of class.

Python Credit Card Validation

I'm a beginner Python learner and I'm currently working on Luhn Algorithm to check credit card validation. I wrote most of the code, but I'm stuck with 2 errors I get 1st one is num is referenced before assignment. 2nd one I'm getting is object of type '_io.TextIOWrapper' has no len(). Further help/ guidance will be greatly appreciated.
These are the steps for Luhn Algorithm (Mod10 Check)
Double every second digit from right to left. If this “doubling” results in a two-digit number, add the two-digit
number to get a single digit.
Now add all single digit numbers from step 1.
Add all digits in the odd places from right to left in the credit card number.
Sum the results from steps 2 & 3.
If the result from step 4 is divisible by 10, the card number is valid; otherwise, it is invalid.
Here's what my output is supposed to be
Card Number Valid / Invalid
--------------------------------------
3710293 Invalid
5190990281925290 Invalid
3716820019271998 Valid
37168200192719989 Invalid
8102966371298364 Invalid
6823119834248189 Valid
And here is the code.
def checkSecondDigits(num):
length = len(num)
sum = 0
for i in range(length-2,-1,-2):
number = eval(num[i])
number = number * 2
if number > 9:
strNumber = str(number)
number = eval(strNumber[0]) + eval(strNumber[1])
sum += number
return sum
def odd_digits(num):
length = len(num)
sumOdd = 0
for i in range(length-1,-1,-2):
num += eval(num[i])
return sumOdd
def c_length(num):
length = len(num)
if num >= 13 and num <= 16:
if num [0] == "4" or num [0] == "5" or num [0] == "6" or (num [0] == "3" and num [1] == "7"):
return True
else:
return False
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
main()
You just forgot to initialize num
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
# initialize num here
num = cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = cc = (infile.readline().strip())
First, maybe you should remove the extra characters:
def format_card(card_num):
"""
Formats card numbers to remove any spaces, unnecessary characters, etc
Input: Card number, integer or string
Output: Correctly formatted card number, string
"""
import re
card_num = str(card_num)
# Regex to remove any nondigit characters
return re.sub(r"\D", "", card_num)
After check if credit card is valid using the Luhn algorithm:
def validate_card(formated_card_num):
"""
Input: Card number, integer or string
Output: Valid?, boolean
"""
double = 0
total = 0
digits = str(card_num)
for i in range(len(digits) - 1, -1, -1):
for c in str((double + 1) * int(digits[i])):
total += int(c)
double = (double + 1) % 2
return (total % 10) == 0
This is a very simpler version of code it is based on lunh's algorithm
def validator(n):
validatelist=[]
for i in n:
validatelist.append(int(i))
for i in range(0,len(n),2):
validatelist[i] = validatelist[i]*2
if validatelist[i] >= 10:
validatelist[i] = validatelist[i]//10 + validatelist[i]%10
if sum(validatelist)%10 == 0:
print('This a valid credit card')
else:
print('This is not valid credit card')
def cardnumber():
result=''
while True:
try:
result = input('Please enter the 16 digit credit card number : ')
if not (len(result) == 16) or not type(int(result) == int) :
raise Exception
except Exception:
print('That is not a proper credit card number. \nMake sure you are entering digits not characters and all the 16 digits.')
continue
else:
break
return result
def goagain():
return input('Do you want to check again? (Yes/No) : ').lower()[0] == 'y'
def main():
while True:
result = cardnumber()
validator(result)
if not goagain():
break
if __name__ == '__main__':
main()
Old thread but the answer concerns me... and the real issue wasn't identified.
Actually, the error is that you have used the identifier (num) for the parameter when defining checkSecondDigits as the identifier/name of the argument when calling the function in the mainline. The function should be called in main() by
even = checkSecondDigits(cc) so the value in cc (which is the argument) is passed into num (as the parameter) for use within the function.
The same rookie error is made with odd_digits and cc_length.
This question (and the initially suggested answer) demonstrates a fundamental mis-understanding of passing arguments to parameters...
The suggested 'declaring' of num just hides this error/misunderstanding and also obfuscates the local and global scopes of num (which should only be local) and cc (which is global) so whilst the suggestion works in this case, it works for the wrong reason and is poor style and bad programming.
Further,
num should not appear anywhere in main() as it should be local to (only appear inside of) the functions called...
The last line in this code should be the same as the first, but the last line incorrectly assigns the data to num instead of cc
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
you can use my code for card validation it is 100% dynamic because of the card structure is stored in CSV file, so it is easy to update here is the code on GitHub profile, python file link, code explanation file link and CSV for datafile link
python code:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 20:55:30 2019
#author: Preyash2047#gmail.com
"""
import csv
import numpy as np
#csv file imported and storf in reader
reader = csv.DictReader(open("card_data.csv"))
#input card number
card_number = input("Enter the card No: ")
#global variable declaration
min_digits=0
max_digits=0
card_number_list = list(card_number)
card_number_list_reverse=card_number_list[::-1]
card_number_length=len(card_number_list)
first_digit = int(card_number_list[0])
#global variable for final output
card_provider_list_number = 0
result_found = False
card_number_digits = 0
mit_name=""
#list
start=[]
end=[]
name=[]
c_d=[]
number_length=[]
min_max_digits_list=[]
#append the list from csv
for raw in reader:
start.append(raw['start'])
end.append(raw['end'])
name.append(raw['name'])
c_d.append(raw['c_d'])
number_length.append(raw['number_length'])
#initialize the value of min_digits & max_digits
def min_max_digits():
global min_digits
global max_digits
for i in range(len(start)):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
min_max_digits_list.append(available_length[j])
min_max_digits_array = np.array(min_max_digits_list)
np.unique(min_max_digits_array)
min_digits=int(min(min_max_digits_array))
max_digits=int(max(min_max_digits_array))
#list to int
def list_to_int(noofdigits):
str1 = ""
return int(str1.join(noofdigits))
#card validation
def iin_identifier():
first_six_digit = list_to_int(card_number_list[0:6])
for i in range(len(start)):
if(first_six_digit >= int(start[i]) and first_six_digit <= int(end[i])):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
if(card_number_length == int(available_length[j])):
global card_provider_list_number
card_provider_list_number = i
global card_number_digits
card_number_digits = available_length[j]
global result_found
result_found = True
#Major Industry Identifier (MII) identification
def mit_identifier():
global first_digit
global mit_name
switcher = {
1: "Airlines",
2: "Airlines",
3: "Travel and Entertainment",
4: "Banking and Financial Services",
5: "Banking and Financial Services",
6: "Merchandising and Banking",
7: "Petroleum",
8: "Health care, Telecommunications",
9: "National Assignment"
}
mit_name=switcher.get(first_digit, "MIT Identifier Not Found")
#Luhn Algorithm or modulo-10 Algorithm
def luhn_algorithm():
for i in range(card_number_length):
if(i%2!=0 and i!=0):
card_number_list_reverse[i]=int(card_number_list_reverse[i])*2
#print(str(i)+" "+ str(card_number_list_reverse[i]))
if(len(str(card_number_list_reverse[i]))==2):
even_number_2=list(str(card_number_list_reverse[i]))
card_number_list_reverse[i] = int(even_number_2[0])+int(even_number_2[1])
#print("\tsubsum "+str(i)+" "+str(card_number_list_reverse[i]))
else:
card_number_list_reverse[i]=int(card_number_list_reverse[i])
division_int = int(sum(card_number_list_reverse)/10)
division_float=sum(card_number_list_reverse)/10
if(division_int-division_float==0):
return True
#initial level number length validation
def card_number_validation():
min_max_digits()
if(card_number_length>= min_digits and card_number_length <= max_digits and first_digit != 0):
iin_identifier()
mit_identifier()
if(result_found and luhn_algorithm()):
print("\nEntered Details are Correct\n")
print("\nHere are the some details we know about you card")
print("\nNo: "+card_number)
print("\nIssuing Network: "+name[card_provider_list_number])
print("\nType: "+c_d[card_provider_list_number]+" Card")
print("\nCategory of the entity which issued the Card: "+mit_name)
else:
print("\nCard Number is Invalid\nPlease renter the number!\n")
else:
print("\nCard Number is Invalid\n")
#method called to run program
card_number_validation()
n = input("Enter 16-digit Credit Card Number:")
lst = []
for i in range(16):
lst.append(n[i])
# print(lst)
# list1 = n.split()
# print(list1)
def validate_credit_card():
global lst
if len(lst) == 16:
for i in range(0, len(lst)):
lst[i] = int(lst[i])
# print(lst)
last = lst[15]
first = lst[:15]
# print(first)
# print(last)
first = first[::-1]
# print(first)
for i in range(len(first)):
if i % 2 == 0:
first[i] = first[i] * 2
if first[i] > 9:
first[i] -= 9
sum_all = sum(first)
# print(first)
# print(sum_all)
t1 = sum_all % 10
t2 = t1 + last
if t2 % 10 is 0:
print("Valid Credit Card")
else:
print("Invalid Credit Card!")
else:
print("Credit Card number limit Exceeded!!!!")
exit()
if __name__ == "__main__":
validate_credit_card()

Division by zero error when adding rogue value without any data

Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()

Categories