Tuesday, October 3, 2017

Adventures in Python: Input Requires Declaring Type of Input

Adventures in Python: Input Requires Declaring Type of Input

I work with calculators, and in calculator programming, the Input command usually defaults to numerical input.  That is not the case in Python.  Input, without declaration, defaults in strings.  Strings are nice, but don’t usually do well in mathematical calculation.

Ways to use the Input command:

input(‘prompt’)
Input accepted as a string.  We can also use string(input(‘prompt’)).
int(input(‘prompt’))
Input accepted as integers.
float(input(‘prompt’))
Input accepted as real (floating) numbers.
complex(input(‘prompt’))
Input accepted as complex numbers.  In Python, complex numbers are in the form x + yj (instead of x + yi). 

The prompt is an optional string. 

In the following program, thanks to complex(input()) format, inputs are accepted as complex numbers.  This solves the quadratic equation using the quadratic formula. 

One other note, I use the double asterisk (**) for powers.  Examples:  2**2 = 2^2 = 4,  16**0.5 = √16 = 4.  The double asterisk works on complex numbers, opposed to the math.sqrt function.

# Program 002: Quadratic Equation
# header
# note that all comments start with a hashtag

# header
print("a*x^2 + b*x + c = 0")

# the default format of input is string
# we must use complex to all for complex numbers
# complex numbers are in the format real + imag*j
# where j = sqrt(-1).  j is usally i but it is used
# for Python and electronic engineering
a = complex(input("a: "))
b = complex(input("b: "))
c = complex(input("c: "))

# discriminat
# note that powers y^x are used by double asterisk, like this y**x
d = b**2-4*a*c

# root calculation
root1 = (-b + d**(0.5))/(2*a)
root2 = (-b - d**(0.5))/(2*a)

# display results
print("Discriminant =  ",d)
print("Root 1 = ",root1)
print("Root 2 = ",root2)


Output (I give a = 1+6j, b = -9, c = 4 as inputs):

a*x^2 + b*x + c = 0
a: 1+6j
b: -9
c: 4
Discriminant =   (65-96j)
Root 1 =  (-0.1590249844353114-1.5691249198547j)
Root 2 =  (0.4022682276785546+0.10966546039524058j)

More adventures in Python to come! 

Eddie


This blog is property of Edward Shore, 2017.

No comments:

Post a Comment

HP Prime: Feet-Inches Calculator

HP Prime:   Feet-Inches Calculator Calculate in Feet-Inches The program FTIN is an arithmetic calculator that calculates in feet-...