Python: Print without newline or space
Python Basic: Exercise-50 with Solution
Write a Python program to print without a newline or space.
# Iterate through a range of numbers from 0 to 9 (inclusive). for i in range(0, 10): # Print an asterisk '*' character on the same line using the 'end' parameter. print('*', end="") # Print a newline character to move to the next line. print("\n")
In the above Python code the for loop iterates through the range of numbers from 0 to 9 (inclusive) generated by the range() function. On each iteration, it prints a single asterisk character using the print() function, with the end parameter set to an empty string (""). This causes the print() function not to insert a newline character after each asterisk.
After the loop completes, a newline character is printed to the console using the print() function.
# Import the functools module to use the 'partial' function. import functools # Create a partial function 'printf' based on the 'print' function with 'end' parameter set to an empty string. printf = functools.partial(print, end="") # Iterate through a range of numbers from 0 to 9 (inclusive). for i in range(0, 10): # Use the 'printf' function to print an asterisk '*' character to the same line. printf('*') # Note: The variable 'i' is defined but not used in this code.
The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.
functools.partial: Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.
In the above Python code we use the ‘functools’ module to create a partial function that prints a string without a newline character.
After defining the printf function, a for loop is used to iterate through the range of numbers from 0 to 9 (inclusive) generated by the range() function. On each iteration, it calls the printf() function to print a single asterisk character to the console without adding a newline character.
# Initialize the variable 'i' with the value 0. i = 0 # Start a while loop that continues as long as 'i' is less than 10. while i < 10: # Print an asterisk '*' to the same line without moving to the next line. print('*', end='') # Increment the value of 'i' by 1 in each iteration. i = i + 1
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join