[Tutor] How to manipulate a user's input twice in one statement

Alan Gauld alan.gauld at yahoo.co.uk
Wed May 17 05:49:30 EDT 2023


On 17/05/2023 07:25, Goran Ikac wrote:
> I'd like to manipulate an user's input using a method.

A method is a technical term that means an operation of
an object defined in a class. It is more or less the same
as a function except that its part of a class.
Is that what you mean by a method?
If not can you expand on what you mean, with examples?

> I'm aware that I can get the result this way:
> 
>>>> user_input = input('Please, type a word: ')
>>>> to_remove = user_input[1:]             # The value of the slice depends
>>>> result = user_input.removesuffix(to_remove)

That would be the preferred way to do it.
Easy to read, easy to debug and easy to maintain.

>>>> user_input = input('Please, type a word: ')
>>>> result = user_input.removesuffix(user_input[1:])

That's OK too, if you never need the slice again.

> I was curious if I could get the result (that depends on both the value of
> the input, and the value of the slice that was applied to the input)
> without assigning the input to a variable first. 

I don't think so, that's what variables are for: to store results that
you need to use more than once.


>>>> user_input = int(input('Please, type a number: '))
>>>> result = 3 * (2 + user_input)
> 
> That could be written:
> 
>>>> result = 3 * (2 + int(input('Please, type a number: '))

It could, but it starts to get more difficult to read
and much harder to debug.

> But, if I need to manipulate the value (that depends on the value of the
> input) by a method, not by an operand or by a function, 

This is where I'm confused. There is no difference between
a method or a function in this regard. If you can use a
function you can use a method? Can you give an example
of what you tried that didn't work?

> ...can I do it without
> assigning that value or/and the value of the input to a variable?
> Perhaps not?

I suspect not. If you want to use an input value more than once you
need to assign it to a variable. There is a special nameless
variable (_) that might help in this case, but frankly giving a
name helps readers(including future you) understand why it's there
(even if the name is just 'x' or 'dummy' or 'tmp').

> People, I'm learning, not trying to write a useful program, yet.

That's OK and we are happy to answer questions. But in this case I
think you are trying to find a way to make your future life more
difficult for yourself. Putting too much on a single line is
usually a mistake that you live to regret!


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





More information about the Tutor mailing list