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: 4For now this is what I get:
Enter grade for course 1: A Enter credits for course 1: 4Here 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+=creditHow to print() and input() on the same line in Python #
Pass a string to the input() function to have a print statement and input on the same line, e.g. username = input('Enter your username: '). The input() function takes a prompt string and prints it to standard output without a trailing newline.
Copied!
# ✅ print input message on same line username = input('Enter your username: ') print(username) # ---------------------------------- # ✅ use print() and input() without separator and newline character print( 'Your username is: ', input('Enter your username: '), sep='', end='' )In the first example, we passed a prompt string to the input() function.
The input function takes an optional prompt argument and writes it to standard output without a trailing newline.
Copied!
s = input('Enter your name: ') print(s)The function then reads the line from input, converts it to a string and returns the result.
You can also use the print() function before or after the input() function.
Copied!
print('this runs before') user_input = input('Enter your username: ') print('this runs after')If you use the print() function instead of the prompt argument, the print statement is printed on a separate line.
Copied!
print('Enter your name: ') s = input() print(s)If you want to call the print() function with multiple arguments without a separator, set the sep and end keyword arguments to empty strings.
Copied!
print( 'Your username is: ', input('Enter your username: '), sep='', end='' )The sep argument is the separator between the arguments we pass to print().
By default, the argument is set to a space.
Copied!
print('a', 'b', 'c') # 👉️ 'a b c' print('a', 'b', 'c', sep='') # 👉️ 'abc'The end argument is printed at the end of the message.
By default, end is set to a newline character (\n).
Copied!
print('a', 'b', 'c') # 👉️ 'a b c\n' print('a', 'b', 'c', end='') # 👉️ 'a b c'You can also use a formatted string literal to print multiple arguments on the same line.
Copied!
print(f'Your name is: {input("Enter your name: ")}')Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
Copied!
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: TrueMake sure to wrap expressions in curly braces - {expression}.