I'm new to python: convention question

I’m new to python. I wanted to know if when I use the input command, is it common to write the type of variable we expect to recieve from the input?
For example:

  1. num = int(input())
    The other option: just
  2. num=input()
    What is more conventional and used?
    Thx
  1. input isn’t a command. It’s a function. (As a general rule: almost every beginner to almost every programming language, would be better off pretending that there is no such word as “command”. It is extremely rare for it to actually be the right word for whatever the beginner is trying to talk about.)

  2. input will give you a string, no matter what the user typed. (Unless of course we do something special, like quitting the program or shutting off its input stream.)

  3. We aren’t “writing the type of variable” here. Python’s names (we like to call them names, rather than “variables”) don’t have a type. It is the values that have a type - i.e., the actual objects that you get by doing computations.

  4. In this code, int is not any kind of declaration of the type of something else. It is, instead, a call of the type itself, that creates a new integer for you, from what was passed (or at least it tries). int(input()) is not any kind of special syntax; it is just the combination of int() and input(). The user types a string; that string is used to try to create an integer; then num is a name for that integer.

  5. There is no convention because the purpose is different. We convert to integer when we need an integer for the next step in the logic.

  6. Conversion to integer can fail. If the user types hi mom then that does not represent an integer. Instead of trying to give back some dummy value, Python complains about this, using an exception that needs to be handled using try/except statements (or else the program will terminate and show the exception message as an error).

For more:

2 Likes

Hi and welcome.

Each to their own; myself, I tend to use the default return of the input() function, which is a string object. The reason being is that if (to use your example) you code int(input()) then you then have to rely on a user not to enter anything that can’t be type converted to a integer value. There are (of course) ways to prevent a script crash in the event that a user does not play nice and in any case you’re going to want to do a check on what has been entered. That process is called ‘sanitization’ and you’ll maybe come across the mantra: sanitize your users input.

See: Top 10 Best Coding Practices

But, like said; each to their own.

1 Like

wow! Thank you very much! Very helpful
Great to have people responding like this!
Thx

Summary:

  1. It is common to need the user to enter strings from a subset of possible strings, whether to be converted to some other type of to select from defined options.
  2. One must be prepared for the user to enter something not in the desired subset.