Refactoring While & If loop of a code with Python? - python

Hi I'm learning Python by myself and I'm tying to refactor this code. I need to use declaration and invoke of the function.
So the original code is:
while True:
length = int(input("Enter the length of your room: "))
if length > 0:
break
while True:
width = int(input("Enter the width of your room: "))
if width > 0:
break
while True
height = int(input("Enter the height of your room: "))
if height > 0:
break
print("The volume of your room is", length * width * height)
What I'm doing so far (I'm not sure if it's good or not). Any suggestions?:
def volume(length, width, height)
length= int(input("Enter the length of your room: "))
while (length = 0):
print(f"The length of your room is invalid)
return
width = int(input("Enter the width of your room: "))
while (width = 0):
print(f"The width of your room is invalid)
return
height = int(input("Enter the height of your room: "))
while (height = 0):
print(f"The height of your room is invalid)
return
print("The volume of your room is", length * width * height)
return
volume(length*width * height)

Code:
def volume(lenght, width, height):
if lenght > 0 and width > 0 and height > 0:
room_volume = lenght*width*height
return room_volume
return 'wrong input'
room_volume = volume(input('Length: '), input('Width: '), input('Height: '))
print(f'Room volume: {room_volume}')
You can check if argument value is greater than 0 just by one simple if statement, no need for these while loops.

Related

Print statement inside an if block never executes? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last month.
Here is the code:
print("Welcome to the weight maintenance calculator!")
startWeight = float(input("Input your start weight, in kilograms: "))
height = float(input("Enter your height in centimetres: "))
sex = input("Enter your sex (M/F): ")
age = float(input("Enter your age: "))
dailyActivity = input("Rank your activity level, from 0-5: ")
if ((sex == "M") or (sex == "m")):
startWeightBmr = int((10 * startWeight) + (6.25 * height) - (5 * age) + 5)
if (dailyActivity == 0):
caloriesUsedCurrently = startWeightBmr + 300
print(caloriesUsedCurrently)
if (dailyActivity == 1):
caloriesUsedCurrently = startWeightBmr + 350
print(caloriesUsedCurrently)
if (dailyActivity == 2):
caloriesUsedCurrently = startWeightBmr + 400
print(caloriesUsedCurrently)
Anyway, if you run it, you'll see the issue quite clearly - no matter what number you put in (0, 1 or 2) for the dailyActivity variable, caloriesUsedCurrently is never printed. I'm wondering if there's something wrong with the if blocks, and whether or not they're being executed at all. Could someone please guide me on this one? It will run, so there's no error message, which makes it all the more confusing. Please help!
I tried running this in IDLE to see if it was VSCode that was the issue, but nope, as I suspected it was my code. Running it in IDLE did nothing.
Try:
dailyActivity = int(input("Rank your activity level, from 0-5: "))
Code:
print("Welcome to the weight maintenance calculator!")
startWeight = float(input("Input your start weight, in kilograms: "))
height = float(input("Enter your height in centimetres: "))
sex = input("Enter your sex (M/F): ")
age = float(input("Enter your age: "))
dailyActivity = int(input("Rank your activity level, from 0-5: "))
if ((sex == "M") or (sex == "m")):
startWeightBmr = int((10 * startWeight) + (6.25 * height) - (5 * age) + 5)
if (dailyActivity == 0):
caloriesUsedCurrently = startWeightBmr + 300
print(caloriesUsedCurrently)
if (dailyActivity == 1):
caloriesUsedCurrently = startWeightBmr + 350
print(caloriesUsedCurrently)
if (dailyActivity == 2):
caloriesUsedCurrently = startWeightBmr + 400
print(caloriesUsedCurrently)
Output:-
Welcome to the weight maintenance calculator!
Input your start weight, in kilograms: 60
Enter your height in centimetres: 162
Enter your sex (M/F): m
Enter your age: 19
Rank your activity level, from 0-5: 2
1922

Area/Type of triangle python

I'm supposed to find a code that asks the user for the base, height, and side of a triangle and then tells the user "This (type) triangle has an area of (area)" and then keeps asking the user for more numbers until they decide to quit. The code I have so far is...
again = "y"
while again != "n":
base = int(input("Enter base: "))
height = int(input("Enter height: "))
side1 = int(input("Enter side 1: "))
side2 = int(input("Enter side 2: "))
side3 = int(input("Enter side 3: "))
area = (base*height) / 2
certain_type = []
if side1 == side2 == side3:
print("Equilateral triangle")
elif side1==side2 or side2==side3 or side1==side3:
print("isosceles triangle")
else:
print("Scalene triangle")
print('This %f of the triangle is %0.2f' %area, certaintype)
Well done, so a few comments...
(1) indentation throws it off because the entire code should be under the while loop, so that your entire game will repeat itself after every triangle
(2) Instead of directly printing the "isosceles", "scalene" etc, "certaintype" ...you can store the value (eg scalene) under the certaintype variable using certaintype='scalene'. That way, you can print the type of triangle in your sentence later.
(3) The final print should also be under the while loop as you want to tell your users the answer after every triangle information entry.
(4) The syntax for string interpolation is %s for string variables like certaintype while the syntax for number/decimals is %d for number variables like area. Check out how I rewrote the final print line.
Somethig like this should work:
while again != "n":
base = int(input("Enter base: "))
height = int(input("Enter height: "))
side1 = int(input("Enter side 1: "))
side2 = int(input("Enter side 2: "))
side3 = int(input("Enter side 3: "))
area = (base*height) / 2
certain_type = []
if side1 == side2 == side3:
certaintype = "Equilateral triangle"
elif side1==side2 or side2==side3 or side1==side3:
certaintype = "isosceles triangle"
else:
certaintype = "Scalene triangle"
print('This %d of the triangle is %s' % (certaintype, area) )

Loop for shape calculator

I need to add a loop to the code in order to allow the user to restart the programme and choose another of the available shapes.
import math
import time
shapearea = 0
pi = 3.14159
print("Select shape\n1.Square\n2.Circle\n3.Triangle")
shape = input("Enter shape(Square/Circle/Triangle):")
if shape == "square":
sideval = int(input("Enter side value of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(sideval ** 2)
elif shape == "circle":
circleradius = int(input("Enter radius value of the circle:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(pi * circleradius **2)
elif shape == "triangle":
height = int(input("Enter the height of the shape:"))
base = int(input("Enter the base of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(base*height/2)
else:
print("The given shape is invalid, give a valid shape to calculate the area")
print ("The area of the chosen shape is " "%.2f" % shapearea)
try this maybe this could help you:
import math
import time
def calculate():
shapearea = 0
pi = 3.14159
print("Select shape\n1.Square\n2.Circle\n3.Triangle")
shape = input("Enter shape(Square/Circle/Triangle):")
if shape == "square":
sideval = int(input("Enter side value of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(sideval ** 2)
elif shape == "circle":
circleradius = int(input("Enter radius value of the circle:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(pi * circleradius **2)
elif shape == "triangle":
height = int(input("Enter the height of the shape:"))
base = int(input("Enter the base of the shape:"))
print("Calculating...")
#time.sleep(2)
shapearea = shapearea +(base*height/2)
else:
print("The given shape is invalid, give a valid shape to calculate the area")
print ("The area of the chosen shape is " "%.2f" % shapearea)
calculate()
while input("Do you want to continue?(Y/N)") == "Y":
calculate()
print("exiting from program...")

Multiply & Divide Non-type and int in Python

So I am writing a simple program that calculates your BMI. I am running into an issue when it is time to calculate the BMI by taking the returned values of weight and height (it acts as if there is no value being returned). This code use to work when I had all modules in one function, since I have divided all functions into separate modules I have run into this issue.
> Error:
> Traceback (most recent call last):
> File "C:/OneDrive/Documents/3.py", line 43, in <module>
> bmi = calcBMI(weight, height)
> File "C:/OneDrive/Documents/3.py", line 17, in calcBMI
> bmi = float(weight * 703 / (height * height))
> TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
Here's my code:
##########
# Functions
##########
def getweight():
weight = float(input('Enter your weight in LBs: '))
if weight <= 0 or weight > 1000:
print('Weight cannot be less than 0 or greater than 700')
return weight
def getheight():
height = float(input('Enter your height in inches: '))
if height <= 0:
print('Height cannot be less than 0')
return height
def calcBMI(weight, height):
bmi = float(weight * 703 / (height * height))
return bmi
def printData(name, bmi):
print(name)
print('Your BMI is %.2f' % bmi)
if bmi >= 18.5 and bmi <= 24.9:
print('Your BMI is normal')
elif bmi <= 18.5:
print('Your BMI is underweight')
elif bmi >= 25 and bmi <= 29.9:
print('Your BMI is overweight')
elif bmi >= 30:
print('**Your BMI is obese**')
#####################
# Beginning of program
#####################
print("Welcome to the Body Mass Index Calculator")
name = input('Enter your name or 0 to quit: ')
# beginning of loop
while name != "0":
height = getheight()
weight = getweight()
bmi = calcBMI(weight, height)
printData(name, weight, height, bmi)
name = input('Enter another name or 0 to quit: ')
print("Exiting program...")
For a start, you are only returning height if it is less than 0. You would want to remove the return statement from within the if block.
You probably also want to create some logic to deal with an incorrect height being entered, such as raising an exception, or returning the user to the prompt.
def getweight():
weight = float(input('Enter your weight in LBs: '))
if weight <= 0 or weight > 1000:
print('Weight cannot be less than 0 or greater than 700')
#Some code here to deal with a weight less than 0
return weight
def getheight():
height = float(input('Enter your height in inches: '))
if height <= 0:
print('Height cannot be less than 0')
#Some code here to deal with a height less than 0
return height
One way of dealing with incorrect weights would be:
def getweight():
while True:
weight = float(input('Enter your weight in LBs: '))
if weight <= 0 or weight > 1000:
print('Weight cannot be less than 0 or greater than 700')
else:
return weight
You may want to limit this to a certain number of iterations - up to you.
Neither getheight nor getweight necessarily returns a number (i.e. when the if fails); in such cases, it returns None.

Expected an indented block [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 6 months ago.
I'm getting an Expected an indented block here's the code, thank you for any help.
#Given the menu the user will calculate the area of square, circle, rectangle
from math import pi
def main ():
#declare and initialize variables
#float radius = length = width = base = height = 0.0
radius = length = width = base = height = 0.0
#float areaCircle = areaRectangle = areaTriangle = 0.0
areaCircle = areaRectangle = areaTriangle = 0.0
#int menuChoice = 0
menuChoice = 0
#display intro
while menuChoice != 4:
#Display menu
print("Geometry Calculator")
print("1) Calculate the Area of a Circle")
print("2) Calculate the Area of a Rectangle")
print("3) Calculate the Area of a Triangle")
print("4) Quit")
#Prompt for menuChoice
if menuChoice == 1:
while radius < 0:
#prompt for radius
radius = eval(input("What is radius of circle: "))
if radius < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaCircle
areaCircle = pi*r**2
#display areaCircle
print("The area of the circle is: ", areaCircle)
elif menuChoice == 2:
while length < 0:
#prompt for length
length = eval(input("What is the length of the rectangle: "))
if length < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
while width < 0:
#prompt for width
width = eval(input("What is the width of the rectangle: "))
if width < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaRectangle
areaRectangle = length * width
#diplay areaRectangle
print("The area of the rectangle is: ", areaRectangle)
elif menuChoice == 3:
while base < 0:
#prompt for base
base = eval(input("What is the length of the base of the triangle:"))
if base < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
while height < 0:
#prompt for height
height = eval(input("What is height of triangle"))
if height < 0:
#display invalid
print("Invalid input. Cannot be a negative value.")
#calculate areaTriangle
areaTriangle = 1/2 * base * height
#display areaTriangle
print("The area of the triangle is: ", areaTriangle)
elif menuChoice == 4:
#display exit message
else:
#display invalid
print("You must choose a number between 1-4 from the menu")
The error pops up at else. I've tried indenting one at a time, probably something small i'm overlooking third week into programming.
You need some sort of placeholder for the final elif block. You may use the standard Python non-op, pass:
elif menuChoice == 4:
#display exit message
pass
I'm assuming this will eventually be replaced by some other code, so the problem would have resolved itself had you continued working. If you are not planning on putting anything in this block, omit it entirely. There is no need for a conditional branch that does nothing.
It's the last line (#display exit message). Add a correctly indented pass statement, until you know what to do here. You need an actual python statement here, not a comment.

Categories

Resources