new to coding and lots of the vernacular is not yet under my belt.
I was practicing some very basic stuff, and I created a new project after finishing the last exercise. All the code looks good and should work, but I'm getting an error that is quoting code from the previous exercise. Am I missing something?
Here's the code I'm trying to execute:
# Enter Calculation: 5 * 6
# answer should be 30
num1, operator, num2 = raw_input('Enter calculation:').split()
num1 = int(num1)
operator = int(operator)
num2 = int(num2)
if operator == "+":
print("{} + {} = {}".format(num1, num2, num1+num2))
elif operator == "-":
print("{} - {} = {}".format(num1, num2, num1 - num2))
elif operator == "*":
print("{} * {} = {}".format(num1, num2, num1 * num2))
elif operator == "/":
print("{} / {} = {}".format(num1, num2, num1 / num2))
And when I enter 5 * 6 it brings up this error message:
Traceback (most recent call last):
File "C:\Users\Rocky\PycharmProjects\PythonTutorial.py\pythontut.py", line
5, in <module>
miles = float(raw_input('Enter a number: '))
ValueError: invalid literal for float(): 5 * 6
The code for this previous exercise is:
# Problem: Receive miles and convert to kilometers
# Kilometers = miles * 1.60934
# Enter miles 5
# 5 miles = 8.04
miles = float(raw_input('Enter a number: '))
def kilo_conversion(miles):
if miles > 0 or miles < 0:
conversion = miles * 1.60934
print 'Your distance of {} miles in kilometers is: {}'.format(miles,
conversion)
else:
print 'Nice. Try again with a number greater than zero!'
kilo_conversion(miles)
operator variable can't be typecasted to int. Try removing that line.
num1, operator, num2 = input('Enter calculation:').split()
num1 = int(num1)
num2 = int(num2)
if operator == "+":
print("{} + {} = {}".format(num1, num2, num1+num2))
elif operator == "-":
print("{} - {} = {}".format(num1, num2, num1 - num2))
elif operator == "*":
print("{} * {} = {}".format(num1, num2, num1 * num2))
elif operator == "/":
print("{} / {} = {}".format(num1, num2, num1 / num2))
GOT IT! Thanks for the help, guys. I just closed everything and copy/pasted the code into a new project. I think I just needed to clear the air. Still getting an error message, but at least it pertains to the code in the window. Thanks again :)
Related
I am building a basic calculator on python to get to know the basics of programming and what not. Basically my issue is that when I am squaring a number with my calculator it will still ask for my second number, while it spits out the correct answer still I would like it to not ask for my second number when the square function is used.
name = input("Enter your name: ")
lastname = input("Enter your last name: ")
print("Welome " + name + " " + lastname + "!")
num1 = float(input("Enter a number to calculate: "))
Component = input("*, /, +, -...?????: ")
num2 = float(input("Enter your last number...: "))
if Component == "*":
print(num1 * num2)
if Component == "+":
print(num1 + num2)
if Component == "/":
print(num1 / num2)
if Component == "-":
print(num1 - num2)
if Component == "sqr":
print(num1 ** 2)
try this num2 = float(input("Enter your last number...: ")) if Component.strip() != "sqr" else 0 instead.
Full code here:
name = input("Enter your name: ")
lastname = input("Enter your last name: ")
print("Welome " + name + " " + lastname + "!")
num1 = float(input("Enter a number to calculate: "))
Component = input("*, /, +, -...?????: ")
num2 = float(input("Enter your last number...: ")) if Component.strip() != "sqr" else 0
if Component == "*":
print(num1 * num2)
if Component == "+":
print(num1 + num2)
if Component == "/":
print(num1 / num2)
if Component == "-":
print(num1 - num2)
if Component == "sqr":
print(num1 ** 2)
Here are the instructions I received for my assignment:
4) Add the following function into Mylib
scalc(p1)
p1 will be a string like this "N1, N2, operator"
examples
scalc("20,30,*")
the result will be 600
scalc("50,20,+")
the result will be 70
scalc("50,20,-")
the result will be 30
scalc("60,20,/")
the result will be 30
use string functions to parse the first number, the second number, and the operator from the input string.
use the prior functions (add, subtract, divide and multiply ) to do the calculations.
And here is my attempt that is not working. I have the add() sub() mult() div() functions, I'm just not showing them here.
I know it's something very simple that likely has to do with where I call the function scalc(p1). What is the proper way to do that?
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[3] == "+":
add()
elif astring[3] == "-":
sub()
elif astring[3] == "*":
mult()
elif astring[3] == "/":
div()
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
EDIT: Here is the Answer. I did not have arguments being passed to my functions. By adding num1 and num2 to every instance of my arithmetic functions, they were able to receive the new variable values.
#Define the main program function
def main():
#Define input function
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
print("You must enter a number!")
else:
break
#Declare variables
rangeLower = float_input("Enter your Lower range: ")
rangeHigher = float_input("Enter your Higher range: ")
num1 = float_input("Enter your First number: ")
num2 = float_input("Enter your Second number: ")
#Define formula functions
def add(num1, num2):
sum = num1 + num2
print("The Result of",num1,"+",num2,"=", sum)
def sub(num1, num2):
diff = num1 - num2
print("The Result of",num1,"-",num2,"=", diff)
def mult(num1, num2):
product = num1 * num2
print("The Result of",num1,"*",num2,"=", product)
def div(num1, num2):
if num2 == 0:
print("The Result of",num1,"/",num2,"= You cannot divide by Zero")
else:
quotient = num1 / num2
print("The Result of",num1,"/",num2,"=", quotient)
#If-else
if num1 < rangeLower or num1 > rangeHigher or num2 < rangeLower or num2 > rangeHigher:
print("The input values are outside the input ranges.")
print("Please check the number and try again.")
print("Thanks for using our calculator")
else:
#Call functions
add(num1, num2)
sub(num1, num2)
mult(num1, num2)
div(num1, num2)
print("Thanks for using this calculator!")
def scalc(p1):
astring = p1.split(",")
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1, num2)
elif astring[2] == "-":
sub(num1, num2)
elif astring[2] == "*":
mult(num1, num2)
elif astring[2] == "/":
div(num1, num2)
return num1, num2
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
This does it. There were a couple errors. First, in Python you start counting at 0, so you wanted to use astring[2] instead of astring[3]. Also you needed a value to be returned:
def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1,num2)
elif astring[2] == "-":
sub(num1,num2)
elif astring[2] == "*":
mult(num1,num2)
elif astring[2] == "/":
div(num1,num2)
return value
p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)
Example:
input: "20,30,+"
Out[2]: 50.0
This question already has answers here:
Formatting floats without trailing zeros
(21 answers)
Closed 4 years ago.
A beginner python programming learner here.
I'm making a very simple two number calculator in python. Although it runs perfectly, I can't fix the issue with floating numbers ending with ".0". I want to remove this ending. I tried a few things but they didn't work. What condition do I need to add inside the code? Could you please take a look at it below:
def calculator():
num1 = float(input('First number: '))
operator = input('+, -, / or * ? ')
num2 = float(input('Second Number: '))
if operator == '+':
return print(num1, '+', num2, '=', num1 + num2)
elif operator == '-':
return print(num1, '-', num2, '=', num1 - num2)
elif operator == '/':
return print(num1, '/', num2, '=', num1 / num2)
elif operator == '*':
return print(num1, '*', num2, '=', num1 * num2)
calculator()
Thank you in advance!
I exactly did what #water-winter suggested but whenever I execute the program and enter numbers and operator I get this error: if result.is_integer():
AttributeError: 'int' object has no attribute 'is_integer'
Update: Looks like that only "/" operator works perfectly. The other 3 operators give the same error above. :/
New Update: Finally I managed to make the calculator programming flawlessly!
def calculator():
num1 = float(input("First number: "))
operator = input("Choose: +, -, /, or *")
num2 = float(input("Second number: "))
num1 = int(num1) if num1.is_integer() else num1
num2 = int(num2) if num2.is_integer() else num2
add = (num1 + num2)
subtract = (num1 - num2)
divide = (num1 / num2)
multiply = (num1 * num2)
if operator == "+" and add % 1 == 0:
print(num1, "+", num2, "is equal to:", int(add))
elif operator == "+" and not add % 1 == 0:
print(num1, "+", num2, "is equal to:", add)
elif operator == "-" and subtract % 1 == 0:
print(num1, "-", num2, "is equal to:", int(subtract))
elif operator == "-" and not subtract % 1 == 0:
print(num1, "-", num2, "is equal to:", subtract)
elif operator == "/" and divide % 1 == 0:
print(num1, "/", num2, "is equal to:", int(divide))
elif operator == "/" and not divide % 1 == 0:
print(num1, "/", num2, "is equal to:", divide)
elif operator == "*" and multiply % 1 == 0:
print(num1, "*", num2, "is equal to:", int(multiply))
elif operator == "*" and not multiply % 1 == 0:
print(num1, "*", num2, "is equal to:", multiply)
calculator()
Thank you guys, for the help and suggestions. They helped a lot! :)
First, there's a built-in function for float to check for integer and there's int() to trip off decimal places.
>> float(0.5).is_integer()
>> False
>> float(3.0).is_integer()
>> True
>> int(float(5.5))
>> 5
>> int(float(3))
>> 3
Second, if you simply want to print, the return keyword is unnecessary.
def calculator():
num1 = float(input('First number: '))
operator = input('+, -, / or * ? ')
num2 = float(input('Second Number: '))
num1 = int(num1) if num1.is_integer() else num1
# This line is equivalent to:
# if num1.is_integer():
# num1 = int(num1)
# else:
# num1 = num1
num2 = int(num2) if num2.is_integer() else num2
if operator == '+':
result = num1 + num2
result = int(result) if result.is_integer() else result
print(num1, '+', num2, '=', result)
elif operator == '-':
...
calculator()
First my codes are from this link
https://www.programiz.com/python-programming/examples/calculator
When i open the program whatever choice I make it prints me invalid input. Am I missing something?
However when I do it on Codeskulptor I do not get it but get the answer i am looking for?
Note: I am using ubuntu and I am trying on Terminal.
Using the built-in eval() is probably the easiest approach:
while True:
data = input('Enter operation: ')
print(eval(data))
use this code
num1 = float(input('Enter a number: '))
the_operation = str(input('choose operator: '))
num2 = float(input('Enter an anathor number: '))
if the_operation == '*':
print(num1 * num2)
elif the_operation == '+':
print(num1 + num2)
elif the_operation == '-':
print(num1 - num2)
elif the_operation == '/':
print(num1 / num2)
print("There must be a space between the number and the operator!!\nBlank to continue\n")
def calc(a,b,c):
if b in '+-*/':
if b=='+':
d=a+c
if b=='-':
d=a-c
if b=='*':
d=a*c
if b=='/':
if c==0:
d="undefind"
else:
d=a/c
return "Answer:- {}".format(d)
else:
return "Invalid operator '{}' !".format(b)
while True:
cal=input("Type here:- ").split()
if len(cal)!=3:
print("Try again!")
continue
num1,op,num2=cal[:]
print(calc(float(num1),op,float(num2)))
if input("Going to next calculation or not\n::- ").strip()!='':
break
I am trying to find out how to make my code repeat its self 3 times at the end of the set of questions and also I'm trying to make sure my validation is correct so that the input to the questions is only a number.
This is my code...
import random
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in range(10):
num1 = float(random.randint(1, 10))
num2 = float(random.randint(1, 10))
Math = random.choice(["+", "-", "*","/"])
print("Please solve:", num1, Math, num2)
user = int(input(""))
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = num1 / num2
if answer!= int:
print ("Please reenter a number")
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, " You Got", correct, "Out Of 10")
Your answer != int should be if not isinstance(answer, int)
Furthermore, you will get ValueError each time user tries to insert characters.
Because of this, you should edit your code to look like this:
from __future__ import division
import random
for i in xrange(3):
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in xrange(3):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
Math = random.choice(["+", "-", "*","/"])
print("Please solve: {} {} {}".format(num1, Math, num2))
while True:
try:
user = int(raw_input(""))
except ValueError:
print ("Please reenter a number")
continue
break
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = round(num1 / num2, 1)
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print("{} You Got {} Out Of 10".format(name, correct))
As you can see there was a lot things that you needed to change.