Home > Enterprise >  How do I reference a name in a different input
How do I reference a name in a different input

Time:01-18

Program:

CLASS = str(input("What is the name of your class: "))
HOURS = int(input("How many hours a week do you spend in", CLASS))

the second line does work, the first line work and then crashes once it gets to the second line.

I;ve tried googling and looking through my notes and nothering explaines it

CodePudding user response:

input does not work like print in regards to how each takes arguments. print uses varargs, which allows it to accept an arbitrary number of arguments and automatically concatenates them for you. input has no such functionality though. You need to do the concatenation yourself.

I'd use f-strings here:

HOURS = int(input(f"How many hours a week do you spend in {CLASS}")) 

or, using :

HOURS = int(input(f"How many hours a week do you spend in "   CLASS)) 

CodePudding user response:

The input function in python only takes 1 argument, and you gave it 2 (a comma indicates a new input).

Their are two main ways to do this:

The first way to do this is via string formatting, this would look like this:

HOURS = int(input(f"How many hours a week do you spend in {CLASS}"))

Generally this is the best way to do this. The f at the beginning of the int string allows you to put variables into the string using curly brackets.

The other way to do this is to make the string for input a completley new variable, like this:

HOURS_str = "How many hours a week do you spend in "   CLASS
HOURS = int(input(HOURS_str))

Here, a new variable, HOURS_str is made, and this variable is then referenced in the input.

You can also put the whole of hours string into the input for a third method:

HOURS = int(input("How many hours a week do you spend in "   CLASS))
  • Related