Having a Python if statement syntax error, assistance please - python-3.x

I'm currently working on some python code but its giving me a syntax error in the second 'if statement'. When I run it, it highlights the 'quadpos'. What seems to be the problem?
print(' Hello, press enter to continue')
print('What is your A value?') # Asking for the A value
myA = input()
myA = int(myA)
print('What is your B value?') # Asking for the B value
myB = input()
myB = int(myB)
print('What is your C value?') # Asking for the C value
myC = input()
myC = int(myC)
quad = ((myB * myB) - (4 * myA * myC))
if int(quad) < int(0):
print('Cannot process Value')
else:
quad2 = (int(quad)**(1/2.0))
if int(myA) > int(0):
quadneg = ((int(-myB) - int(quad2)) / (2 * myA)
quadpos = ((int(-myB) + int(quad2)) / (2 * myA)
print(int(quadneg))
print(int(quadpos))
else:
quad3 = ((int(-myB) * int(-myB)) + int(quad2)) / (2 * myA)
print (int(quad3))

The error is in the line 21 and 22 according to your attached picture
print( int( quardneg) )
print( int(quardpos) )
followed by else statement
The syntax of if else statements are :
If condition:
Code...
Else
Code ..
You are doing:
If condition:
Code
Code -- Error is here
Else
Code.
You can't put the code in the same indentation of if statement, if you do so then you have to replace else by next if.

You seem to have a missing bracket.
quadneg = ( (int(-myB) - int(quad2)) / (2 * myA) )
quadpos = ( (int(-myB) + int(quad2)) / (2 * myA) )

Related

Python Truth value of a series is ambiguous error in Function

I 'm trying to build a function that uses several scalar values as inputs and one series or array also as an input.
The function applies calculations to each value in the series. It works fine so far. But now I'm adding a phase where it has to check the value of the series and if it's less than X it performs one calculation other it performs a different calculation.
However I keep getting a 'truth value series is ambiguous error and I can't seem to solve it.
What is a work around?
My code is below
import numpy as np
import pandas as pd
import math
tramp = 2
Qo = 750
Qi = 1500
b = 1.2
Dei = 0.8
Df = 0.08
Qf = 1
tmax = 30
tper = 'm'
t = pd.Series(range(1,11))
def QHyp_Mod(Qi, b, Dei, Df, Qf, tmax, tper, t):
tper = 12
Qi = Qi * (365/12)
Qf = Qf * (365/12)
ai = (1 / b) * ((1 / (1 - Dei)) ** b - 1)
aim = ai / tper
ai_exp = -np.log(1 - Df)
aim_exp = ai_exp / tper
t_exp_sw = 118
Qi_exp = Qi / ((1 + aim * t_exp_sw * b) ** (1 / b))
Qcum = (Qi / (aim * (1 - b))) * (1 - (1 / ((1 + aim * t * b) ** ((1 - b) / b))))
t_exp = t - t_exp_sw
Qcum_Exp = (Qi_exp / aim_exp) * (1 - np.exp(-aim_exp * t_exp))
if t < t_exp_sw:
return Qcum
else:
return Qcum_exp
z = QHyp_Mod(Qi=Qi, b=b, Dei=Dei, Df=Df, Qf=Qf, tmax=tmax, tper=tper, t=t)
Replace the if - else statement:
if t < t_exp_sw:
return Qcum
else:
return Qcum_exp
with this:
Q.where(t < t_exp_sw, Q_exp)
return Q
The where method tests the conditional for each member of Q, if true keeps the original value, and if false replaces it with the corresponding element of Q_exp

How to give a space along with printing result

So, i want to create a function. If i use 4 as input number, then it will give a result:
****
***
**
*
I use code like this.
def print_pattern(input_number):
for i in reversed(range(input_number)):
integer = (i+1)
if integer == input_number:
output = (integer * '*')
elif integer < input_number:
output = " " + (integer * '*')
print(output)
print_pattern(6)
But, the result only show the first looping like this.
****
***
**
*
what should i do?
Using str.rjust
Ex:
def print_pattern(input_number):
num = input_number+1
for i in reversed(range(num)):
print(("*"*i).rjust(input_number, " "))
print_pattern(4)
Output:
****
***
**
*
def print_pattern(input_number):
for i in range(input_number):
print((" " * i) + "*" * (input_number -i))
Examples:
>>> print_pattern(4)
****
***
**
*
>>> print_pattern(6)
******
*****
****
***
**
*

why compiler doesn't stop iterating while loop

I made a program to print pyramid using * with my own way but whenever i run my program on compiler the program gets executed and doesn't stop after the for loop ends its iteration,here's my program which i think should stop executing after 10 iterations.
a = " "
b = ""
for i in range(10):
a = a[:-1]
b = (b * i) + '*'
print('\n')
for k in range(i):
print("{}{}".format(a,b), end="")
i am expecting the output like this:
*
***
*****
*******
*********
***********
*************
***************
Your problem probably comes from your b assignation.
Let's calculate the length of b at step i (from 0 to 10) (b(n) = b(n-1)*index + 1)
b(0) = 0*0 + 1 = 1
b(1) = 1*1 + 1 = 2
b(2) = 2*2 + 1 = 5
b(3) = 5*3 + 1 = 16
And so on, we can see the length of b is going exponential, for instance, for index = 10, len(b) = 986410
This increasing string might make the compiler slowing down.
You might want to try this code which does not keep in memory the strings.
height = 10
for i in range(height):
print(' '*(height-i-1)+'*'*(2*i+1))
output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
Try this improved code instead:
a = " " # empty string to be attached at the front and back (length is 11)
for i in range(10): # height of pyramid
a = a[:-1] # make string a bit smaller to compensate for
b = '*' * (i*2 + 1) # the increasing amount of '*'s
print("{}{}{}".format(a, b, a)) # prints the pyramid
The len(a) should be the height of your pyramid plus the amount of padding wanted on the last row. For example:
*
***
*****
*******
There's 2 spaces left on the bottom row, and the height of the pyramid is 4. That means the length of a should be 6. Make a using a = ' '*(height + padding)

How can I correctly implement this example of using classes?

In the following example, one can choose constants to depend upon the context of a future situtation.
class Constants:
SPEEDLIGHT = 3 * 10**8
GRAVITY = 9.81
C = Constants()
print(C.GRAVITY)
>> 9.81
That was not too difficult because each quantity is a fixed constant. But suppose I want to do something similar for functions. In this first block of code below, I specify two distributions of integrable variable x and fixed parameters a and b.
class IntegrableDistribution:
def Gaussian(x,a,b):
cnorm = 1 / ( b * (2 * pi)**(1/2) )
return cnorm * np.exp( (-1) * (x-a)**2 / (2 * b**2) )
# Gaussian = Gaussian(x,a,b)
def Lognormal(x,a,b):
cnorm = 1 / ( b * (2 * pi)**(1/2) )
return cnorm * exp( (-1) * (np.log(x)-a)**2 / (2 * b**2) ) / x
# Lognormal = Lognormal(x,a,b)
I was trying to name the distributions so that they could be callable. That resulted in an error message, hence the commented out code above. In this next block of code, I am trying to use an input to select a distribution for integration (though I feel it is extremely inefficient).
Integrable = IntegrableDistribution()
class CallIntegrableDistribution:
def Model():
def Pick():
"""
1 : Gaussian Distribution
2 : Lognormal Distribution
"""
self.cmnd = cmnd
cmnd = int(input("Pick a Distribution Model: "))
return cmnd
self.cmnd = cmnd
if cmnd == 1:
Distribution = Integrable.Gaussian
if cmnd == 2:
Distribution = Integrable.Lognormal
return Distribution
OR ALTERNATIVELY
cmnd = {
1: Gaussian,
2: Lognormal,
}
I'm not really concerned with the problem of distributions; I'm only applying it to showcase my knowns and unknowns. What are some ways to properly do this or something similar/simpler using classes or dictionaries?
Use static methods:
class IntegrableDistribution:
#staticmethod
def Gaussian(x,a,b):
cnorm = 1 / ( b * (2 * pi)**(1/2) )
return cnorm * np.exp( (-1) * (x-a)**2 / (2 * b**2) )
#staticmethod
def Lognormal(x,a,b):
cnorm = 1 / ( b * (2 * pi)**(1/2) )
return cnorm * exp( (-1) * (np.log(x)-a)**2 / (2 * b**2) ) / x
And usage:
some_result = IntegrableDistribution.Gaussian(1, 2, 3)
another_result = IntegrableDistribution.Lognormal(1, 2, 3)

How to write cos(1)

I need to find a way to write cos(1) in python using a while loop. But i cant use any math functions. Can someone help me out?
for example I also had to write the value of exp(1) and I was able to do it by writing:
count = 1
term = 1
expTotal = 0
xx = 1
while abs(term) > 1e-20:
print("%1d %22.17e" % (count, term))
expTotal = expTotal + term
term=term * xx/(count)
count+=1
I amm completely lost as for how to do this with the cos and sin values though.
Just change your expression to compute the term to:
term = term * (-1 * x * x)/( (2*count) * ((2*count)-1) )
Multiplying the count by 2 could be changed to increment the count by 2, so here is your copypasta:
import math
def cos(x):
cosTotal = 1
count = 2
term = 1
x=float(x)
while abs(term) > 1e-20:
term *= (-x * x)/( count * (count-1) )
cosTotal += term
count += 2
print("%1d %22.17e" % (count, term))
return cosTotal
print( cos(1) )
print( math.cos(1) )
You can calculate cos(1) by using the Taylor expansion of this function:
You can find more details on Wikipedia, see an implementation below:
import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def cos(order):
a = 0
for i in range(0, order):
a += ((-1)**i)/(factorial(2*i)*1.0)
return a
print cos(10)
print math.cos(1)
This gives as output:
0.540302305868
0.540302305868
EDIT: Apparently the cosine is implemented in hardware using the CORDIC algorithm that uses a lookup table to calculate atan. See below a Python implementation of the CORDIS algorithm based on this Google group question:
#atans = [math.atan(2.0**(-i)) for i in range(0,40)]
atans =[0.7853981633974483, 0.4636476090008061, 0.24497866312686414, 0.12435499454676144, 0.06241880999595735, 0.031239833430268277, 0.015623728620476831, 0.007812341060101111, 0.0039062301319669718, 0.0019531225164788188, 0.0009765621895593195, 0.0004882812111948983, 0.00024414062014936177, 0.00012207031189367021, 6.103515617420877e-05, 3.0517578115526096e-05, 1.5258789061315762e-05, 7.62939453110197e-06, 3.814697265606496e-06, 1.907348632810187e-06, 9.536743164059608e-07, 4.7683715820308884e-07, 2.3841857910155797e-07, 1.1920928955078068e-07, 5.960464477539055e-08, 2.9802322387695303e-08, 1.4901161193847655e-08, 7.450580596923828e-09, 3.725290298461914e-09, 1.862645149230957e-09, 9.313225746154785e-10, 4.656612873077393e-10, 2.3283064365386963e-10, 1.1641532182693481e-10, 5.820766091346741e-11, 2.9103830456733704e-11, 1.4551915228366852e-11, 7.275957614183426e-12, 3.637978807091713e-12, 1.8189894035458565e-12]
def cosine_sine_cordic(beta,N=40):
# in hardware, put this in a table.
def K_vals(n):
K = []
acc = 1.0
for i in range(0, n):
acc = acc * (1.0/(1 + 2.0**(-2*i))**0.5)
K.append(acc)
return K
#K = K_vals(N)
K = 0.6072529350088812561694
x = 1
y = 0
for i in range(0,N):
d = 1.0
if beta < 0:
d = -1.0
(x,y) = (x - (d*(2.0**(-i))*y), (d*(2.0**(-i))*x) + y)
# in hardware put the atan values in a table
beta = beta - (d*atans[i])
return (K*x, K*y)
if __name__ == '__main__':
beta = 1
cos_val, sin_val = cosine_sine_cordic(beta)
print "Actual cos: " + str(math.cos(beta))
print "Cordic cos: " + str(cos_val)
This gives as output:
Actual cos: 0.540302305868
Cordic cos: 0.540302305869

Resources