Program skipping if statement [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm a beginner with python.
I've created a little program for my navigation homework which when I input the data solves it for me but it's not working. It asks the initial question to determine which type of problem to solve and then, when it's supposed to solve it, it crashes. Why is that?
import math
print("Insert all values in degree decimal form.")
prob = input("1 or 2")
if prob == 1:
fia = input("Insert value of phi in A: ")
lama = input("Insert value of lambda in A: ")
route = input("Insert value of true route: ")
vel = input("Insert speed: ")
Tma = input("Insert Established Time of Departure: ")
Tmb = input("Insert Established Time of Arrival: ")
deltaT = Tmb - Tma
print(deltaT)
m = vel * deltaT
print(m)
deltafi = (m / 60) * math.cos(route)
print(deltafi)
fib = fia + deltafi
if fib > 180:
fib1 = -(360 - fib)
fib = fib1
print(fib)
else:
print(fib)
fim = (fia + fib) / 2
print(fim)
deltalam = (m * math.sin(route) / (60 * math.cos(fim)))
lamb = lama + deltalam
if lamb > 180:
lamb1 = -(360 - lamb)
lamb = lamb1
print(lamb)
else:
print(lamb)
print("Coordinates of B: ")
print(fib, lamb, Tmb)
elif prob == 2:
fia = input("Insert value of phi in A: ")
lama = input("Insert value of lambda in A: ")
fib = input("Insert value of phi in B: ")
lamb = input("Insert value of lambda B: ")
deltafi = fib - fia
deltalam = lamb - lama
fim = (fia + fib) / 2
tanroute = (deltalam / deltafi) * math.cos(fim)
route = math.atan(tanroute)
m = (60 * abs(deltafi)) / math.cos(route)

You have to convert the prob input (and all the other inputs) into int as it is considered a string by default: prob = int(input("...")).
You can also verify this by simply printing type(prob).

Input in python receives the value as string, and you are comparing it to integer value in your if condition
update your input statement to the following line to receive integer input:
prob = eval(input("1 or 2"))

Input method interpret your data as string, not as integer.
In your if condition you've to put
if int(prob) == 1:

Related

my decoration sometimes appears just outside the triangle

It seems that my decoration sometimes appears just outside the triangle... How can I fix this?
import random
n = int(input('enter n: '))
x = 1
for i in range(n):
if i == 0:
count = 0
else:
count = random.randint(0, x)
print(' ' * (n - i), '*' * count, end = '')
if i == 0:
print('&', end = '')
else:
print('o', end = '')
print('*' * (x - count - 1))
x += 2
What do I get for value n = 10:
&
***o
*o***
o******
******o**
*********o*
*************o
*****o*********
*************o***
******************o
The random number you generate may return x as randint includes the second value in the set of possible values. So pass x - 1 to randint:
count = random.randint(0, x - 1)
It is also a pity that you have a check for i == 0 in your loop. In that case, why not deal with that first case outside of the loop, and start the loop at 1? It will make your code a bit more elegant.
def tree(n):
from random import sample
body = ["&"] + ["".join(sample("o" + "*" * (k:=x*2+1), k=k)) for x in range(1, n)]
spaces = [" " * (x-2) for x in range(n, 1, -1)]
return "\n".join("".join(tpl) for tpl in zip(spaces, body))
print(tree(10))
Output:
&
o**
****o
o******
*******o*
********o**
*******o*****
**************o
o****************
I love christmas tress! This is my take on the question :-)
import random
n = int(input('Enter tree height: '))
print(" " * (n-1) + "&")
for i in range(2, n+1):
decoration = random.randint(1, (i-1)*2 -1)
print(" " * (n - i) + "*" * decoration + "o" + "*" * ((i-1)*2 - decoration))
Enter tree height: 12
&
*o*
**o**
*o*****
*o*******
********o**
*******o*****
***********o***
********o********
****************o**
***o*****************
*********o*************

Getting Invalid syntax on a correct line of syntax [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am getting an invalid syntax error when I run this code, but when i checked the line of the error, it seems to be correct. This is a code meant to calculate parts of parabolas.
def PCalculator():
print("What are you missing?")
print("D for directrix")
print("F for focus")
print("V for vertex")
inp = input("Answer D, V, or F: ").lower()
if inp == "v":
fx = input("What is the X value of the focus? ")
fy = input("What is the Y value of the focus? ")
d = input("What is the Y value of the directrix? ")
ptlst = [fx, fy, d]
stopper = 1
for x in ptlst:
if (x.strip("-")).isnumeric() == False:
stopper = 0
if stopper == 1:
fx = int(fx)
fy = int(fy)
d = int(d)
vy = fy - ((abs(fy - d)/2)
print("The vertex is (" + str(fx) + ", " + str(vy) + ")") #this is where I am having the error
elif inp == "f":
vx = input("What is the X value of the vertex? ")
vy = input("What is the Y value of the vertex? ")
d = input("What is the Y value of the directrix? ")
ptlst = [vx, vy, d]
stopper = 1
for x in ptlst:
if (x.strip("-")).isnumeric() == False:
stopper = 0
if stopper == 1:
vx = int(vx)
vy = int(vy)
d = int(d)
fy = vy + (abs(vy - d))
print("The focus is (" + str(vx) + "," + str(fy) + ")")
else:
print("ERROR: Letter detected")
PCalculator()
You have an extra opening bracket on this line:
vy = fy - ((abs(fy - d)/2)

why do I keep getting a bad input error on line five? are my variables alright? the declaration of function?

here is my code
def computepay(h,r):
if h>40.0:
OT = 1.5*float(r)
p=OT
else:
ck = float(h)*float(r)
p=ck
return 'p'
hrs = input("Enter Hours:")
rate = input("Enter rate:")
h = float(hrs)
r = float(rate)
p = computepay(h,r)
print("Pay", p)
here are the parameters it needs to fill
4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function.
here is the sample code given
def computepay(h, r):
return 42.37
hrs = input("Enter Hours:")
p = computepay(10, 20)
print("Pay", p)
i've tried messing with indentation several times also removing else statement entirely
can I get some advice?
instead of return 'p' in line 8 of your code...
type return p so that it returns the variable instead of a string.
def computepay(h,r):
if h > 40.0 :
reg = r * h
OT = (h - 40.0) * (r * 0.5)
p= reg + OT
else:
p = h * r
return p
hrs = input("Enter Hours:")
rate = input("Enter rate:")
fh = float(hrs)
fr = float(rate)
p = computepay(fh,fr)
print("Pay",p)
def computepay(h,r):
if h>40.0:
p = 40.0*r
p = p + (h-40.0)*1.5*r
else:
p = h*r
return p
hrs = input("Enter Hours:")
rate = input("Enter rate:")
h = float(hrs)
r = float(rate)
p = computepay(h,r)
print("Pay", p)
my code:
def computepay():
mhours = (h - 40) * (r * 1.5) + uhours*r
return mhours
uhours = 40
try:
hours = input("Enter Hours please: ")
rate = input("Enter Rate per hours please: ")
h = float(hours)
r = float(rate)
if h <= uhours:
print('Pay', h * r)
elif h > uhours:
print('Pay', computepay())
except ValueError:
print('Please Enter a Number! not a word!')

Trying to do a cosine rule formula in python however not giving the expected output

If I select missing angle function and put for example a = 10, b = 10, c = 10, the expected output is 60 degrees for the angle, however the output from the program is 0.1546...
import math, sys
def missingAngle():
sideA = int(input("size of side a = "))
sideB = int(input("size of side b = "))
sideC = int(input("size of side c = "))
answer = math.acos((sideB**2 + sideC**2 - sideA**2) / (2 * sideB * sideC))
return answer
def missingSide():
angleA = int(input("size of angle A = "))
sideB = int(input("size of side b = "))
sideC = int(input("size of side c = "))
answer = math.sqrt(sideB**2 + sideC**2 - 2 * sideB * sideC * math.cos(angleA))
return answer
missingSideOrAngle = input("Are you trying to work out the missing angle or side?(Angle/Side) = ")
while True:
if missingSideOrAngle.title() == "Angle":
print("Your answer is = " + str(missingAngle()))
sys.exit()
elif missingSideOrAngle.title() == "Side":
print("Your answer is = " + str(missingSide()))
sys.exit()
else:
missingSideOrAngle = input("Please enter a valid string(Angle/Side) = ")
I never could reproduce the error that yielded the erroneous 0.1546.
Here is your program with a few tweaks that will help you towards expanding the programs' abilities:
import math
def missingAngle():
sideA = float(input("size of side a = "))
sideB = float(input("size of side b = "))
sideC = float(input("size of side c = "))
try:
answer = math.acos((sideB**2 + sideC**2 - sideA**2) / (2 * sideB * sideC))
return f'Your answer is: {math.degrees(answer):.2f} degrees'
except ValueError:
return 'Values given cannot form a triangle'
def missingSide():
angleA = math.radians(float(input("size of angle A (degrees) = ")))
sideB = float(input("size of side b = "))
sideC = float(input("size of side c = "))
answer = math.sqrt(sideB**2 + sideC**2 - 2 * sideB * sideC * math.cos(angleA))
return f'Your answer is: {answer:.2f} units'
while True:
missingSideOrAngle = input("Are you trying to work out the missing angle or side?(Angle/Side) = ")
if missingSideOrAngle.title() == "Angle":
print(missingAngle())
elif missingSideOrAngle.title() == "Side":
print(missingSide())
else:
missingSideOrAngle = input("Please enter a valid string(Angle/Side) = ")
I made it an actual loop, so it will let the user run scenarios endlessly until they hit Ctrl-C or enter something that raises an unhandled error. I have not tried to account for all possible errors.
The missingAngle is made to return degrees. It also includes a ``'try-except``` block to catch the error that will occur if the three sides cannot form a real triangle (eg: 12, 45, 85). The inputs are cast to floats, so the user may enter decimals of distance or angles, and the returns are formatted to render to 2 decimal places.
This should help you on your way. You may want to design error handling for user inputs to the number fields that are not numbers, and run some tests on the missingSide to see what can go wrong with user inputs and catch these. One you might want to experiment with is giving it an angle of 180. Some values may not yield an actual error, but may yield unexpected results.
Good Luck!

Loop to add more input

I have 3 more cars that I have but I need to know how to loop things like the car input so it will allow you to input it again if you do the wrong input same thing with the extras so they have to be either 1 or 0.
print("===================================================")
print("==============Car Finance Calculations=============")
print(" Choose your veicle: ")
print(" SUV type 1 ")
print(" Hatch type 2 ")
print(" Sedan type 3 ")
print("===================================================")
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
if caaaaaaaar == 1:
carsvalue = int(input("Please enter you cars value: "))
residual = carsvalue * 0.30
financing = carsvalue - residual
print(" financing value for the car is: ", round(financing,2))
print(" Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r*((r+1)**n))/(((r+1)**n)-1))
print(" Your Montly financing rate is: ", round(Financingcost,2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
print(" If you would like fuel type 1 if not type 0")
print(" If you would like insurance type 1 if not type 0")
print(" if you would like Maintenance type 1 if not type 0")
print("======================================================")
if caaaaaaaar == 1:
x, y, z = [int(x) for x in input("Enter Your extras with spaces:").split()]
print("=======================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost,2))
if x == 0:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost,2))
if y ==0:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ",insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost,2))
if z == 0:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ",maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras,2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING,2))
You want to use a while loop.
Like this:
carsEntered = 0
while (carsEntered <= 4):
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
carsEntered += 1
You could also use a for loop instead but that depends on what you want to do.
As per my understanding of the question you want to run an iteration until the user gives the right answer.
In that case, you can use flag variable in while.
flag = False
while(flag is False):
if(condition_statisfied):
flag = True
I suggest that you put your vehicle types in a dictionary:
vehicle_type_dict = {
1: "SUV type",
2: "Hatch type",
3: "Sedan type"
}
and do a while-loop to check if your input is in the dictionary:
while True:
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
if caaaaaaaar not in vehicle_type_dict:
continue #loop again if input not in the dictionary
#read next line of code if input is in the dictionary
#do something below if input is correct
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
break #end loop
My recommendation is to take a functional approach to this problem. You are calling int(input()) multiple times and want to validate the user input before proceeding on to the next lines each time. You can do this in a function that will continue to loop until the input is confirmed as valid. Once the input is validated, you can exit the function's frame by returning the value using the return key word.
# This is the function definition.
# The code in this function does not execute until the function is called.
def prompt_int(
text,
minimum=0,
maximum=1,
error="The value you entered is not valid try again."
):
# when the function is called it will start a second while loop that will keep looping
# until valid input is entered
while True:
try:
val = int(input(text))
if minimum <= val <= maximum:
return val
raise ValueError
except ValueError:
print(error)
# This is the outer while loop. It will keep looping forever if the user so chooses.
while True:
# instead of calling print() a bunch one option is to assign a docstring to a variable
car_prompt = '''
===================================================
==============Car Finance Calculations=============
Choose your veicle:
SUV: 1
Hatch: 2
Sedan: 3
===================================================
Please enter the number for the car you want to finance or 0 to exit:\n
'''
# This is where we first call the function.
# Our docstring will be passed into the function to be used as a prompt.
# We also pass in some args for maximum and minimum params
caaaaaaaar = prompt_int(car_prompt, 0, 3)
# 0 is false so we can exit the while loop if the user enters 0
if not caaaaaaaar:
break
year_prompt = "Enter years of the car loan (3, 4 or 5):\n"
years = prompt_int(year_prompt, 3, 5)
if caaaaaaaar == 1:
val_prompt = "Please enter you cars value:\n"
carsvalue = prompt_int(val_prompt, 0, 2147483647)
residual = carsvalue * 0.30
financing = carsvalue - residual
print("Financing value for the car is: ", round(financing, 2))
print("Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r * ((r + 1) ** n)) / (((r + 1) ** n) - 1))
print(" Your Montly financing rate is: ", round(Financingcost, 2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
x = prompt_int("If you would like fuel type 1 else type 0:\n")
y = prompt_int("If you would like insurance type 1 else type 0:\n")
z = prompt_int("If you would like Maintenance type 1 else type 0:\n")
print("======================================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost, 2))
else:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost, 2))
else:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ", insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost, 2))
else:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ", maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras, 2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING, 2))
elif caaaaaaaar == 2:
# Put your code for car 2 in this block.
# If it is like car 1 code except the value of a few variables
# then make another func
pass
else:
# Car 3 code...
pass

Categories

Resources