Please mind I am very new to the Python world.
I've been looking for an answer to this online and can't seem to find the right solution, based on my understanding I feel the logic is correct. In the end, though my results are just not there.
I am compiling with Idle.
Point of the solution: Is to take a string value of Kilometers from the console. Then convert it to Miles, then output the string.
Seems simple but debugging the below code over and over again I cannot seem to figure out why after I enter my kilometer number the print with the conversion value never displays.
def main(distanceMile=None):
# Declare and initialize variables
# string called distancekilo
distanceKilo = ""
# distancemile = ""
# conversion = 0.6214
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
I would simply like to know where I am going wrong here?
Your code has three main bugs. One is the indentation at the end of calcConvert (return should be indented). Another is that the main definition at the top doesn't seem to do anything. Another is that you want to save calcConvert(distanceKilo) to a variable. This code works:
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
distanceMile = calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
If you're new to Python, I would suggest also reading some posts and articles about the way people normally style code (like calc_convert vs calcConvert) in Python :) It's not entirely necessary, but it makes it easier for other Python users to read your code.
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I am currently learning python and I was wondering if there is an easier way to validate user input. I am working on a Body Mass Index calculator. Even though the code is working, I feel like this is not the best practice and that there is an easier way to validate user input without using multiple while loops.
Right now my code is looking as follows.
print("#########################################################\n"
"############## Body Mass Index calculator ###############\n"
"#########################################################\n")
# asks user to input his height
height = input("Please enter your height in m: ")
# mechanism to check if the user input is valid input
while True:
# checks if the user input is a float
try:
float(height)
new_height = float(height)
break
# if the user input is not a float or a number, it prompts the user again for valid input
except ValueError:
print("Enter a valid height...")
height = input("enter your height in m: ")
print("")
continue
weight = input("Please enter your weight in kg: ")
while True:
# checks if the user input is a float
try:
float(weight)
new_weight = float(weight)
break
# if the user input is not a float or a number, it prompts the user again for valid input
except ValueError:
print("Enter a valid weight...")
weight = input("enter your weight in kg:")
print("")
continue
# calculating the body mass index
body_mass_index = new_weight / new_height**2
# printing out the result to the user
print("\nYour BMI is " + str(round(body_mass_index, 2)))
Repeated code like this is best put into a function. Here's an example.
def get_float_input(var, units):
while True:
value = input('enter your {} in {}: '.format(var, units))
try:
return float(value)
except ValueError:
print('Invalid entry!')
height = get_float_input('height', 'm')
weight = get_float_input('weight', 'kg')
There's a programming principle called DRY: Don't Repeat Yourself. If you have the same logic/functionality being utilized in multiple places, you should gather it into one place.
In addition to improving readability, this has the benefit of making your life a lot easier. As the great Larry Wall said (I'm paraphrasing), "The first great virtue of a programmer is laziness." Suppose you later wanted to make some change to the logic (for example, changing the message printed when the user enters an invalid string). With the DRY principle, you don't have to track down every single part in your code (which could be thousands of lines long) where you used this loop. Instead, you go to the one place where it's defined and make the change there. Presto!
I'm completely new to python, and I wanted to create a program that "loads" a number that the user would have entered.
To do this, I made a function with an input variable,
percentage
that I then tried to transform to an interfer,
percentage_int
To then put in a while loop.
However, I get an error message, why?
def loader():
percentage = input("what percentage do you want?")
percentage_int =int(percentage)
x = 0
print("Goal:{} %".format(percentage_int))
while x < percentage_int:
x+=1
print(x)
loader()
You need to do the type conversion, that is in this case from string to integer.
If you dont do so python will consider percentage_int as the input string itself.
percentage = input("what percentage do you want?")
percentage_int = int(percentage)
Go through this tutorial which will help you learn more about type conversions with python.
I have a very brief familiarity with coding in general, though a majority of my experience thus far has been with Python. Which is why it's upsetting that I can't seem to figure out how to do this...
I have an assignment in my Python class where I am required to compute the area of a right triangle. I have completed the assignment successfully, but I wanted to take it a step further and restrict the user from inputting anything but an integer as input. I've tried multiple ideas from what I learned on Codecademy, though I can't seem to figure it out. Any help would be greatly appreciated!
Here is the code I've written so far; it works fine for what it is, but I would like to have it return a string that says something like "Please enter a valid number" if the user were to type anything besides a number:
from time import sleep
import math
print("Let\'s find the area of a right triangle!")
sleep(2)
triangleBase = float(input("Enter the base value for the triangle: "))
print("Great!")
triangleHeight = float(input("Enter the height value for the triangle: "))
print("Great!")
sleep(2)
print("Calculating the area of your triangle...")
sleep(2)
def triangleEquation():
areaString = str("The area of your triangle is: ")
triangleArea = float(((triangleBase * triangleHeight) / 2))
print('{}{}'.format(areaString, triangleArea))
triangleEquation()
You are close. You noticed that your code raised an exception. All you need to do is catch that exception and prompt again. In the spirit of "don't repeat yourself", that can be its own function. I cleanup up a couple of other things, like your calculation function using global variables and converting things that don't need converting (e.g. 'foo' is a str, you don't need str('foo')) and got
from time import sleep
import math
def input_as(prompt, _type):
while True:
try:
# better to ask forgiveness... we just try to return the
# right stuff
return _type(input(prompt.strip()))
except ValueError:
print("Invalid. Lets try that again...")
def triangleEquation(base, height):
area = base * height / 2
print('The area of your triangle is: {}'.format(areaString, area))
print("Let\'s find the area of a right triangle!")
sleep(2)
triangleBase = input_as("Enter the base value for the triangle: ", float)
print("Great!")
triangleHeight = input_as("Enter the height value for the triangle: ", float)
print("Great!")
sleep(2)
print("Calculating the area of your triangle...")
sleep(2)
triangleEquation(triangleBase, triangleHeight)
This should get you started. I'll leave the rest for you (if you'd like to also allow floats, hint, hint), since you said you wanted to take it a step further, that way you'll still retain the sense of accomplishment.
def triangleEquation(triangleBase, triangleHeight):
if type(triangleHeight) == int and type(triangleBase) == int:
areaString = "The area of your triangle is: "
triangleArea = float(((triangleBase * triangleHeight) / 2))
return '{}{}'.format(areaString, triangleArea)
else:
return 'Integers only.'
Note: You could also use the is idiom: if type(triangleHeight) is int...
This may be a really basic question, but I'm kind of new to Python. I'm building a simple distance conversion tool and I'd like to have the user get the option to input a float or an int, depending on their measurement. Other than a billion if statements (one for each unit of measurement, like inches to centimeters or feet to meters), is there a decent way to do this?
EDIT: Here is a snippet of my code
#if imperial, offer choices of inch, foot, or mile
if disType == "i":
print """
What unit of measurement do you want to convert?
inches to centimeters: i
feet to meters: f
miles to kilometers: m
"""
unitType = raw_input(prompt)
#if unit is inches, prompt user for number of
#inches and convert to centimeters
if unitType == "i":
print "Please input distance in inches"
inches = int(raw_input(prompt))
centimeters = inches * 2.54
print "That is %i centimeters" % centimeters
If the user inputs a decimal, I want to be able to account for it. But I have one of these if statements for every conversion (six conversions in distance alone). I'd rather not add an if statement for each one that branches off in the case of a float.
You seem to have trouble in how to implement unit conversions without a bunch of if statements, right?
If I were you, I would do this:
conv_func = {
'inch': func_for_inch_conv,
'cm': func_for_cm_conv,
...
}
data = raw_input() # prompt the user to enter data in the form '1 inch'
mag, unit = data.split(' ')
result = conv_func[unit](mag)
I don't know whether this is a good way to solve it, but that's what I think of.
Write a program that asks the user to enter two values: an integer choice and a real number x. If choice is 1, compute and display the area of a circle of radius x. If choice is 2, compute and display the are of a square with sides of length x. If choice is neither 1, nor 2, will display the text Invalid choice.
so im guessing this is broken into 2 parts? all i can think of so far is having a choice(input) function and defining what pi and area and so on are. but i keep getting errors. what am i doing wrong?
choice = input ('Enter Choice:')
choice_1 = int (choice)
if (choice_1==1): radius = (int)
print('Enter x:',radius)
pi = 3.14159
area = ( radius ** 2 ) * pi
print ( 'The Area is=' , area )
choice_2= (choice)
if (choice_2==2): side= (int)
print('enter X:' side*side)
While you've got the actual calculations right, there are some problems with how you're receiving input. You start out well:
choice = input ('Enter Choice:')
But then do this:
choice_1 = int (choice)
That's not wrong, but there's no need for a new variable name. You could just as well do choice = int(choice).
You then go on:
if (choice_1==1): radius = (int)
The if statement is okay (although the parentheses are not necessary), but the body of it is a bit strange. I don't know what you're trying to achieve there, but it's almost certainly not doing what you want. What you'll probably want to do is remove the current body of the if statement and indent a bunch of the following code.
print('Enter x:',radius)
This will print out Enter x: followed by radius, which you just set to the int function (probably not what you want. Instead, you probably want to prompt the user and receive their input:
radius = input('Enter x: ')
And then convert it to a float:
radius = float(radius)
Back to your code. pi = 3.14159 is valid and correct, but there is no need to assign pi in your own code; just import it from math:
from math import pi
Then you've got these two lines:
area = ( radius ** 2 ) * pi
print ( 'The Area is=' , area )
You've got no problem there; those should work fine. Your code continues:
choice_2= (choice)
This is not useful. Just use choice; you don't need a new variable.
if (choice_2==2): side= (int)
The if statement, here, too, is correct, but its body, too, is senseless. Again, you probably want to prompt the user to enter something and then convert it to a float.
At the end, you've got:
print('enter X:' side*side)
First of all, you're missing a comma. Second of all, you're outputting the area after enter X:, which doesn't make that much sense. That said, you did get the calculation right.
There are a number of issues with the code. Here is a working example of what I believe you want to accomplish:
#!/usr/bin/python
pi = 3.14159265
choice = input('Enter Choice [1 or 2]:')
choice = int (choice)
if choice == 1:
radius = input('Enter x:')
area = ( radius ** 2 ) * pi
print 'The Area is=', area
if choice == 2:
side = input('Enter x:')
area = side ** 2
print 'The Area is=', area
There are a number of problems with the code you've presented: indentation, variables, inputs, and outputs. There are a number of improvements that can be made as well (such as removing duplicate statements). The code I've given above will accomplish what you want to do. So let's go through the errors to get a deeper understanding.
Indentation
First, Python programs should be indented properly. This means that lines following a conditional logic (such as an if statement) should be tabbed. The indentation is called a "block" statement. Only those lines that are indented will be evaluated (executed) if the given condition is met (e.g., the user supplied 1 or 2 as a value).
Variables
The choice_1 and choice_2 variables are not necessary. Logistically, you want to tell the reader of your source code that the user's input should be rounded to a whole integer. The extra variables are superfluous -- you can reuse the choice variable.
Inputs
The input function is used to assign the value of whatever the user typed to the variable on the left-hand-side of the expression. Examples:
choice = input ('Enter choice:')
radius = input( 'Enter x:' )
side = input( 'Enter x:' )
These input statements appear on the screen. The user types in a number and the value of that number is put inside the corresponding variable.
Outputs
The print statement is used to display a value on the screen. In your code, you had combined a text string ('Enter x') with a print statement. The computer cannot "know" that 'Enter x' means that the user must type in a value. Just like the computer does not know that 'Barney' is the name of a purple dinosaur.
radius = (int)
This seems to be the main problem.
A few things.
If that is how your script is indented, it's not going to work, period. Indenting is core to python, and you need to understand that before you'll get anything substantial working.
If the input is an integer, it will be automatically converted using input(). You're only asking for input once, so don't both creating two variables.
choice = input('Enter choice: ')
If should be using an if-elif-else statement here. Use control structures to your advantage:
if choice == 1:
radius = input('Enter radius: ')
print('Area of circle is ', (radius ** 2) * 3.14159)
elif choice == 2:
side = input('Enter side length: ')
print('Areas of square is ', side*side)
That's simplified, what you're trying to acheive.
Other than that, you shouldn't do side= (int) or radius = (int). You're assigning a type of int to the variable, when you should be getting a value from input. You'll find very quickly that there are no operators that support multiplication of type and type.