How can i reverse the output in my binary adder? - python

So im trying to create a simple program that will add two binary strings together, im almost done but the output it creates is reversed, how would i implement a way to reverse it in my code? I want to remove the "ob" at the start of the output as well.
repeat = True
while repeat==True:
num1 = input("what number would you like to add ")
if num1.isdigit():
a= int(num1)
elif not num1.isdigit():
continue
a = int(num1, 2)
num2 = input("what number would you like to add to it ")
if num2.isdigit():
b= int(num2)
elif not num2.isdigit():
continue
b = int(num2, 2)
ans = bin(a+b)[2:]
print("Your addition of numbers, in binary is " + ans)
choice=input("Would you like to start again, y/n")
if choice== "y":
repeat=True
else:
print("Its not like i wanted you here or anything baka")
repeat=False

You could just reverse the string using:
ans = ans[::-1]

Related

I tried making a python calculator (Text based) and I am new to python. So I don't know how do to add two strings.(Or turn strings into integers.) [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 21 days ago.
Don't know how to convert strings to integers.
I tried putting int around it and it still didn't work frstn = int(input("Type first number: "))
import math
# frstn means first number
# scndn means second number
op = input("What operator do you want? + - / *: ")
if op == "+":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn + scndn)
elif op == "-":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn - scndn)
elif op == "/":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn / scndn)
elif op == "*":
frstn = input("Type first number: ")
scndn = input("Type second number: ")
print(frstn * scndn)
else:
print("Invalid operator, reboot calculator.")
You are looking to cast the user input into an int.
firstn = int(input("Type the first number: "))
This will take the user input and turn it into a number that you can now use it for arithmetic operations.
You could probably move your input statements outside the if statements. If you would like to keep the same style then you could think of something along the lines of
firstn = int(input("Type the first number: "))
op = input("What operator do you want? + - / *: ")
secondn = int(input("Type the second number: "))
if op == "+":
print(firstn + secondn)
....

How to restart a programm if input is invalid python

first project beginner here! I just finished my first project, a somewhat working calculator i know it is not that great but as i said beginner. I would like to limit the options for number = input meaning if you write anything else than add,substract,divide or multiply you receive an error like " please try again" and afterwards the programm is restarted
Help very much appreciated Thank you.
list = ("add", "substract", "divide" , "multiply" )
number = input("do you want to add substract divide or multiply? ")
if number in list:
print("ok")
else:
print("try again")
number_one = float(input("enter your first number "))
number_two = float(input("enter your second number "))
if number == "add":
solution_one = number_one + number_two
print(solution_one)
if number == "substract":
solution_two = number_one - number_two
print(solution_two)
if number == "divide":
solution_three = number_one / number_two
print(solution_three)
if number == "multiply":
solution_four = number_one * number_two
print(solution_four)
i could only find solutions regarding while loops but i did not know how to use them in this case as these weren't strings but integers.
The fact that you're prompting for a string doesn't change the way the while loop works. Run your code in a loop and break when it's time for the loop to end.
while True:
number = input("do you want to add substract divide or multiply? ")
if number in ("add", "substract", "divide" , "multiply" ):
print("ok")
break
print("try again")
Note that it's considered bad practice to give a variable a name like list (or any other built-in name) since it can lead to very confusing bugs when you try to reference the built-in name later!
You could consider using the operator module.
Build a dictionary that maps the user's selected operation with the relevant function.
import operator
OMAP = {
'add': operator.add,
'subtract': operator.sub,
'divide': operator.truediv,
'multiply': operator.mul
}
while (op := input('Do you want to add, subtract, multiply, divide or end? ')) != 'end':
try:
if (func := OMAP.get(op)):
x = float(input('Enter your first number: '))
y = float(input('Enter your second number: '))
print(func(x, y))
else:
raise ValueError(f'"{op}" is not a valid choice')
except ValueError as e:
print(e)

adding python loop best practices

I am new to python and trying to learn the best way to learn to code. I am practicing with some simple code that asks for 2 numbers and multiples them and I want to add a a function to ask if you are done or if you want to multiply some more numbers. Below is the code I started with. I want to know what is the best way to have it loop back to asking for 2 more numbers with a yes or no question?
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
You can set a reminder like when the user is finish then make you can make the reminder is False to make it finish or take a input and check if user want to exit then just simply break the loop.
# set reminder for while loop
done = False
while not done:
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
ask = input('Do you want to try again y/n: ')
if ask == 'n':
done = True # set the reminder is true or break the loop
# break
While loop is the most used one:
repeat = 'yes'
while repeat.lower() == 'yes':
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
print('If you want to continue type yes or no')
repeat = input()
You can do that by wrapping the whole code in a while True loop with a break statement to exit. Essentially, we will want to repeat the process forever, until the user types n or N. The check condition can be refined as desired.
while True:
# Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
# Convert input to interger
num1 = int(num1)
num2 = int(num2)
# Multiply the numbers
results = num1 * num2
# Print the results
print("Your answer is: " + str(results))
# Ask to continue or not
res = input("\nWould you like to continue? (y/n) ").strip()
if res.lower() == 'n':
break
Just simple use while loop and declare a variable named choice and ask the user to enter his choice.
while(True):
choice = input("Would you like to continue? (y/n) ")
if(choice.lower=='y'):
num1 = int(input("\nEnter the first number you want to multiply: "))
num2 = int(input("\nEnter the second number you want to multiply: "))
results = num1 * num2
print("Your answer is: ",results)
else:
break
def termination():
_noexit=str(raw_input())
if _noexit.lower() == 'y':
return True
else:
return False
#Cal the termination condition
while termination:
num1 = input("\nEnter the first number you want to multiply: ")
num2 = input("\nEnter the second number you want to multiply: ")
num1 = int(num1)
num2 = int(num2)
results = num1 * num2
print results
#Checking termination
termination()

If statements printing after a variable is entered

I'm new to programming/coding and I'm using Python in my course. I have been asked to create a calculator that can add, subtract, divide and multiply. I'm trying to get the program to receive the numbers through input, then ask for what to do with it (eg. plus or minus) through a number entered and then give a result. I have the input stages of the code working but when I get to the last part I cant get it to work. This is the code
FirstNumber = "blank1"
SecondNumber = "blank2"
Device = "blank3"
FirstNumber = input("First number?")
SecondNumber = input("Second number?")
Device = input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide.")
if "Device" == 1:
print("FirstNumber"+"SecondNumber")
When it gets the the end it does nothing, help please.
The condition "Device" == 1 will always be False because no string is equal to an integer. You probably want to change it to Device == 1, but this will (likely) still fail because on python3.x, input returns a string. You probably want something like:
Device = int(input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide."))
if Device == 1:
print(FirstNumber + SecondNumber)
Of course, for the same reason, you'll probably also want to convert FirstNumber and SecondNumber into some numeric type ...
ops = {
"+": lambda a,b: a+b,
"-": lambda a,b: a-b,
"*": lambda a,b: a*b,
"/": lambda a,b: a/b
}
a = int(input("Please enter the first number: "))
op = input("Please enter an operator: ")
b = int(input("Please enter the second number: "))
print("{} {} {} == {}".format(a, op, b, ops[op](a,b)))

Python Calculator Using 2 vars, Operators, and Q (Quit)

I am trying to create a simple python calculator for an assignment. The basic idea of it is simple and documented all over online, but I am trying to create one where the user actually inputs the operators. So instead of printing 1: addition, 2: subtraction, etc, the user would select + for addition, - for subtraction, etc. I am also trying to make Q or q quit the program.
Any ideas for how to allow the user to type operators to represent the operation?
Note: I know I still need to define my remainder operation.
import math
loop = 1
choice = 0
while loop == 1:
print("your options are:")
print("+ Addition")
print("- Subtraction")
print("* Multiplication")
print("/ Division")
print("% Remainder")
print("Q Quit")
print("***************************")
choice = str(input("Choose your option: "))
if choice == +:
ad1 = float(input("Add this: "))
ad2 = float(input("to this: "))
print(ad1, "+", ad2, "=", ad1 + ad2)
elif choice == -:
su2 = float(input("Subtract this: "))
su1 = float(input("from this: "))
print(su1, "-", su2, "=", su1 - su2)
elif choice == *:
mu1 = float(input("Multiply this: "))
mu2 = float(input("with this: "))
print(mu1, "*", mu2, "=", mu1 * mu2)
elif choice == /:
di1 = float(input("Divide this: "))
di2 = float(input("by this: "))
print(di1, "/", di2, "=", di1 / di2)
elif choice == Q:
loop = 0
print("Thank-you for using calculator")
First off, you don't need to assign choice to zero
Second, you have your code right, but you need to put quotes around the operators in your if statements like this
if choice == '+':
to show that you are checking for a string
make your loop like this:
while 1: #or while True:
#do stuff
elif choice == 'Q': #qoutes around Q
break #use the `break` keyword to end the while loop
then, you don't need to assign loop at the top of your program
You should try replacing if choice == + by if choice == "+".
What you're getting from the input is actually a string, which means it can contain any character, even one that represents an operator.

Categories