adding functions to self made calculator - function

Ok so I'm trying to make a working napier numeral calculator. I have gone through most of the steps I need to make it work. I need 2 more steps the function and converting it back to napier numbers. Currently I'm stuck on getting the functions to work. It just seems to skip that step. From what I can tell it should work and not be skipped. Could anyone tell me if I missed a step in the process of making the function.
def main():
response = 'y'
while response == 'y' or response == 'Y':
nap1 = getNapier()
num1 = napToInt(nap1)
print(num1)
nap2 = getNapier()
num2 = napToInt(nap2)
print(num1, num2)
operator = getOperator
result = doMath(num1, num2, operator)
response = input("Try another[y/n]")
def doMath(num1, num2, operator):
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "*":
answer = num1 * num2
else:
if operator == "/":
answer = num1 / num2
return doMath
def getOperator():
op = input("Enter operator: ")
while op not in "+-*/":
op = input("Error!!!! Enter operator: ")
return op
def napToInt(n):
result = 0
for ch in n:
result += 2 ** (ord(ch) - ord('a'))
return result
def getNapier():
nap = input("Enter Napier number: ")
while not nap.isalpha():
nap = input("Error!!! Enter Napier number: ")
return nap
main()
this is the result I get as you can see it gets the napier numbers and just stops
Enter Napier number: asdf
262185
Enter Napier number: adsf
262185 262185
Try another[y/n]

your line operator = getOperator should be operator = getOperator()

Related

How to write Python functions and nested functions?

link to assignment**
This is what I have so far but I cant figure out the rest. I am having a hard time solving the rest of the problem. Like calling sum variables from other functions. If anyone could lend a hand I would appreciate it, thank you.
#hello function
def hello():
print("***************************************")
print("*** WELCOME TO THE MAGIC PROGRAM *****")
print("***************************************")
#get_highest function
def get_highest():
first_num = int(input("\nEnter first number: "))
second_num = int(input("Enter second number: "))
largest_num = 0
if first_num > 0 and second_num > 0 and first_num >= second_num:
print("\nThe largest number is: ", first_num)
first_num = largest_num
elif second_num > 0 and first_num > 0 and second_num >= first_num:
print("\nThe largest number is:", second_num)
second_num = largest_num
else:
print("\nERROR: Both numbers must be greater than 0!")
print("Try again.")
get_highest()
return largest_num
#odd_or_even function
def odd_or_even(largest_num):
largest_num = get_highest()
if (largest_num % 2 == 0):
print(largest_num, " is an EVEN NUMBER!!")
else:
print(largest_num, " is an ODD NUMBER!!")
#print_magic function
def print_magic(largest_num):
largest_num = get_highest()
total = 0
for x in range(1, largest_num):
total = total + x
hello()
get_highest()
odd_or_even()

Why isn't my return statement working?

I have a function that converts a decimal value to binary. I understand I have the logic correct as I can get it to work outside of a function.
def decimaltobinary(value):
invertedbinary = []
value = int(value)
while value >= 1:
value = (value / 2)
invertedbinary.append(value)
value = int(value)
for n, i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n] = 0
else:
invertedbinary[n] = 1
invertedbinary.reverse()
value = ''.join(str(e) for e in invertedbinary)
return value
decimaltobinary(firstvalue)
print (firstvalue)
decimaltobinary(secondvalue)
print (secondvalue)
Let's say firstvalue = 5 and secondvalue = 10. The values returned each time the function is executed should be 101 and 1010 respectively. However, the values I get printed are the starting values of five and ten. Why is this happening?
The code works as expected, but you didn't assign the returned value:
>>> firstvalue = decimaltobinary(5)
>>> firstvalue
'101'
Note that there are easier ways to accomplish your goal:
>>> str(bin(5))[2:]
'101'
>>> "{0:b}".format(10)
'1010'

Sequence function error?

I'm getting an error on line 3 "TypeError: 'int' object is not iterable," and its been bothering me. Any advice/fixes appreciated.
Example test: collatz_counts(4) → 3 # 4 -> 2 -> 1 (3 steps)
Code I have:
def collatz_counts(x):
num = 0
for i in (x):
if i == 1:
num += 1
return num
elif i % 2 == 0:
num(i) / 2
num += 1
num.append(i)
else:
num = (i*2) + 3
num += 1
num.append(i)
return num
This can be solved recursively:
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which lends itself to be memoized if you are going to be calling for a range of numbers, e.g. in Py3
import functools as ft
#ft.lru_cache(maxsize=None)
def collatz_length(n):
if n == 1:
return 1
return 1 + collatz_length(3*n+1 if n%2 else n//2)
Which will run through the first million collatz sequences in about 2.31s vs about 28.6s for the iterative solution.
Use a while loop. Just modify x in place until you get to 1 and keep track of the number of steps each time you run a cycle.
def collatz_counts(x):
steps = 0
while x != 1:
if x % 2:
x = x * 3 + 1
else:
x = x // 2
steps += 1
return steps

python function will not return value that is based on condition

I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def printStock(stockList, stockPrice, p):
for i in range(len(stockPrice)):
if stockPrice[i] > p:
p = stockList[i]
print("The stocks with a higher value are:", p)
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
searchStock(stockList, stockPrice, s)
p = s
printStock(stockList, stockPrice, p)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I also get an error saying "unorderable types int() > str()" regarding line 3. Basically the function printStock takes the three parameters and once the function is done it should print the names of the stocks higher than the value 'p'. The value of 'p' is the same as the value I get after calling searchStock function, but I cant seem to get it to work. Can someone please help me?
s is being returned from the function, but the return value is not being assigned to any variable on the outer scope.
Just replace
searchStock(stockList, stockPrice, s)
with
s=searchStock(stockList, stockPrice, s)
And everything should work as expected

Support with Logic Gate Simulation program in Python

I'm trying to create a logic gate simulation program in python so that a user can choose the type of logic gate they want to simulate. Once chosen, they can then enter the inputs and the program should return the value of the output from the chosen logic gate to the user.
This is what I have so far:
print ("Logic Gate Simulation")
def AND (a,b):
if a == 1 and b == 1:
return 1
else:
return 0
def NAND (a,b):
if a == 1 and b == 1:
return 0
else:
return 1
def OR(a,b):
if a == 1:
return 1
elif b == 1:
return 1
else:
return 0
def NOR (a,b):
if a != b:
return 1
else:
return 1
def Main():
question = input("what type of gate do you want to simulate - OR, AND or NAND? ")
if question == 'AND':
a = input("enter value for input 1")
b = input("enter value for input 2")
x= AND(a,b)
print (x)
else:
print ("")
Main()
When I run the program and enter AND, inputs 1 and 1 it still returns 0 and I cant see why.
this works:
def AND (a,b):
a=int(a)
b=int(b)
if a == 1 and b == 1:
return 1
else:
return 0
you have to tell python that a and b are integers - (there are better ways of doing that than the method shown)
This is my version of the code (I had to this for homework for AS Level, this may help you!) :
print("Logic Gate Calculator")
def AND(a, b): # AND Gate
a = int(a)
b = int(b)
if a == 1 and b == 1: # AND Gate logic
return 1
else:
return 0
def NAND(a, b): # NAND Gate
a = int(a)
b = int(b)
if a == 1 and b == 1: # NAND Gate logic
return 0
elif a == 1 and b == 0:
return 0
elif a == 0 and b == 1:
return 0
else:
return 1
def OR(a, b): # OR Gate
a = int(a)
b = int(b)
if a == 1: # OR Gate Logic
return 1
elif b == 1:
return 1
else:
return 0
def NOR(a, b): # NOR Gate
a = int(a)
b = int(b)
if a == 1 and b == 0: # NOR Gate Logic
return 1
elif a == 0 and b == 1:
return 1
elif a == 0 and b == 0:
return 1
else:
return 0
def XOR(a, b): # XOR Gate
a = int(a)
b = int(b)
if a == 1 and b == 0: # XOR Gate Logic
return 1
elif a == 1 and b == 1:
return 1
else:
return 0
def main(): # The main program
run = True
while run: # While loop
question = input("What type of gate do you want to use OR, AND, NOR, or NAND or (Q)uit") # Logic Gate chooser
if question == "AND" or question == "and" or question == "And": # If the user selects AND
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = AND(a, b) # Calling the AND Function
print("The output will be:", x) # Output result
elif question == "OR" or question == "or" or question == "Or": # If the user selects OR
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = OR(a, b) # Calling the OR Function
print("The output will be:", x) # Output result
elif question == "NOR" or question == "nor" or question == "Nor": # If the user selects NOR
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = NOR(a, b) # Calling the NOR function
print("The output will be:", x) # Output result
elif question == "NAND" or question == "nand" or question == "Nand": # If the user selects NAND
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = NAND(a, b) # Calling the NAND function
print("The output will be:", x) # Output result
elif question == "XOR" or question == "xor" or question == "Xor": # If the user selects XOR
a = input("Enter value for input 1 (1 or 0):") # Getting the Logic Gate's 1st input
b = input("Enter value for input 2 (1 or 0):") # Getting the Logic Gate's 2nd input
x = XOR(a, b) # Calling the XOR function
print("The output will be:", x) # Output result
elif question == "Q" or question == "q": # Quiting the program
run = False
else:
print("Please enter one of the shown logic gates") # Error handling
main()
a=True
b=True
output=a and b
print (output)
a=True
b=False
output=a and b
print (output)
Please try this
It works. Use
if a == 1:
if b == 1:
return 1
else
return 0