Python OOP - object has no attribute - python

I am attempting to learn how to program. I really do want to learn how to program; I love the building and design aspect of it. However, in Java and Python, I have tried and failed with programs as they pertain to objects, classes, methods.. I am trying to develop some code for a program, but im stumped. I know this is a simple error. However I am lost! I am hoping someone can guide me to a working program, but also help me learn (criticism is not only expected, but APPRECIATED).
class Converter:
def cTOf(self, numFrom):
numFrom = self.numFrom
numTo = (self.numFrom * (9/5)) + 32
print (str(numTo) + ' degrees Farenheit')
return numTo
def fTOc(self, numFrom):
numFrom = self.numFrom
numTo = ((numFrom - 32) * (5/9))
return numTo
convert = Converter()
numFrom = (float(input('Enter a number to convert.. ')))
unitFrom = input('What unit would you like to convert from.. ')
unitTo = input('What unit would you like to convert to.. ')
if unitFrom == ('celcius'):
convert.cTOf(numFrom)
print(numTo)
input('Please hit enter..')
if unitFrom == ('farenheit'):
convert.fTOc(numFrom)
print(numTo)
input('Please hit enter..')

Classes and objects are tools to accomplish a task -- they allow you to encapsulate data or state with a set of methods. However, your data is just a number. There is no need to encapsulate the integer, so there is no need to create a class.
In other words, don't create a class because you think you should, create a class because it makes your code simpler.
import sys
def f_to_c(x):
return (x - 32) * (5/9)
def c_to_f(x):
return x * (9/5) + 32
num_from = float(input('Enter a number to convert: '))
unit_from = input('What units would you like to convert from? ')
unit_to = input('What units would you like to convert to? ')
if (unit_from, unit_to) == ('fahrenheit', 'celsius'):
num_to = f_to_c(num_from)
elif (unit_from, unit_to) == ('celsius', 'fahrenheit'):
num_to = c_to_f(num_from)
else:
print('unsupported units')
sys.exit(1)
print('{} degrees {} is {} degrees {}'
.format(num_from, unit_from, num_to, unit_to))
Enter a number to convert: 40
What units would you like to convert from? celsius
What units would you like to convert to? fahrenheit
40.0 degrees celsius is 104.0 degrees fahrenheit
The convert object and Converter class don't serve any purpose, so the code is simpler and easier to read without them.

1.It should be
def fTOc(self, numFrom):
self.numFrom = numFrom
cTOf method has the same problem.
2.Variable numTo not defined
numTo = convert.cTOf(numFrom)
print (numTo)

You almost got it right.
There is no self.numFrom because it is your parameter. Remove the lines numFrom =self.numFrom and you will be fine.

Related

Issue With Math Function Called From Another File

I'm currently working on a unit conversion calculator, and wanted to make it smoother by calling the math functions from a different file. Currently, Celsius -> Fahrenheit (CF) is put in 'func.py', like this:
# This file has all the math functions that get called by main.py when needed.
# Also, VARIABLES!
num = 0
typ = 0
def CF():
tota = (num * 9/5) + 32
print("Answer: " + str(tota) + " degrees Fahrenheit")
And the code to call it in main.py looks like this:
if (typ == str('C-F')):
num = int(input("Enter the temperature in Celcius: "))
num = num
CF()
I figure that I imported something wrong, but I've edited the import function several times now. I'm not looking for some type of complete correction, I wish for somebody to tell me what I did wrong, so that I can fix it. I used repl.it, if it helps. Even if someone can tell me that it's possible, it'll help.
I couldn't find anything on websites like GeeksforGeeks, which is my main source on research.
This is very odd:
def CF():
You're relying on num being defined at module scope within its module.
Much better to spell it this way, so you're passing in an argument:
def cf(num):
Over in main.py you're doing this, which isn't helpful:
num = num
Much better to pass it in:
cf(num)
The big concept you've been missing is you have two different modules,
and each one has a num variable.
They are different.
Changing one won't automatically affect the other.
Use function parameters instead.
You need to work with function parameters and returns (see this for a tutorial).
# func.py
def CF(num):
return (num * 9/5) + 32
# main.py
if (typ == str('C-F')):
num = int(input("Enter the temperature in Celcius: "))
tota = CF(num)
print("Answer: " + str(tota) + " degrees Fahrenheit")

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