adding python loop best practices - python

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

Related

Why does my if-statement always evaluate to True? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I have the following code:
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while 1 > 0:
function = input("Enter the type of function you want to do:\n")
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print('Your answer is ' + str(total))
continue
elif function == 'subtraction' or 'Subtraction' or 'SUBTRACTION' or 'sUBTRACTION' or '-' or 'subtract':
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print('Your answer is' + str(total))
continue
elif function == 'multiplication' or 'multiply' or '*' or 'Multiply' or 'MULTIPLY':
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print('Your answer is' + str(total))
continue
elif function == 'divide' or 'DIVIDE' or '/':
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print('Your answer is' + str(total))
continue
elif function == 'stop' or 'STOP' or 'Stop' or 'sTOP':
break
else:
print('Can\'t understant what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')
I have a infinite loop which asks you to enter a function. And I have if-elif-else statements to see, which function the user inputed. I want the function the user inputed to be the one that gets activated, but for a reason it always does addition. Any help is appreciated!
In python a string can get evaluated as a boolean. An empty string returns False and a non-empty one returns True.
Example:
print(bool("A non empty string"))
Output:
True
Example:
print(bool("")) # <---- Empty String
Output:
False
In the if statements you have, you wrote:
if function == 'addition' or 'Addition' or 'ADDITION' or 'aDDITION' or '+' or 'add':
...
Python first checks if function equals "addition" then if not it continues to the next condition and that is simply "Addition". Since there is no comparison or anything like that it simply gets evaluated to True and, thus the if statement becomes True, because you used or (So only one of the conditions have to be True.)
To fix this you have to add function == ... to your every check as such:
if function == 'addition' or function == 'Addition' or function == 'ADDITION' or function == 'aDDITION' or function == '+' or function == 'add':
...
To make this more readable you can use the in keyword and check if function is in the tuple as such:
if function in ('addition', 'Addition', 'ADDITION', 'aDDITION', '+', 'add'):
...
And to make this even better you can upper case the function and check if function is ADDITION only not every combination like "Addition", "aDdition"...
This is how you do it:
if function.upper() in ('ADDITION', '+', 'ADD'):
...
And here is the full working code (I also did a little bit of cleaning):
print('''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer\n''')
while True:
function = input("Enter the type of function you want to do:\n").upper()
if function in ('ADDITION', '+', 'ADD'):
num1 = int(input("Enter your number:\n"))
num2 = int(input("Enter your number:\n"))
total = num1 + num2
print(f'Your answer is {total}')
continue
elif function in ('SUBTRACTION', '-', 'SUBTRACT'):
num1 = int(input("Enter the number you want to subtract from:\n"))
num2 = int(input(f"Enter the number you want to subtract from {num1}:\n"))
total = num1 - num2
print(f'Your answer is {total}')
continue
elif function in ('MULTIPLICATION', '*', 'MULTIPLY'):
num1 = int(input("Enter the number you want to multiply:\n"))
num2 = int(input(f"Enter the number you want to multiply {num1} wit:\n"))
total = num1 * num2
print(f'Your answer is {total}')
continue
elif function in ('DIVISION', '/', 'DIVIDE'):
num1 = int(input("Enter the number you want to divide:\n"))
num2 = int(input(f"Enter the number you want to divisor for {num1}:\n"))
total = num1 / num2
print(f'Your answer is {total}')
continue
elif function == 'STOP':
break
else:
print('Can\'t understand what you want to do please write your choice in the format below\n' + '''How to use this calculator:
1 - Enter the type of function you want it to do like addition(+), subtraction(-), etc.
2 - Enter your number and it'll keep asking you until you say it to stop
3 - Voila! you have your answer''')

how do i turn an input into a variable so i can add or use in equations in python

if I have a code like this?
num1= input (" number goes here")
num2= input ("number goes here")
how can I make a simple equation work such as.
num3=num2+num1
print ("num3")
and when I do that it outputs
num2num3
I have tried things such as
int=(num1)
You need to convert num1 and num2 into int type because input gives you a str type.
num1 = int(input(" number goes here"))
num2 = int(input("number goes here"))
num3 = num1 + num2
print(num3)

Where did i wrong?Take 2 integers, pass function and calcualte sum of cubes

The code is:Take 2 numbers from the user. Pass these two numbers to a function mathExp(). This function will calculate the sum of the cubes of the two numbers.
Return and print this value.
Function Structure:
int mathExp(int,int)
My code is:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(num1,num2):
print(num**3 + num**2, mathExp(num1,num2))
There is a lot wrong with this code:
First, you are calling the mathExp function IN itself. Thats recursion and I dont think that you want to do this.
Second, the parameters of the mathExp function are called num1 and num2. But in the function you use just num which doesnt exist.
So what you probably want to do is this:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(n1,n2):
return n1**3 + n2**3
print(mathExp(num1, num2))
Your mathExp function was wrong. Try this instead:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(num1,num2):
ans = num1**3 + num2**3
return ans
cubes = mathExp(num1, num2)
print(cubes)
Try this code:
# take two number as input from the user
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
# define the function which calculate the sum of cubes of the input numbers
def mathExp(num1,num2):
result = num1**3 + num2**3
return result
# call the function with user input and print the result
print(mathExp(num1, num2))
Example:
write a number: 4
write a number: 7
407

How can i reverse the output in my binary adder?

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]

Python calculator concatenates instead of preforming operations

I'm new to Python and I'm attempting to program a calculator. The problem is I can't find a way to make the variables num1 and num2 do the operation I have listed for them. All they do is concatenate the two numbers instead of performing the operation, any suggestions? Thanks.
letter = ()
class Calc():
print raw_input("What operation do you want to do?\n\tA) Addition\n\tB) Subtraction\n\ ")
num1 = raw_input("Please enter your first number: ")
num2 = raw_input("Please enter your second number: ")
if letter == 'A' or 'a':
print "The sum of", num1, "plus", num2, "equals"
print num1 + num2
elif letter == 'B' or 'b':
print "The difference of", num1, "minus", num2, "equals"
print num1 - num2
raw_input returns a string, so your two inputs are concatenated. You need to convert that input to a number before using it with numeric operators.
num1 = int(raw_input("Please enter your first number: "))
You can use either float or int to convert the input string to a number.
You also need to change
if letter == 'A' or 'a':
to
if letter == 'A' or letter == 'a':
You are using
raw_input()
which converts the input to strings.
If you want to add them together, you would like to use
num1 = float(num1)
before adding.
This is because you are doing string operations. raw_input returns a string, so you must manually convert it to an int or float using: float() or int().
Do this:
print int(num1) + int(num2) in order to print the numbers in their addition form.
I think this will do what you ask:
letter = raw_input("What operation do you want to do?\n\tA)
Addition\n\tB)Subtraction\n")
num1 = input("Please enter your first number: ")
num2 = input("Please enter your second number: ")
if letter == 'A' or 'a':
print "The sum of", num1, "plus", num2, "equals"
print num1 + num2
elif letter == 'B' or 'b':
print "The difference of", num1, "minus", num2, "equals"
print num1 - num2

Categories