call function to check if input is divisible by 7 - python

A programme that check if the user input number is divisible by 7. No error until I run and enter the number, then I receive a number of errors. where is the mistake, please?
def inputdata():
userinput=float(input("Enter number:"))
return userinput
def processdata (userinput):
reminder=userinput % 7
if reminder==0:
result=True
return result
else:
result=False
return result
def outputdata(result):
if result==True:
answer=(print("It is dividable by 7"))
return answer
if result==False:
answer=(print("It is not dividable by 7"))
return answer
def main():
inputdata()
processdata(inputdata)
outputdata(processdata)

I have edited the main part.
There were some problems with the main()
def inputdata():
userinput=float(input("Enter number:"))
return userinput
def processdata (userinput):
reminder=userinput % 7
if reminder==0:
result=True
return result
else:
result=False
return result
def outputdata(result):
if result==True:
answer=(print("It is dividable by 7"))
return answer
if result==False:
answer=(print("It is not dividable by 7"))
return answer
def main():
inp = inputdata() # <---------
pr_data = processdata(inp) # <-------------
outputdata(pr_data)
Enter number:21
It is dividable by 7
Enter number:2
It is not dividable by 7
One liner Solution:
g = lambda x: "It is not dividable by 7" if x%7 else "It is dividable by 7"
g(int(input("Enter Number: ")))
Enter Number: 12
It is not dividable by 7

Try
def divisible(x):
return x % 7 == 0
userinput = int(input())
if divisible(userinput):
print('Case true')
else:
print('Case false')
Note that answer=(print("It is dividable by 7")) is not valid in python since print returns a None value

I don't think you are passing parameters correctly in main(). You have:
def main():
inputdata()
processdata(inputdata)
outputdata(processdata)
but (crudely) what might work is
def main():
outputdata(processdata(inputdata()))

I think your program is a bit to complicated in terms of the number of functions your using. Also your input wasn't converted into a integer in order to perform the calculation:
def trydivision(promt):
"""Test if what is given from the user is divisible by 7"""
try:
value = int(promt) % 7
if value == 0:
print("Yes, " + str(promt) + " is divisible by 7.")
print("The result is " + str(value))
else:
print("The number " + str(promt) + " is not divisible by 7.")
except ValueError:
print("Please type an integer and not a string!")
promt = input("Enter Number: ")
trydivision(promt)

Related

how to get the sum of all the elements in here?

def isempty(qu):
if qu==[]:
return True
else:
return False
def push(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1
def pop(qu):
if isempty(qu):
return "underflow"
else:
item=qu.pop()[0]
if len(qu)==0:
front=rear=0
return item
def peek(qu):
if isempty(qu):
return "underflow"
else:
front=0
return qu[front]
def display(qu):
if isempty(qu):
print("Queue Empty")
else:
front=0
rear=len(qu)-1
print(qu[front],"<--- front")
for a in range(1,rear):
print(qu[a])
print(qu[rear],"<--- rear")
def summation():
def sum_arr(arr,size):
if (size == 0):
return 0
else:
return arr[size-1] + sum_arr(arr,size-1)
n=int(input("Enter number of elements in the queue for addition="))
queue=[]
for i in range(0,n):
queue.append(item)
print("The list is:")
print(queue)
print("sum of items :")
b=sum_arr(queue,n)
print(b)
queue=[]
for i in range(0,4):
print("----Queue Operations----")
print("1.Push/Enqueue")
print("2.Pop/Dequeue")
print("3.Peek")
print("4.Display Queue")
print("5.Exit")
print("6.Summation")
ch=int(input("Enter your choice="))
if ch==1:
item=int(input("Enter element="))
push(queue,item)
elif ch==2:
item=pop(queue)
if item=="underflow":
print("Queue Empty")
else :
print("Popped item=",item)
elif ch==3:
item=peek(queue)
if item=="underflow":
print("Queue Empty")
else:
print("Front most=",item)
elif ch==4:
display(queue)
elif ch==5:
break
elif ch==6:
summation()
else:
print("Invalid Choice")
this is the entire code which we are using here....
this actually for the implementation of queues using lists
it is compulsory to use queues method only here
Enter element=4
Enter element=5
Enter element=6
Enter the number of elements in the queue for addition=3
The list is:
[6, 6, 6]
the sum of items :
18
here the error is that the elements given are 4,5,6 but only the last element '6' is used for finding the sum thrice...
i hope i answered all the queries asked in the comments.....
any ideas with a little explanation are highly appreciated....
Zen of Python: Simple is better than complex
No matter what custom function you build, it will never be faster than a builtin.
l = [6,6,6]
total = sum(l)
print('The list is: {}'.format(l)
print('the sum of items : {}'.format(total))
If you must still need a custom function
def arr_sum(arr):
holder = 0
if len(arr) == 0:
return 0
else:
holder = [holder + i for i in arr if type(i) == int]
return holder

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())

How to check whether a number is prime or not and ask the user again if it's not prime without exiting the program?

I'm trying to check whether a number is prime or not as a part of Diffie Hellman algorithm and if it's not a prime number ask the user again to input another number without exiting the program.
Here's my code:
def prime(p):
for i in range(2,p):
if (p % i) == 0:
return(False)
break
else:
return(True)
def primRoots(p):
roots = []
required_set = set(num for num in range (1, p))
for g in range(1, p):
actual_set = set(pow(g, powers) % p for powers in range (1, p))
if required_set == actual_set:
roots.append(g)
return roots
p=int(input("enter any prime no:"))
check=prime(p)
if(check==True):
primitive_roots = primRoots(p)
g=primitive_roots[0]
print(g)
x=int(input("Alice chooses value of X as:"))
y=int(input("Bob chooses value of y as:"))
r1=(g**x) % p
r2=(g**y) % p
print("value of r1 is",r1)
print("value of r2 is",r2)
a=x*y
k1=(r2**x) % p
print("k1 is",k1)
k2=(r1**y)% p
print("k2 is",k2)
k=(g**a)%p
print("shared key is",k)
else:
print("It is not a prime num,enter again")
prime(p)
user_input = int(input("Enter an integer ! "))
def prime(n):
isPrime = True
for num in range(2, int(n/2)):
if n % num == 0:
isPrime = False
return isPrime
while (prime(user_input)== False):
user_input = int(input("==> Your input is incorrect, please enter an other integer !"))
print("{} is prime ".format(user_input))

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()

Python Palindrome

So my task is to see and check a positive integer if its a palindrome. I've done everything correctly but need help on the final piece. And that the task of generating a new a palindrome from the one given given by the user. Am i on the right track with the while loop or should i use something else? So the result is if you put 192 it would give back Generating a palindrome....
483
867
1635
6996
"""Checks if the given, positive number, is in fact a palindrome"""
def palindrome(N):
x = list(str(N))
if (x[:] == x[::-1]):
return True
else: return False
"""Reverses the given positive integer"""
def reverse_int(N):
r = str(N)
x = r[::-1]
return int(x)
def palindrome_generator():
recieve = int(input("Enter a positive integer. "))
if (palindrome(recieve) == True):
print(recieve, " is a palindrome!")
else:
print("Generating a palindrome...")
while palindrome(recieve) == False:
reverse_int(recieve) + recieve
If I understand your task correctly, the following should do the trick:
def reverse(num):
return num[::-1]
def is_pal(num):
return num == reverse(num)
inp = input("Enter a positive number:")
if is_pal(inp):
print("{} is a palindrome".format(inp))
else:
print("Generating...")
while not is_pal(inp):
inp = str(int(inp) + int(reverse(inp)))
print(inp)
The variable inp is always a string and only converted to int for the arithmetic.
I've been using this solution for many years now to check for palindromes of numbers and text strings.
def is_palindrome(s):
s = ''.join(e for e in str(s).replace(' ','').lower() if e.isalnum())
_len = len(s)
if _len % 2 == 0:
if s[:int(_len/2)] == s[int(_len/2):][::-1]:
return True
else:
if s[int(_len/2+1):][::-1] == s[:int(_len/2)]:
return True
return False
This one is using Complement bitwise and Logical AND and OR operators
_input = 'Abba' # _input = 1221
def isPalindrome(_):
in_str = str(_).casefold() # Convert number to string + case insensitive
for _ in range(int(len(in_str) / 2)): # Loop from 0 till halfway
if in_str[_] != in_str[~_]:
return False
return True
print(_input, isPalindrome(_input) and ' is palindrome' or ' is not palindrome')
Abba is palindrome

Categories