How to make input statements optional? - python

I was having a small issue while I was trying to write a program to calculate simple interest in Python.
def si(p,r=100,t=2):
return (p*r*t)/100
x=float(input("Enter principal amount"))
y=float(input("Enter rate"))
z=float(input("Enter time"))
print (si(x,y,z))
I want to make y and z optional. Any idea how can I do? If I leave it blank and press enter it shows error.

The easiest way is using or
def si(p,r,t):
return (prt)/100
x = float(input("Enter principal amount: "))
y = float(input("Enter rate: ") or 100)
z = float(input("Enter time: ") or 2)
print (si(x,y,z))
Enter principal amount: 1
Enter rate:
Enter time:
2.0
But correct way is validating input before converting it to float
def si(p,r=100,t=2):
return (p*r*t)/100
x = input("Enter principal amount: ")
y = input("Enter rate: ")
z = input("Enter time: ")
def validate(param):
return float(param) if param else 1
print (si(validate(x), validate(y), validate(z)))
Output:
Enter principal amount: 1
Enter rate:
Enter time:
0.01

Related

Can someone show the right approach to get below desired output? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
When the user gives wrong input for tax_rate, it should ask user the correct input for that variable, but instead it is starting from first, asking the hr_rate input which is already received.
while True:
try:
hr_rate = float(input("Enter Hourly Rate: "))
emp_ot_rate = float(input("Enter Overtime Rate: "))
tax_rate = float(input("Enter Standard Tax Rate: "))
ot_tax_rate = float(input("Enter Overtime Tax Rate: "))
except Exception:
print("Invalid entry, please retry")
Output:
Enter Hourly Rate: abc
Invalid entry, please retry
Enter Hourly Rate: 10.2
Enter Overtime Rate: 20.25
Enter Standard Tax Rate: abc
Invalid entry, please retry
Enter Hourly Rate:
The last line should ask for Standard Tax Rate again.
Whenever you see repetitive code, it is generally the case of defining a function that performs the same task but with the appropriate differences based on the given argument(s):
def userInput(variable):
while True:
try:
user_input = float(input(f"Enter {variable}: "))
break
except Exception:
print("Please enter any numbers")
return user_input
This function will perform the same task but the input prompt will change according to the variable argument; e.g you can call it with 'Hourly Rate':
hr_rate = userInput("Hourly Rate")
and it will prompt the user with the correct sentence:
>>>Enter Hourly Rate:
From #Brian's comment above, and at the risk of doing someone's homework for them...
def float_input(prompt):
'''Prompt user with given <prompt> string.'''
while True:
try:
return float(input("Enter Hourly Rate: "))
except ValueError: # Make exceptions as specific as possible
print("Please enter any numbers")
hr_rate = float_input("Enter Hourly Rate: ")
emp_ot_rate = float_input("Enter Overtime Rate: ")
tax_rate = float_input("Enter Standard Tax Rate: ")
ot_tax_rate = float_input("Enter Overtime Tax Rate: ")

Marks calculator for average

I have used the sum function for the array.I need to use that so that if the list gets bigger, the total is still right. But I keep getting error.
This is the code I have:
print("please enter your 5 marks below")
#read 5 inputs
mark1 = input("enter mark 1: ")
mark2 = input("enter mark 2: ")
mark3 = input("enter mark 3: ")
mark4 = input("enter mark 4: ")
mark5 = input("enter mark 5: ")
#create array/list with five marks
marksList = [mark1, mark2, mark3, mark4, mark5]
#print the array/list
print(marksList)
#calculate the sum and average
sumOfMarks = sum(marksList)
averageOfMarks = sum(marks_ist)/5
#display results
print("The sum of your marks is: "+str(sumOfMarks))
print("The average of your marks is: "+str(averageOfMarks))
Thats because you get the input as a string and not int.
mark1 = int(input("enter mark 1: "))

ValueError: math domain error.. No root of negative number

My python always gives me this error..
There is no root of negative number because all bits inside are squared..help!
elif coordNumber == "4":
fourInputXOne = int(input ("Please enter the x value of the first co-ordinate "))
fourInputYOne = int(input ("Please enter the y value of the first co-ordinate "))
print ("")
fourInputXTwo = int(input ("Please enter the x value of the second co-ordinate "))
fourInputYTwo = int(input ("Please enter the y value of the second co-ordinate "))
print ("")
fourInputXThree = int(input ("Please enter the x value of the third co-ordinate "))
fourInputYThree = int(input ("Please enter the y value of the third co-ordinate "))
print ("")
fourInputXFour = int(input ("Please enter the x value of the fourth co-ordinate "))
fourInputYFour = int(input ("Please enter the y value of the fourth co-ordinate "))
print ("")
print ("Here are the co-ordinates you have entered:")
print ("1: (",fourInputXOne,",",fourInputYOne,")")
print ("2: (",fourInputXTwo,",",fourInputYTwo,")")
print ("3: (",fourInputXThree,",",fourInputYThree,")")
print ("4: (",fourInputXFour,",",fourInputYFour,")")
sideOneLength = math.sqrt((fourInputXTwo-fourInputXOne)^2 + (fourInputYTwo-fourInputYOne)^2 )
sideTwoLength = math.sqrt((fourInputXThree-fourInputXTwo)^2 + (fourInputYThree-fourInputYTwo)^2 )
sideThreeLength = math.sqrt((fourInputXFour-fourInputXThree)^2 + (fourInputYFour-fourInputYThree)^2 )
sideFourLength = math.sqrt((fourInputXOne-fourInputXFour)^2 + (fourInputYOne-fourInputYFour)^2 )
Error with the sidelengths bit.
in python you use a**b to square not a^b
the caret symbol is a binary XOR operator
elif coordNumber == "4":
fourInputXOne = int(input ("Please enter the x value of the first co-ordinate "))
fourInputYOne = int(input ("Please enter the y value of the first co-ordinate "))
print ("")
fourInputXTwo = int(input ("Please enter the x value of the second co-ordinate "))
fourInputYTwo = int(input ("Please enter the y value of the second co-ordinate "))
print ("")
fourInputXThree = int(input ("Please enter the x value of the third co-ordinate "))
fourInputYThree = int(input ("Please enter the y value of the third co-ordinate "))
print ("")
fourInputXFour = int(input ("Please enter the x value of the fourth co-ordinate "))
fourInputYFour = int(input ("Please enter the y value of the fourth co-ordinate "))
print ("")
print ("Here are the co-ordinates you have entered:")
print ("1: (",fourInputXOne,",",fourInputYOne,")")
print ("2: (",fourInputXTwo,",",fourInputYTwo,")")
print ("3: (",fourInputXThree,",",fourInputYThree,")")
print ("4: (",fourInputXFour,",",fourInputYFour,")")
sideOneLength = math.sqrt((fourInputXTwo-fourInputXOne)**2 + (fourInputYTwo-fourInputYOne)**2 )
sideTwoLength = math.sqrt((fourInputXThree-fourInputXTwo)**2 + (fourInputYThree-fourInputYTwo)**2 )
sideThreeLength = math.sqrt((fourInputXFour-fourInputXThree)**2 + (fourInputYFour-fourInputYThree)**2 )
sideFourLength = math.sqrt((fourInputXOne-fourInputXFour)**2 + (fourInputYOne-fourInputYFour)**2 )
Why are you logically XORing your values?
Printing the offending numbers:
print( (fourInputXTwo-fourInputXOne)^2 ) # you can see its negative
or experimenting:
print(6^2) # prints 4 - because 0b110^0b010 == 0b100
print(6**2) # prints 36 - because 6**2 = 6*6 = 36
would have shown you that what you do wrong.
See binary bitwise operations for the full documentation.

Trigonometry in Python

I made this calculator to try and calculate trigonometry in python. I've only just started learning how to use this program and I haven't been able to find anything so far that makes sense to me. The problem with this is that I keep getting different answers to those that come up on my scientific calculator.
while True:
print('type "sine1" to find the value of the Opposite')
print('type "sine2" to find the value of the Hypotenuse')
print('type "cosine1" to find the value of the Adjacent')
print('type "cosine2" to find the value of the Hypotenuse')
print('type "tangent1" to find the value of the Opposite')
print('type "tangent2" to find the value of the Adjacent')
user_input = input(": ")
from math import sin, cos, tan
if user_input == 'sine1':
degrees = float(input('Enter the degrees: '))
hypotenuse = float(input('Enter the value of the hypotenuse: '))
result = str(hypotenuse * sin(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'sine2':
degrees = float(input('Enter the degrees: '))
opposite = float(input('Enter the value of the opposite: '))
result = str(opposite / sin(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'cosine1':
degrees = float(input('Enter the degrees: '))
hypotenuse = float(input('Enter the value of the hypotenuse: '))
result = str(hypotenuse * cos(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'cosine2':
degrees = float(input('Enter the degrees: '))
adjacent = float(input('Enter the value of the adjacent: '))
result = str(adjacent / cos(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'tangent1 ':
degrees = float(input('Enter the degrees: '))
adjacent = float(input('Enter the value of the adjacent: '))
result = str(hypotenuse * tan(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'tangent2':
degrees = float(input('Enter the degrees: '))
opposite = float(input('Enter the value of the opposite: '))
result = str(adjacent / cos(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
else:
print('invalid input, please close the program and try again... maybe learn how to spell first :P')
print(input('press enter to quit'))
All trigonometric function from the math module require their argument to be in radians, not in degrees. You can use math.radians to do the conversion.
import math
degrees = 90
radians = math.radians(degrees)
print(math.sin(radians)) # 1.0
Python's trig functions assume that the input is in radians, and you're entering degrees.
First convert your degrees to radians by multiplying degrees by math.pi/180.0 and see if those match better.

Sum/ average / product in python

I am trying to write a program which asks an input of two numbers and then prints the sum, product and average by running it. I wrote a program but it asks an input for 2 numbers everytime i need a sum or average or product. How can I get all 3 at once, just making two inputs once.
sum = int(input("Please enter the first Value: ")) + \
int(input("Please enter another number: "))
print("sum = {}".format(sum))
product = int(input("Please enter the first Value: ")) * \
int(input("Please enter another number: "))
print ("product = {}".format(product))
Use variables to store the input:
first_number = int(input("Please enter the first Value: "))
second_number = int(input("Please enter another number: "))
sum = first_number + second_number
product = first_number * second_number
average = (first_number + second_number) / 2
print('Sum is {}'.format(sum))
print('product is {}'.format(product))
print('average is {}'.format(average))
You need to assign your numbers to variables and then reuse them for the operations.
Example
x = int(input("Please enter the first Value: "))
y = int(input("Please enter another number: "))
print("sum = {}".format(x+y))
print("product = {}".format(x*y))
print("average = {}".format((x+y)/2))
You're going to want to get the numbers first, then do your operation on them. Otherwise you're relying on the user to alway input the same two numbers:
a = int(input("Please enter the first Value: "))
b = int(input("Please enter the second Value: "))
print ("sum = {}".format(a+b))
print ("product = {}".format(a*b))
print ("average = {}".format((a*b)/2))

Categories