Python ask for user input without a newline? - python

I just started python a few days ago and have been working on a calculator (not extremely basic, but also not advanced). The problem doesn't prevent code from running or anything, it is just a visual thing.
Output in the console looks like this (stuff in parenthesis is explaining what is happening and is not actually part of the output):
4 (user prompted for first number, press enter afterwards)
+ (user prompted for an operator, press enter afterwards
5 (user prompted for second number, press enter afterwards)
9.00000 (answer is printed)
Process finished with exit code 0
Basically what I want it to look like is this when I'm entering it into the console:
4+5
9.00000
I don't want it to start a newline after I enter a number or operator or whatever, it looks more like an actual calculator when it prints along one line. Is this possible to do and if so how? Btw I know end="" works with print but not with input since it doesn't accept arguments. Also I know the whole calculator thing is kind of redundant considering you can make calculations really easily in the python IDLE but I thought it was a good way for me to learn. Here is the entire code if you need it:
import math
while True:
try:
firstNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
while True:
operators = ['+', '-', '*', '/', '!', '^']
userOperator = str(input())
if userOperator in operators:
break
else:
print("Enter a valid operator... ", end="")
if userOperator == operators[4]:
answer = math.factorial(firstNumber)
print(answer)
pause = input()
raise SystemExit
while True:
try:
secondNumber = float(input())
break
except ValueError:
print("Please enter a number... ", end="")
if userOperator == operators[0]:
answer = firstNumber + secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[1]:
answer = firstNumber - secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[2]:
answer = firstNumber * secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[3]:
answer = firstNumber / secondNumber
print('%.5f' % round(answer, 5))
elif userOperator == operators[5]:
answer = firstNumber ** secondNumber
print('%.5f' % round(answer, 5))
pause = input()
raise SystemExit

Your problem is that you're asking for input() without specifying what you want. So if you take a look at the first one: firstNumber = float(input()) It's executing properly, but you hit enter it gives an error which is only then you're specifying what you want.
Try replacing with these:
...
try
firstNumber = float(input("Please enter a number... "))
...
userOperator = str(input("Enter a valid operator... "))
...
secondNumber = float(input("Please enter a number... "))
Is that what you're looking for?
Using my method I suggested:
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
Using your method:
Please enter a number... 5
Enter a valid operator... +
Please enter a number... 6
11.00000
Extra newlines which is what I'm assuming you're referring to.

That's a nice exercise, and as I wrote in the comments, I would ignore whitespaces, take the expression as a whole from the user and then parse it and calculate the result. Here's a small demo:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def calc(expr):
if is_number(expr):
return float(expr)
arr = expr.split('+')
if len(arr) > 1:
return sum(map(calc, arr))
arr = expr.split('-')
if len(arr) > 1:
return reduce(lambda x,y: x-y, map(calc, arr))
arr = expr.split('*')
if len(arr) > 1:
return reduce(lambda x,y: x*y, map(calc, arr), 1)
arr = expr.split('/')
if len(arr) > 1:
return reduce(lambda x,y: x/y, map(calc, arr))
print calc("3+4-2 *2/ 2") # 5

Related

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)

If statement not executing what it should

mylist = []
for i in range(0,101,2):
mylist.append(i)
length = len(mylist)
middle_index = length // 2
first_half = mylist[:middle_index]
second_half = mylist[middle_index:]
userRandomNumber = str(input('Please input a random number from 0-100: '))
while True:
if userRandomNumber.isdigit():
break
else:
userRandomNumber = input('Please input a number!: ')
print(first_half)
print(second_half)
if userRandomNumber in first_half:
print('you got it')
elif userRandomNumber in second_half:
print('you got it')
else:
print('false!')
I am making a program where the user has to guess the number in the random list generated automatically. But the problem is when I run the code and input a number that is actually in the list the if statement does not work the way it should!
What is wrong with the code here? Please help!
input returns a string. So, the number you actually enter is converted to string. Even if it didn't, the str would.
Your lists are full of integers. So there is a difference between an integer and string number. It is checking if the string number is in the list.
Of course, it isn't. So the in operator returns False
input('Please input a random number from 0-100: ')
Try this:
if int(userRandomNumber) in first_half:
print('you got it')
elif int(userRandomNumber) in second_half:
print('you got it')
else:
print('false!')
Here this is code:
number=input("Type a number:")
mylist = []
for i in range(0,101,2):
mylist.insert(1,i)
length = len(mylist)
middle_index = length // 2
first_half = mylist[:middle_index]
second_half = mylist[middle_index:]
if int(number) in first_half:
print('you got it')
elif int(number) in second_half:
print('you got it')
else:
print("Nope, "+"'"+"number"+"'"+" not found in the list")
print(first_half)
print(second_half)
In your code, these set of code -
userRandomNumber = str(input('Please input a random number from 0-100: '))
while True:
if userRandomNumber.isdigit():
break
else:
userRandomNumber = input('Please input a number!: ')
can be changed into this -
while True:
try:
userRandomNumber = int(input('Please input a random number from 0-100: '))
break
except:
pass
If you do not know what try and except does, then check this - Python Exception Handling
The rest of the code can be the same, and it will work.
mylist = [i for i in range(0, 101, 2)]
middle_index = len(mylist) // 2
first_half, second_half = mylist[:middle_index], mylist[middle_index:]
print(first_half, second_half, sep='\n')
userRandomNumber = ''
while not userRandomNumber.isdigit():
userRandomNumber = input('Please input a random number from 0-100: ')
userRandomNumber = int(userRandomNumber)
# I think the point of splitting the list into two parts is probably to determine which part belongs to
# the number entered. Otherwise, if the output is 'you got it', then splitting the list makes no sense.
if userRandomNumber in first_half:
print('you got it in the first half')
elif userRandomNumber in second_half:
print('you got it in the second half')
else:
print('false!')

Is this an efficient calculator in Python?

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

Adding onto an input prompt after the user inputs

I'm trying to make a "pi-practicing' program in python, and I want the user's input, if correct, to be placed next to the "3.".
I have:
numbers = [1,4,1,5,9,2,6,5]
def sequence():
i = input("3.")
y = int(i)
if y == numbers[0]:
print ("Good job!")
#??????
numbers.pop(0)
sequence()
else:
print("nope")
sequence()
sequence()
So when prompted, if the user enters 1 as the first number, I want the next input prompt to be 3.1, so the user has to enter 4, and so on.
Thank you in advance!
-rt
You don't need recursion a simple while loop would do. It's generally not good practice to leverage global variables:
def sequence():
numbers = [1,4,1,5,9,2,6,5]
prompt = '3.'
while numbers:
i = input(prompt)
y = int(i)
if y == numbers[0]:
print ("Good job!")
prompt += i
numbers.pop(0)
else:
print("nope")
sequence()

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

Categories