This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm making a calculator on python for a school assignment but the trouble is, my teacher knows nothing. I've made the calculator, but I need to add some code so the user cannot input a number larger than 999, and if they do it creates a loop where the software asks what the users inputs are. Any help?
# Program make a simple calculator
# that can add, subtract, multiply
# and divide using functions
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
I've tried a variety of things but nothing works
P.S. I'm a bit of a novice so go easy
Thanks
while True:
num = int(raw_input('enter an integer <= 999: '))
if num <= 999:
break
print('invalid input, please try again!')
print('you entered: {}'.format(num))
MAX_VALUE = 999
def read_number(message):
n = MAX_VALUE
while (n >= MAX_VALUE):
n = int(raw_input(message))
return n
num1 = read_number("Enter first number:")
num2 = read_number("Enter second number:")
Example run:
Enter first number: 1000
Enter first number: 56
Enter second number: 800
Related
#Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
# imports
import random
# declarations
num1 = (random.randint(0, 10))
num2 = (random.randint(0, 10))
guess = ""
# Now we build the program code:
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")
print("The first number is", num1, "Enter h for higher or l for lower to guess the second number")
guess = input('-->')
if guess == 'h':
if num1 < num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
elif guess == 'l':
if num1 > num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
else:
print("Not an exceptable entry")
I made this and it works but I want to create a loop so the user can play all they want. I am new to this ..any suggestions would be appreciated
After copy paste your code in my IDE I realize you miss the conception for this code.
You should start this with the idea of breaking the loop if right, continue if wrong.
This isn't a good practice but I found a quick way to answer your need without refactoring your code:
Add you entire code (except the import of random module) inside
while True:
And add break control statement after each good answer.
I tested it and it's work but I recommend you to search for similar project to compare with your, it will be a good point for later in your adventure.
Using functions here would be a good idea, I'd recommend putting your main code in a function called 'play' for example and also create a function which prompts the user if he wants to play again.
Then create a while loop which calls your 'play' function, and update the condition of your main loop after each 'play' with the prompt function.
This is how I have done it.
# Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
# imports
import random
# Now we build the program code:
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")
def play():
# declarations
num1 = (random.randint(0, 10))
num2 = (random.randint(0, 10))
print("The first number is", num1, "Enter h for higher or l for lower to guess the second number")
guess = input('-->')
if guess == 'h':
if num1 < num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
elif guess == 'l':
if num1 > num2:
print("you guessed it! the number is:", num2)
else:
print("Nice guess but the number is:", num2)
else:
print("Not an exceptable entry")
def promptAgain():
print("Play again? y/n")
response = input().lower()
if response == 'n':
return False
elif response == 'y':
return True
else:
print("Not an exceptable entry")
return promptAgain()
again = True
while again:
play()
again = promptAgain()
Since you only allow higher or lower input you need to ensure the same number is not randomly selected twice. I.e., if num1 is 8 then num2 should not be able to also be 8 (your current code doesn't prevent this).
Consider utilizing random.sample to achieve this:
"""Daniel Gardner's Higher/Lower Game."""
import random
MIN_RAND_VALUE = 0
MAX_RAND_VALUE = 10
GUESS_PROMPT = '--> '
HIGH_GUESS = 'h'
LOW_GUESS = 'l'
def get_yes_no_input(prompt: str) -> bool:
"""Returns True if the user enters yes."""
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
def higher_or_lower_game_loop() -> None:
num1, num2 = random.sample(range(MIN_RAND_VALUE, MAX_RAND_VALUE + 1), 2)
print('The first number is', num1,
'Enter h for higher or l for lower to guess the second number.')
guess = input(GUESS_PROMPT)
while guess not in {HIGH_GUESS, LOW_GUESS}:
print('Not an exceptable entry, you must enter h or l')
guess = input(GUESS_PROMPT)
if guess == HIGH_GUESS:
if num1 < num2:
print('You guessed it! the number is:', num2)
else:
print('Nice guess but the number is:', num2)
elif guess == LOW_GUESS:
if num1 > num2:
print('You guessed it! the number is:', num2)
else:
print('Nice guess but the number is:', num2)
def main() -> None:
print('Welcome to my high/lower game.',
'You will guess the second number in the game,',
'is it higher or lower than the number presented?')
while True:
higher_or_lower_game_loop()
play_again = get_yes_no_input('Play again? ')
if not play_again:
break
print('Goodbye!')
if __name__ == '__main__':
main()
Example Usage:
Welcome to my high/lower game. You will guess the second number in the game, is it higher or lower than the number presented?
The first number is 8 Enter h for higher or l for lower to guess the second number.
--> l
You guessed it! the number is: 5
Play again? yes
The first number is 10 Enter h for higher or l for lower to guess the second number.
--> l
You guessed it! the number is: 8
Play again? n
Goodbye!
You can utilize recursion and while loop to validate input:
from random import sample
def hilow():
num1, num2 = sample(range(1, 11), 2); # print(num1, num2)
print(f"The first number is {num1} Enter h for higher or l for lower to guess the second number")
while (guess:=input('-->').lower()) not in ('h','l'):print("Not an exceptable entry")
res = guess == 'h' and num1 < num2 or guess == 'l' and num1 > num2
print((f"Nice guess but the number is {num2}",f"you guessed it! the number is {num2}")[res])
while (p:=input("Play again (y/n)?: ").lower()) not in ('y','n'):print("Not an exceptable entry")
p == 'n' or hilow()
print("Welcome to higher or lower, Choose whether or not the number is higher or lower")
hilow()
Output:
Welcome to higher or lower, Choose whether or not the number is higher or lower
The first number is 2 Enter h for higher or l for lower to guess the second number
-->h
you guessed it! the number is 7
Play again (y/n)?: z
Not an exceptable entry
Play again (y/n)?: y
The first number is 2 Enter h for higher or l for lower to guess the second number
-->l
Nice guess but the number is 5
Play again (y/n)?: y
The first number is 3 Enter h for higher or l for lower to guess the second number
-->x
Not an exceptable entry
-->h
you guessed it! the number is 6
Play again (y/n)?: n
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''')
as you can tell by my code, i want to make a basic calculator, you get asked what you want to do first then asked 2 input 2 numbers to be worked out by the code. I am having a problem where the code returns nothing and doesnt even attempt to use the functions it is meant to.
##Simple Calculator program##
print("Welcome to my basic calculator program")
print("In this program you will be asked to input what function you want to do then")
print("select 2 numbers, where the program will then do the mathematic operation on those 2 numbers")
#Class containing the functions and basic caluclation
class calculator_class():
print("Please select a function by entering these :")
print("Addition")
print("Subtraction")
print("Multiplication")
print("Division")
#this is a function which asks the user to choose what operator to choose before choosing their number
def userchoice():
userchoices = str(input())
if userchoices in ["Addition","Subtraction","Multiplication","Division"]:
return(
if userchoices == "Addition":
print(addition())
elif userchoices == "Subtraction":
print(subtraction())
elif userchoices == "multiplication":
print(multiplication())
elif userchoices == "division":
print(division())
else:
print(invalid_choice())
print(userchoice())
#here the user chooses the 2 numbers
print("Please select 2 numbers to calculate")
usernumber1 = int(input("Please input your first number here : "))
usernumber2 = int(input("Please input your second number here : "))
#Functions of which contain addition, subtraction, multiplication and division
def addition():
print("A D D I T I O N")
print("Just calculating...")
print(usernumber1 + usernumber2)
def subtraction():
print("S U B T R A C T I O N")
print("Just calculating...")
print(usernumber1 - usernumber2)
def multipliction():
print("M U L T I P L I C A T I O N ")
print("Just calculating...")
print(usernumber1 * usernumber2)
def division():
print("D I V I S I O N ")
print("Just calculatin...")
print(usernumber1 / usernumber2)
def invalid_choice():
print("You did not pick a valid option, please try again")
You have many wrong approaches in this code.
More easier to type just a one sign (* for example) instead of typing "multiplication"
It is better to apply .lower() for every user input
input in python is always str, so str() in userchoices = str(input()) is redundant
int() for input() may lead to error (int('1.2') # error), so put such code in try/except block
Is this an efficient calculator in Python?
def calculator():
print("\nBasic Calculator.\n")
num_1 = input("Enter your first number: ")
operation = input("Enter your operation: ")
num_2 = input("Enter your second number: ")
if operation == ("+"):
sum = float(num_1) + float(num_2)
print ("The answer is:",(sum))
elif operation == ("-"):
sum = float(num_1) - float(num_2)
print ("The answer is:",(sum))
elif operation == ("*"):
sum = float(num_1) * float(num_2)
print ("The answer is:",(sum))
elif operation == ("/") and num_2 == ("0"):
print ("\nYou cannot divide by zero.")
elif operation == ("/"):
sum = float(num_1) / float(num_2)
print ("The answer is:",(sum))
else:
print("Invalid Operation.")
restart = input("\nDo you want to enter another equation? Yes or No?").lower()
if restart == ("yes"):
calculator()
else:
print ("\nEnding Program.")
quit()
calculator()
You can use eval()
a = 1
b = 2
operation = '/'
print(eval(f'{a} {operation} {b}'))
0.5
Handle shenanigans by users:
a = 1
b = 0
operation = '/'
try:
print(eval(f'{a} {operation} {b}'))
except Exception as exp:
print(exp)
Here is another basic example:
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}
try:
x, sign, y = input("Enter expression separated by whitespace(ex: 2 + 3): ").split()
if sign == '0':
break
else:
print(operations[sign](int(x), int(y)))
except (ValueError, KeyError, ZeroDivisionError):
print("Something went wrong, check your input")
It's decent, but reviews of working code belong on CodeReview.SE, not here.
Call the result variable result instead of sum, that obviously only is meaningful for addition.
As per AlexanderLekontsev's answer, you don't need a huge big if...else ladder that always computes result and prints the output. A dispatch dictionary to (binary or unary) lambda function is better. You could have all the functions be binary, and default arg2=None, that way you can handle unary functions.
You're assuming the user types in valid floats in response to num_1, num_2. But what if they press return? or type pi or e? or 'help' or :-D etc. You should catch the exception ValueError: could not convert string to floatand display the user's invalid input back to them, "expected a number"(/"operator").
You only need num_2 if operation is a binary not a unary operation, but future stuff like sqrt, log, log10, trigonometrics (sin, cos, tan), hyperbolics and their inverses (arc-fns) are all unary operations. Just something to keep in mind for the future. Don't hardwire your parser to one expected input sequence.
Inputting numbers could get more complicated in future. What if you wanted to support both hexadecimal 7e8 and float/general/exponential notation 7e8? You might need multiple try...except clauses. You might add a HEX mode in future. But then you'll need to generalize from num1 to say arg1, and if arg1 == HEX then enable(/toggle) hex mode, and recurse/loop.
Suggest printing print("Invalid Operation: must be +,-,*,/,..."), this actually tells the user which operations are legal. So: % isn't, neither is ^, neither is log, cos, sqrt etc.
So if you implement the above, you can support things like e^x
Supporting parentheses would require recursion.
Try this:
def calculate(num1, num2, operator):
operator = operator.strip()
if operator.strip() in ['+', '-', '*', '/']:
if operator == '/' and eval(num2) == 0:
return None
try:
result = eval(f'float({num1.strip()}) {operator} float({num2.strip()})')
except:
return ""
return result
num1 = '3'
num2 = '5'
operator = '+'
result = calculate(num1, num2, operator)
if result == '':
print('Wrong expression !')
elif result == None:
print('Dive bye zero !')
else:
print(f'The answe is {result} !')
Your code is alright but we can improvise by using eval()
print(" Basic Calculator ")
i = ""
while i != 'exit':
i = input(" Enter the expression to evaluate or type 'exit' to exit : ")
print(eval(i))
Here is a very clean and short calculator script:
num1 = float(input("Enter a number: "))
op = (input("Enter an operation: "))
num2 = float(input("Enter another number: "))
if op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "^":
print(num1 ** num2)
else:
print("error, you did not enter a supported operation")
Also if you were wondering ** means ^ or to the power of.
Try this:
this calculator will take several inputs, and you can choose to clear the values or to delete it before computing the result.
values_collector = [] #empty list for all values
multi = 1
total = 0
index = 0
print('''For addition press the +,
For Subtraction press the -
For division press the /
For Multiplication press the *''')
entries = int(input('Enter the number of the values you want to compute: '))
signs = input('Enter the sign: ')
while index < entries:
my_input = int(input('Enter your values: '))
values_collector.append(my_input)
index +=1
to_remove = input('Do you want to remove any values, enter Y for yes and N for no ').upper()
if to_remove == 'Y':
values_re=[]
x = 0
no_to_remove = int(input('How many variables do you want to remove: '))
while x < no_to_remove:
my_removed = int(input('Enter your values: '))
values_re.append(my_removed)
x +=1
for y in values_re:
values_collector.remove(y)
my_clear = input("Do you want to clear all the values press Y for yes and N for No ").upper()
if my_clear == 'Y':
values_collector.clear()
print('There is no values to compute because its cleared')
elif my_clear == 'N':
if signs == '+':
for x in range(len(values_collector)):
total +=values_collector[x]
elif signs == '-':
for x in range(len(values_collector)):
total -=values_collector[x]
elif signs == '*':
for x in range(len(values_collector)):
multi *=values_collector[x]
total = multi
elif signs == '/':
for x in range(len(values_collector)):
multi /=values_collector[x]
total = multi
print('The computation of all the values {} is {}'.format(values_collector, total))
enter code here
I'm trying to build a calculator that does basic operations of complex numbers. I'm using code for a calculator I found online and I want to be able to take user input as a complex number. Right now the code uses int(input) to get integers to evaluate, but I want the input to be in the form of a complex number with the format complex(x,y) where the user only needs to input x,y for each complex number. I'm new to python, so explanations are encouraged and if it's something that's just not possible, that'd be great to know. Here's the code as it is now:
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice: 1, 2, 3, or 4: ")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Pass your input to the complex type function. This constructor can also be called with a string as argument, and it will attempt to parse it using Python's representation of complex numbers.
Example
my_number = complex(input("Number"))
Note that Python uses "j" as a symbol for the imaginary component; you will have to tell your user to input numbers in this format: 1+3j
If you would like your calculator to support a different syntax, you will have to parse the input and feed it to the complex constructor yourself. Regular expressions may be of help.
In order to get complex type input from user we have to use complex type function as suggested by #sleblanc. And if you want to separate real and imaginary part then you have to do like this:
complx = complex(input());
print(complx.real, complx.imag);
Example Output:-
>>> complx = complex(input());
1+2j
>>> print(complx.real, complx.imag);
1.0 2.0
>>>
There is no such way to input directly a complex number in Python. But how we can do is take a complex number.
Method 1-
Take a sting as input then convert it into complex.
Method 2-
Take two separate numbers and then convert them into complex.
Code for Method 1-
a = input() # user will enter 3+5j
a = complex(a) # then this will be converted into complex number.
Code for Method 2-
a ,b = map(int, input().split())
c = complex(a, b)
I know this is an old question and is already solved, but I had a little fun messing with it and including numpy to report the angle of the resulting complex number:
import numpy as np
def add(x, y):
"""This function adds two numbers"""
z1=x+y
print(num1,"+",num2,"=", z1)
return z1
...
...
num1 = complex(input("Enter first number: "))
num2 = complex(input("Enter second number: "))
if choice == '1':
z2=add(num1,num2)
print('mag = ', abs(z2))
print('angle = ', np.angle(z2, deg=True))
...
...
I like it, but I might trim the length of some of the resulting numbers, lol:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice: 1, 2, 3, or 4: 1
Enter first number: 2+2j
Enter second number: 1+j
(2+2j) + (1+1j) = (3+3j)
mag = 4.242640687119285
angle = 45.0