Nick Mireri
Nick Mireri

Reputation: 75

Python: How do I put print statement and input on same line?

How can I make it that when the user enters input its on the same line as the print statement

like for example for the code snippet below. The output becomes:

Enter grade for course 1: A
Enter credits for course 1: 4

For now this is what I get:

Enter grade for course 1: 
A
Enter credits for course 1:
4

Here is the code snippet

for i in range(1,coursenumber+1):
    print("Enter grade for course ", i,":", end =""),
    grade=str(input())
    print("Enter credits for course", i,":", end =" ")
    credit=int(input())
    totalgpa+=translate(credit,grade)
    totalcredit+=credit

Upvotes: 5

Views: 47927

Answers (4)

Nick Gurr
Nick Gurr

Reputation: 11

You can utilize cursor movements to be able to print and take input on the same line. This will allow you to take to inputs on the same line as well.

main.py
-------
print("something")
res = input("\033[1A \033[9C Write something here:")
            
            #\033[<num>A -> move cursor up 'num' lines
            #\033[<num>C -> move cursor up 'num' columns

output
------
> somethingWrite something here:▒

Upvotes: 1

wispi
wispi

Reputation: 461

Instead of using print() first, use just input() like this:

question="Enter grade for course" + str(i)
grade=input(question)

question can be whatever, you just can't combine strings inside the input() function.

Upvotes: 5

Blckknght
Blckknght

Reputation: 104682

What you have now should work. If it does not, it's because you're not using a normal console for output. That said, as other answers have suggested, you can do better by including the prompt in the call to input, rather than in a separate print call.

The only complication is that you need to format the prompt yourself, rather than passing separate arguments, like you can do with print. Fortunately, string formatting isn't to hard. I'd do something like this:

input("Enter grade for course {}: ".format(i))

Upvotes: 0

Kazuya Hatta
Kazuya Hatta

Reputation: 750

You can write the question inside the input function like

for i in range(1,coursenumber+1):
    grade=input(f"Enter grade for course {i}:")
    credit=input(f"Enter credits for course {i}:")
    totalgpa+=translate(credit,grade)
    totalcredit+=credit

Then the input prompt appears right next to the question

Upvotes: 10

Related Questions