if-else statement not running elif- or else- clauses [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
I am using Python in an attempt to create an Area Calculator (similar to the one from Code Academy). Only my else statement seems to be running:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer == "Circle" or "C" or "c" or "circle":
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer == "Triangle" or "T" or "t" or "triangle":
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
I edit texts using PyCharm and no syntax errors or errors of any other kind return. Regardless of what I respond into the answer input (whether they are integers or syntax) the code always displays line 8 [radius = float(input("Input Radius: "))]
I am sorry if this turns out to be an easy fix. I am just getting started with Python and have tried a variety of indentation and syntactical variations to no avail.

Use:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer.lower() in {"circle","c"}:
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer.lower() in {"triangle","t"}:
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")
The changes are the lines with or, use in instead so checks by the set
That's what's different.
Note use lower for simplifying the length
Note use set for speed, (it's faster)

You are using the == operator incorrectly. You have to use it this way:
if answer == "Circle" or answer == "C" or answer == "c" or answer == "circle":
An easier way to do this will be to using check whether your string matches any of the items in a tuple or list. So your code will need to be modified like this:
print("Area Calculator.")
print ("Select Shape:")
print ("Circle or Triangle? ")
answer = input()
if answer in ("Circle", "C", "c", "circle"):
radius = float(input("Input Radius: "))
area_c = (3.12159 * radius) * 2
print (area_c)
elif answer in ("Triangle", "T", "t", "triangle"):
base = float(input("Input Base: "))
height = float(input("Input Height: "))
area_t = (.5 * base) * height
print (area_t)
else:
print ("error")

if answer == "Circle" or answer == "C" or answer == "c" or answer == "circle":

Related

Nestes if's in python not working and math module faulty

in this code i first ask the user for the trigonometric function and then ask for the angle in radians or degrees. according to the code, the console should print error, but on running the code, the first if statements accept any input as true.the final coputed value is also worng. please suggest what to do and any other relevant changes that can be made to the code.
from math import *
trigFunc = str(input("What function do you want to use? Sine, Cosine or Tangent: "))
if trigFunc.lower == "sine" :
radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
if radOrDeg.lower == "radians" :
angle = int(input("Please input the value of the angle: "))
print(math.sin(angle))
elif radOrDeg.lower == "degrees" :
angle = int(input("Please input the value of the angle: "))
radAngle = int(math.radians(angle))
print(math.sin(radAngle))
else:
print("error")
elif trigFunc.lower == "cosine" :
radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
if radOrDeg.lower == "radians" :
angle = int(input("Please input the value of the angle: "))
print(math.cos(angle))
elif radOrDeg.lower == "degrees" :
angle = int(input("Please input the value of the angle: "))
radAngle = int(math.radians(angle))
print(math.cos(radAngle))
else:
print("error")
elif trigFunc.lower == "tangent" :
radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
if radOrDeg.lower == "radians" :
angle = int(input("Please input the value of the angle: "))
print(math.tan(angle))
elif radOrDeg.lower == "degrees" :
angle = int(input("Please input the value of the angle: "))
radAngle = int(math.radians(angle))
print(math.tan(radAngle))
else:
print("error")
else:
print("ERROR, the function cannot be used")
input("press enter to exit")
.lower is a function and you need to call it to return a string. Right now you are comparing a function to a string which will return False.
Change trigFunc.lower to trigFunc.lower().
https://docs.python.org/3/library/stdtypes.html#str.lower
There are several errors in your code. Here are the things I changed to get your code working:
Use trigFunc.lower() instead of trigFunc.lower. You need to call the method to get the result you desire.
Use import math instead of from math import *, since you refer to math library throughout.
Use math.radians(int(angle)) instead of int(math.radians(angle)), since math.radians does not take a string as an input.

How to make my code ask the user for input again python

I'm creating a python program that gives you the area for any shape you enter and I want to know how to make the program return to asking the user what shape they want
import math
user_choice = input("Choose a shape")
if user_choice == "rectangle" or "square":
a = input("enter your length in centimeters here")
b = input("enter your width in centimeters here")
area = int(a) * int (b)
print(area, "cm²")
else
print"Sorry, you may have made a spelling error, or have chose a shape that we cannot calculate. Please try again"
#Code that returns to first question here?
Also if possible, since the code is very long because it is just repeating the if statements as elif statements for new shapes, is there a way to shorten it so it isn't lots of elif statements.
Thanks
import math
done = 'n'
while done == 'n':
user_choice = input("Choose a shape")
if user_choice == "rectangle" or "square":
a = input("enter your length in centimeters here")
b = input("enter your width in centimeters here")
area = int(a) * int (b)
print(area, "cm²")
else
print("Sorry, you may have made a spelling error, or have chose a shape that we cannot calculate. Please try again")
done = input("Done? (Y/N)").lower()

Looping in Python

I'm trying to figure a way to loop this code so that it restarts once all three of the calculations are complete. I have figured a way to restart the program itself, however I can't manage to restart it so that it returns back to the first calculation step. Anyone can help a brother out? Thanks in advance.
The code that I have used to restart the program:
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
answer = input("Do you want to restart this program?")
if answer.lower().strip() in "y, yes".split():
restart_program()
My program without the restart code:
import math
import sys
import os
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
You could put everything in a while loop which could repeat forever or until a user types a certain phrase.
import math
import sys
import os
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
while True:
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
or
while answer.lower() in ("yes", "y"):
//code
answer = input("Would you like to repeat?")
You could also put it all into a function def main(): and then do some form of recursion (calling a function in itself).
Those are just a few ways. There are a ton of ways you can get what you want.
Just Have the function loop on itself. Restarting the shell isn't necessary.
import math
import sys
import os
def calc():
print ("This program will calculate the area, height and perimeter of the Triangles: Scalene, Isosceles, Equilateral and a Right Angled Triangle.")
# calculate the perimeter
print ("Please enter each side for the perimeter of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
perimeter = (a + b + c)
print ("The perimeter for this triangle is: " ,perimeter)
# calculate the area
print ("Please enter each side for the area of the triangle")
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c "))
s = (a + b + c) / 2
sp = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 #area = math.sqrt(sp*(sp - a)*(sp - b)*(sp - c))#
print ("The area for this triangle is %0.2f: " %area)
# calculate the height
height = area / 2
print ("The height of this triangle is: ", height)
if __name__ == "__main__":
answer = input("Do you want to restart this program?")
if answer.lower().strip() in "y, yes".split():
calc()
else:
exit()
calc()
If the answer is yes, then the function is called and everything repeats. If the answer is not yes then the program exits.
This should do.
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
while input("Do you want to restart this program?").lower().strip() in "y, yes".split():
restart_program()

Random Maths Program

thanks for taking time to read this.
I have to create a program that generates 10 random maths questions based around =, - and *. I have the program working but everytime I run it after the main program it prints "none" even though that's not in my program.Any help at all would be much appreciated. Thank you.
import random
print ("Welcome")
name=input("What's your name?")
print("Nice to meet you", name, ",you will be given 10 multiplication, addition and subtraction questions.")
Num1 = random.randint(1,12)
Num2 = random.randint(1,12)
sign = random.randint(1,3)
if sign == 1: # If the random number generated is 1
question = Num1 + Num2
rightanswer1 = Num1 + Num2
answer1=input(print("What is", question ,"?"))
if answer1 == rightanswer1:
print("Well Done!")
if answer1 != rightanswer1:
print("Sorry, that's incorrect, the answer was", rightanswer1)
if sign == 2:
question = Num1 - Num2
rightanswer2 = Num1 - Num2
answer2=input(print("What is", Num1, "-", Num2 ,"?"))
if answer2 == rightanswer2:
print("Well done!")
elif answer2 != rightanswer2:
print("Sorry, that's incorrect, the answer was", rightanswer2)
if sign == 3:
question = Num1 * Num2
rightanswer3 = Num1 * Num2
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
if answer3 == rightanswer3:
print("Well done!")
elif answer3 != rightanswer3:
print("Sorry, that's incorrect, the answer was", rightanswer3)`
> Welcome
> What's your name? John
> Nice to meet you John ,you will be given 10 multiplication, addition and subtraction questions.
> What is 12 x 3 ?
> None 36
> Sorry, that's incorrect, the answer was 36
I think you are using python 3. In python 3 input is like raw_input in python 2. So you get the string as input. So convert it into int
var = int(input("Enter a number: "))
So in your code make it as
print("What is", Num1, "x", Num2 ,"?")
answer3 = input()
answer3 = int(answer3)
See this:
whats-the-difference-between-raw-input-and-input-in-python3-x
I'm reluctant to just give you an answer that just does it for you, so instead i'll provide you with a few hints to improve things. (i.e. this isn't an answer, just too large of a comment - and more like a codereview answer)
First off, you use a structure like this:
if x == 1:
#do something
if x == 2:
#do something else
...
In this case, which it makes no difference, it is easier to read if you use the if syntax as intended:
if <condition>:
#do this if the above test is true.
elif <more conditions>:
#do this only if the first test is false and this one is true
elif <more conditions>:
#same as above, except for the second test must be false too
else:
#do this if all the above tests are false
So you could use this something like:
if sign == 1:
...
elif sign == 2:
...
elif sign == 3:
...
else:
# something weird happened...
Which would make that section of the program easier to follow.
The same thing can be done with the if answer1 == rightanswer1: sections;
if answer1 == rightanswer1:
#correct!
else:
#incorrect.
That would be a clearer was to do it. You seem to have used the if...elif style in a couple of them, but not the first one.
Once you have this, it will be a little clearer.
The next way you could improve things is by removing duplicated code. You don't need separate branches for each sign, you can just roll it all into one:
number1 = randint(1,12)
number2 = randint(1,12)
op = randint(1,3)
question_string = "%d %s %d = ?" % (number1, number2, ["+", "-", "*"][op])
result = None
if op == 1:
result = number1 + number2
elif op == 2:
result = number1 - number2
elif op == 3:
result = number1 * number2
This will do most of the logic for you, and generate the strings you want, without duplicating all of the other code.
Small changes like this can make things much more readable.
It's printing None because the print() function returns None and you're passing that value of None from print() as the prompt to your input() functions. Eg,
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
So print("What is", Num1, "x", Num2 ,"?") prints its stuff, and returns None, which then gets printed as the prompt by input().
A simple way to fix this is to just move your print() function calls out of your input() functions.
Eg,
print("What is", Num1, "x", Num2 ,"?")
answer3=input()
However, there's another major problem with your program: the rightanswer variables are ints, but the inputted answers are strings. To compare them properly they need to be the same type. So you should either convert the inputted answers to int, or alternatively, convert the rightanswers to str.
There are two problems with how you use the input function:
You misuse the prompt argument
You forget to convert the result
First, have a better look at the reference of the input function
The prompt argument
input takes a string as argument that will be displayed ("prompted") to the user to indicate that the program is waiting an input. The print function also displays a string to the user, but it doesn't return anything. It does its job and that's all (and in Python a function that returns nothing, returns None). That's what input gets to display, so it displays None. You should use format instead. It will format and return the formatted string that input can display:
answer1_as_str=input("What is {} ?".format(question))))
or
answer2_as_str=input("What is {:d} - {:d} ?".format(Num1, Num2)))
The return value
input returns the user input as a string contrary to python 2 (i.e. exactly as entered). So you have to convert the input to the desired type if you need it. If you type 10 for example, the input will return "10". If you need an int, you have to convert it yourself.
answer1 = int(answer1_as_str)
It looks like you don't really understand how input() works. You might also want to review the different datatypes and conditional statements. Other than that, it was a very good attempt. Here's my solution:
from random import randint
print("Welcome")
name = input("What's your name?\n")
print("Nice to meet you " + name + ", you will be given 10 multiplication, addition and subtraction questions.")
for i in range(10):
print("\nProblem " + str(i+1))
num1 = randint(1,12)
num2 = randint(1,12)
sign = randint(1,3)
if sign == 1:
question = str(num1) + " + " + str(num2)
answer = num1 + num2
elif sign == 2:
question = str(num1) + " - " + str(num2)
answer = num1 - num2
else:
question = str(num1) + " x " + str(num2)
answer = num1 * num2
user_answer = input("What is " + question + "? ")
if user_answer == str(answer):
print("Well done!")
else:
print("Sorry, that's incorrect, the answer was", answer)

Text menu doesn't print properly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The Problem has been solved. However, my account is new, so it won't let me answer the question. It seems that changing the instances of input() with raw_input() makes it work. I honestly have no clue why, but it may have something to do with the differences between 2 and 3.
I'm supposed to make a program that can calculate area and circumference. That part hasn't been so difficult.
However, the menu isn't working. The first part of the menu works just fine, but after you make a selection, it doesn't print what it's supposed to.
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if ans == "1":
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == "2":
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == "0":
print("Thanks for hanging out with me!")
quit()
After indenting properly, change if ans == "1" to str(ans) == "1" or ans == 1 and it should be fine.
This should work:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if str(ans) == "1":
diameter = input("Enter the diameter: ")
print diameter
if float(diameter) > 0.0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
....
PS: As mentionned in the comments, it works, but it is disgusting. We should only use ans == 1 or modify input to input_raw if you use python < python 3
Your code's indentation shows the span of control of each 'if', 'for', or 'while'.
You need to further indent the instructions under each major 'if' statement so that
they only get executed when that 'if' statement is selected. Otherwise, everything
that is at the leftmost indentation gets executed every time through the loop. For example, you should have something like:
if answer == '1':
....<statements that execute under condition 1>
elif answer == '2':
....<statements that execute under condition 2>
where I have emphasized the indentation with '....'.
The second if statement is not within the brackets of the first. this is true for both 1 and 2.
if ans == "1";
diameter = float(input("enter the diameter: "))
if diameter ....
for me treating ans as integer worked. What I mean by treating ans as integer is instead of writing ans=="1" ,I wrote ans==1.it print corret cvalue. Check this code:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
print ans
if ans ==1:
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == 2:
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == 0:
print("Thanks for hanging out with me!")
quit()

Categories

Resources