-2

For example, using input() function like:

input("Type your age:" +"years old")`

When I run it I want the user to type their age between age: and years but, when I run it, the user has to type their age after years old. Is it possible to make it so that the user can type their age between age: and years

martineau
  • 119,623
  • 25
  • 170
  • 301
MartinEG
  • 47
  • 3

4 Answers4

2

Basically, no. When you use input([prompt]), your "Type your age: " + "years old" becomes the prompt. Input always takes in the value at the end.

My question becomes, do you really need the "years old" part?

You can always do something like this:

age = input('How old are you?')
print(f'You are {age} years old!')
Eduards
  • 1,734
  • 2
  • 12
  • 37
2

Actually yes, but it's not quite practical:

x = input("           years old \rAge: ")
print(x)

The trick here is to use \r (carriage return) to return the cursor to the beginning of the line.

Note that if the user types something bigger than the number of spaces given it will overwrite the text "years old".

Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35
1

You can use the implementation of getch to read a single character from the user.

Here is the solution:

import sys

print("Type your age:", end=" ")
sys.stdout.flush()
c = getch()
print(c + " years old")

First, you get:

Type your age: ▯

Then, you press a single character (you can used 2 calls to getch to get 2 characters). And it prints:

Type your age: 9 years old

EDIT

But, the classic way to do that, would be:

while True:
    try:
        age = int(input("Type your age: "))
    except ValueError:
        print("This is not an integer")
        print()
    else:
        if 1 <= age <= 120:
            break
        print("please, enter your age between 1 and 120 years")
        print()

print("You are {age} years old.".format(age=age))
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
0

Yes, but you'd have to learn how to print, backspace, and ingest the input from there. The usual way to handle this is to phrase your question accurately:

input("Enter your age in years, a whole number: ")
Prune
  • 76,765
  • 14
  • 60
  • 81