Python: Users choosing either an int or a float - python

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.

Related

I cant figure out why my python code isn't returning the answer in miles

Write a program that takes as input a number of kilometers and prints the corresponding number of nautical miles. Use the following approximations:
• A kilometer represents 1/10,000 of the distance between the North Pole and
the equator.
• There are 90 degrees, containing 60 minutes of arc each, between the North
Pole and the equator.
• A nautical mile is 1 minute of an arc.
That is the statement that I have to flow in python.
This is the program that I have written down but it's only showing the kilometers.
Kilometers=input("Enter the amount of kilometers:")
degreesPerMin = 90*60
onekilo = degreesPerMin/10,000
nauticalmile = onekilo*Kilometers
print =input("Kilometers,is,nauticalmile,Nautical miles")
You have a few minor errors in your code that needs to be fixed.
Your input statement has to be converted into an int before you use it for computation nauticalmile = onekilo*Kilometers
Your division statement has a comma. Python will consider comma as another variable. So remove the comma onekilo = degreesPerMin/10,000 in this statement
Your print statement needs to be updated. Don't use input statement in your print statement when you want to just display information. Also, separate out strings and variables with proper quotes. print =input("Kilometers,is,nauticalmile,Nautical miles") needs to be edited to print (Kilometers,"is",nauticalmile,"Nautical miles")
When these changes are made, your program works perfectly. See below updated code.
Kilometers=int(input("Enter the amount of kilometers:"))
degreesPerMin = 90*60
onekilo = degreesPerMin/10000
nauticalmile = onekilo*Kilometers
print (Kilometers,"is",nauticalmile,"Nautical miles")
Output:
Enter the amount of kilometers:200
200 is 108.0 Nautical miles
When you are going to take an input you should first declare the data type (eg: int,str,float) if not the data type of the input is set to str/String by default.
If you want to the get the output of the equations/variables you declared (eg: degreesPerMin = 90*60, etc.), you don't have to write them inside brackets because you only use brackets to print Strings or characters.
Kilometers=int(input("Enter the amount of kilometers:"))#datatype is declared(int)
degreesPerMin = 90*60
onekilo = degreesPerMin/10000
nauticalmile = onekilo*Kilometers
print("Kilometers =",Kilometers)#the variable name shouldn't be inside brackets(Kilometers)
print("degreesPerMin =",degreesPerMin)
print("onekilo =",onekilo)
print("nauticalmile =",nauticalmile)

Defined Argument Doesn't seem to Fire

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.

What Python3 method can I use to restrict input to only integer in my assignment?

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...

Python ValueError: invalid literal for int() with base 10:

I am trying to write a program to do some simple power usage and cost calculations, the logic is correct and the algorithm works for VB but I want to use Python. Being new to Python I am a little confused as to what I am missing, the code is below. I have used some conventions here to help me understand what is happening
IntWatts = input ("What is the Watt rating? ")
IntHoursOfUse = input ("How many hours is the device on for? ")
IntTariff = input ("What is the Tariff in cents? ")
IntEnergyRating = int(IntWatts)/1000
IntUsageKWH = int(IntEnergyRating) * IntHoursOfUse
IntCostInCents = IntUsageKWH * int(IntTariff)
IntCostInDollars = float(IntCostInCents) / 100
print('the Cent cost is :',IntCostInCents)
print("the Dollar cost is ;", IntCostInDollars)enter code here
I have been using the inputs of
Watts 240
HoursOfUse 5
Tariff 34.1
Thanks
As to why the error is happening, it is simply a matter of typecasting the wrong variable, note the example below.
watts = input('What is the Watt rating?')
hours_of_use = input('How many hours is the device on for?')
tariff = input('What is the Tariff in cents?')
energy_rating = int(watts) / 1000
usage_kwh = energy_rating * int(hours_of_use)
cost_in_cents = usage_kwh * int(tariff)
cost_in_dollars = cost_in_cents / 100
print('The cent cost is :', cost_in_cents)
print('The dollar cost is :', cost_in_dollars)
This code should produce the results you are looking for. As to what some of the problems are here.
A few things to note, you only need to cast the input() values here since they are coming in as strings and need to be interpreted in your program as integers.
In Python there are two forms of division / which results in expected results according to how we as humans learn math, and // which will floor your result; this is why you do not need to cast to floats.
There are many pythonic things here to take away as you learn this language, while I won't go into great depth, do note the naming conventions. Python variables are typically _ delimited, lowercase and self-documenting. Additionally it is considered fairly poor practice to label variables with type, this is an old convention that has fallen out of practice.
For additional reading on Python, check out the coding guidelines:
https://web.archive.org/web/20111010053227/http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting
you need to type-cast IntHoursOfUse to int while initializing IntUsageKWH as:
# v Type casting this to int()
IntUsageKWH = IntEnergyRating * int(IntHoursOfUse)
# ^ No need to type-cast this as you are already doing it in previous line
I needed to change the inputs to be
IntWatts = int(input ("What is the Watt rating? "))
IntHoursOfUse = int(input ("How many hours is the device on for? "))
IntTariff = float(input ("What is the Tariff in cents? "))
and then remove all other int/float commands
Thanks for the help

how to write program for area for circle and square

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.

Categories

Resources