[Tutor] Stuck on some basics re floats
Hi, I'm a teacher trying to learn Python with my students. I am trying to make a very simple 'unit calculator' program...but I get an error ..I think python is treating my num1 variable as a text string...not an integer. How do I fix this? Thanks! - Matt print ("How many inches would you like to convert? ") num1 = input('Enter inches here') print ("You have entered",num1, "inches") convert = num1 * 2.54 print ("This is", convert, "centimetres") Traceback (most recent call last): File "convert.py", line 10, in convert = num1 * 2.54 TypeError: can't multiply sequence by non-int of type 'float' Matthew Polack | Teacher [image: Emailbanner3.png] Trinity Drive | PO Box 822 Horsham Victoria 3402 p. 03 5382 2529 m. 0402456854 e. matthew.pol...@htlc.vic.edu.au w. www.htlc.vic.edu.au -- **Disclaimer: *Whilst every attempt has been made to ensure that material contained in this email is free from computer viruses or other defects, the attached files are provided, and may only be used, on the basis that the user assumes all responsibility for use of the material transmitted. This email is intended only for the use of the individual or entity named above and may contain information that is confidential and privileged. If you are not the intended recipient, please note that any dissemination, distribution or copying of this email is strictly prohibited. If you have received this email in error, please notify us immediately by return email or telephone +61 3 5382 2529** and destroy the original message.* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Stuck on some basics re floats
On 18/07/18 00:52, Matthew Polack wrote: > Hi, > > I'm a teacher trying to learn Python with my students. > > I am trying to make a very simple 'unit calculator' program...but I get an > error ..I think python is treating my num1 variable as a text string...not > an integer. You are correct. > How do I fix this? Convert the string to a float: f = float(s) > print ("How many inches would you like to convert? ") > num1 = input('Enter inches here') In Python 3 input() always returns a string. In python 2 input() returns an evaluated version of the string, so if a number was entered Python returned a number. This was a serious security risk however, so input() was removed in Python 3 and the old raw_input() was renamed as input(). > print ("You have entered",num1, "inches") > convert = num1 * 2.54 convert = float(num1) * 2.54 > print ("This is", convert, "centimetres") HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Stuck on some basics re floats
Matthew Polack wrote: > Hi, > > I'm a teacher trying to learn Python with my students. > > I am trying to make a very simple 'unit calculator' program...but I get an > error ..I think python is treating my num1 variable as a text string...not > an integer. > > How do I fix this? > > Thanks! > > - Matt > > print ("How many inches would you like to convert? ") > num1 = input('Enter inches here') As you have guessed, at this point num1 is a string. You can convert it to a float with num1 = float(num1) > print ("You have entered",num1, "inches") > convert = num1 * 2.54 > print ("This is", convert, "centimetres") > > > Traceback (most recent call last): > File "convert.py", line 10, in > convert = num1 * 2.54 > TypeError: can't multiply sequence by non-int of type 'float' Note that int is mentioned here because Python can multiply int with str, though the result might surprise you: >>> "spam" * 3 'spamspamspam' So * also works as the repetition-operator just like + is also used to concat strings. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Stuck on some basics re floats
Matthew Polack writes: > I'm a teacher trying to learn Python with my students. Wonderful! Thank you for choosing Python for teaching your students. > I am trying to make a very simple 'unit calculator' program...but I get an > error ..I think python is treating my num1 variable as a text string...not > an integer. Yes. You are using the ‘input’ function, built in to Python 3 https://docs.python.org/3/library/functions.html#input>. Read the documentation for that function; when successful, it returns text (“a string”). If you want an integer, you will need to explicitly tell Python to convert the text to an integer value. To create a new object, a general way is to use the type as a constructor. The type you want is ‘int’, so use that as the constructor, and you will (if it succeeds) get a new integer as the return value:: response = input("Enter inches here: ") inches = int(response) You will also need to learn about handling conversion errors: Try entering something that is *not* a representation of an integer and see what happens. How to handle the error is up to you. -- \ “Yesterday I parked my car in a tow-away zone. When I came back | `\ the entire area was missing.” —Steven Wright | _o__) | Ben Finney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Everything in one file?
On 24/05/2018 03:27, Steven D'Aprano wrote: > On Tue, May 22, 2018 at 03:46:50PM +0530, aishwarya selvaraj wrote: >> Dear all, >> I have created 2 classes in 2 separate files. > > If you have learned the bad habit from Java of putting every class in a > separate file, you should unlearn that habit for your Python code. There > is no need to put every class in a separate file, and it usually leads > to complicated dependencies and circular imports. > > I am an slightly more than a beginner. I have not met this advice from Steven D'Aprano before, so I have some questions. I have constructed a program which has a parent class and a child class and I have them in two different files. I import the parent class into the child class and create instances with the child class. This works fine. But, would it be better to have both classes in one file? Would then the child class 'know' that the parent class is in the file? And further. I have a function which sets up all the suitable data structures into which this function will put the information supplied by the user. I import this file too into both the parent and the child class. Would the instances with which I actually work, 'know' that this function is there if it is simply present in the same file? -- Sydney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Everything in one file?
Comments below. On Wed, Jul 18, 2018 at 03:46:20PM +0200, Shall, Sydney wrote: > On 24/05/2018 03:27, Steven D'Aprano wrote: > > On Tue, May 22, 2018 at 03:46:50PM +0530, aishwarya selvaraj wrote: > >> Dear all, > >> I have created 2 classes in 2 separate files. > > > > If you have learned the bad habit from Java of putting every class in a > > separate file, you should unlearn that habit for your Python code. There > > is no need to put every class in a separate file, and it usually leads > > to complicated dependencies and circular imports. > > > > > > I am an slightly more than a beginner. > I have not met this advice from Steven D'Aprano before, so I have some > questions. Note that I said there is no *need* to put each class in a separate file, not that one should "never" split classes into separate files. > I have constructed a program which has a parent class and a child class > and I have them in two different files. I import the parent class into > the child class and create instances with the child class. This works fine. > But, would it be better to have both classes in one file? Probably. Even better, why do you have two classes if you only ever use one? If Parent is never used on its own, and you only use Child, why bother with Parent? Put everything into one class. > Would then the > child class 'know' that the parent class is in the file? If you write this: class Parent: pass class Child(Parent): pass then it will work fine, for *exactly* the same reasons that this works: x = 99 y = x + 1 # x is already defined But if you try this instead: # Stop! This won't work! class Child(Parent): # NameError: unknown Parent pass class Parent: pass it won't work for exactly the same reason you can't write this: y = x + 1 # NameError: unknown x x = 99 > And further. I have a function which sets up all the suitable data > structures into which this function will put the information supplied by > the user. I import this file too into both the parent and the child class. > Would the instances with which I actually work, 'know' that this > function is there if it is simply present in the same file? Every line of Python code "knows" whatever variables and names exist at the moment that line of code is executed. That usually means variables, classes and functions which are defined *above* it in the file. Whether those variables are defined in place: x = 99 or imported from somewhere else: from module import x makes no difference. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Everything in one file?
On 18/07/18 14:46, Shall, Sydney wrote: > > is no need to put every class in a separate file, and it usually leads > > to complicated dependencies and circular imports. > I have constructed a program which has a parent class and a child class > and I have them in two different files. I import the parent class into > the child class and create instances with the child class. This works fine. > But, would it be better to have both classes in one file? Probably if you know when writing them that you will need to import parent to use child and especially if you are unlikely to ever use parent without child(or some other child class). > Would then the > child class 'know' that the parent class is in the file? Python visibility is controlled by the scope rules (and some other magic stuff that applies to packages but needn't concern us here!) The scope that we are concerned with is module scope, sometimes called global scope, but not in the normal sense that global has in other languages. Module or global scope means that everything inside a module is visible to everything else inside the same module. So yes you child class can see the parent class if it is in the same file (aka module). # myfile.py ## class Parent: pass class Child(Parent): pass # EOF # So Parent is visible to the child definition without any extra work. Now consider the 2 file option: # parent.py # class Parent: pass # EOF ## # child.py ### import parent class Child(parent.Parent): pass # EOF ## Now the child class must import parent and dereference Parent within its module. (ie use parent.Parent) So two classes is more work for you and more work for the interpreter. > And further. I have a function which sets up all the suitable data > structures into which this function will put the information supplied by > the user. I import this file too into both the parent and the child class. > Would the instances with which I actually work, 'know' that this > function is there if it is simply present in the same file? Yes, again the function definition would have module/global scope so the classes can see the function with no extra work. The instances don;t see the function idf they are in a separate file but they do see their class definition which includes all the methods. And those methods see the function. Like so: # myfile2.py ## def myFunc(): return (1,2,3) # some data structure... class Parent: pass class Child(Parent): def __init__(self): self.data = myFunc() # access the function # EOF # # myinstance.py ### import myfile2 instance = myfile2.Child() print(instance.data) # -> (1,2,3) # EOF So it works. But it's probably bad practice. Classes should do all their own data maniplulation. Having a function outside the class preparing data structures for use by a class is bad OOP practice. Much better to prepare the data structures inside the class - maybe as a method of Parent? Remember classes are data structures too. That's why its called object oriented programming - you define objects and pass the objects around. You don't pass data between objects. You pass objects. Objects are data, and they know how to process their own data - so nobody else should need to. That's called encapsulation and is the basis of all things OOP. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Stuck on some basics re floats
On 18/07/18 14:10, Matthew Polack wrote: > Thanks for the reply Alan. > > I found another fix where I could just use this: > > num1 =int(input('Ener inches here?: ')) > > > but a lot of people like yourself seem to be recommending this > 'float' method. It all depends whether your input is a float or an integer. If it will always be a whole number of inches then use int(). If it will be a floating point value then you need to use float(). In your example I'd have thought it reasonable to allow conversions of, say, 11.5 inches... I meant to add that its generally considered good practice to do the conversion as early as possible unless you plan on using the string version later. So wrapping the input() call inside the int or float call is good. You can then wrap that inside a try/except and get the user to re-try if they type invalid data - if you so wish... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Everything in one file?
On 18/07/18 17:00, Alan Gauld via Tutor wrote: > Now the child class must import parent and dereference > Parent within its module. (ie use parent.Parent) > > So two classes is more work for you and more work > for the interpreter. Oops, that should be two *files* is more work... sorry, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Everything in one file?
On 07/18/2018 10:00 AM, Alan Gauld via Tutor wrote: > On 18/07/18 14:46, Shall, Sydney wrote: > >> > is no need to put every class in a separate file, and it usually leads >> > to complicated dependencies and circular imports. > >> I have constructed a program which has a parent class and a child class >> and I have them in two different files. I import the parent class into >> the child class and create instances with the child class. This works fine. >> But, would it be better to have both classes in one file? > > Probably if you know when writing them that you will need to > import parent to use child and especially if you are unlikely > to ever use parent without child(or some other child class). > >> Would then the >> child class 'know' that the parent class is in the file? I had been writing something here and then saw Alan and Steven had already sent pretty much what I was trying to say! > Python visibility is controlled by the scope rules (and some other magic > stuff that applies to packages but needn't concern us here!) > > The scope that we are concerned with is module scope, > sometimes called global scope, but not in the normal sense > that global has in other languages. Module or global scope > means that everything inside a module is visible to > everything else inside the same module. > > So yes you child class can see the parent class if > it is in the same file (aka module). A couple of extra points... first, in standard Python, function and class definitions are runnable statements which are evaluated when encountered (this sometimes surprises new developers), creating objects which are then available to use when it comes time to call them. So "order matters" as Steven was saying, class Child(Parent): pass class Parent: pass fails on the Child class definition because there is not yet a class object named Parent that Child can inherit from. In compiled languages the compiler can figure it all out since it processes it all up front before anything is run, but may still require "forward declarations" to make its life simpler, so it's not so different after all. second, Python creates namespaces - C++ developers, say, may be used to declaring their own namespace, and being able to split those namespaces across multiple files, but Python tends to use a module-based approach. If you just write a single Python file, and run it, Python considers that to be a module named __main__ (stick the line print(__name__) in a python file and run it to see, or use the interpreter), and that has its own set of symbols, called globals but really just module-global. If you want to get the symbols from another module, you need to "import" them, and they appear in a namespace matching that module name. So, # assume module foo defines function bar import foo # makes available the symbols from foo # your module can call foo as foo.bar() but also: from foo import bar # makes available that symbol in _your_ namespace # your module can now call bar as bar(). These are really just symbol-visibility tricks, so you can do both if you have any desire to do so: import foo from foo import bar bar() foo.bar() maybe that's drifting off-topic, so I'll stop now :) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor