Python while loop print on same line

So I am writing a program that asks for your input, puts the words of the sentence you entered into a list and makes the words in the statement go trough the while loop one by one.

The while loops works as follows: if the first letter of a word is a Vowel it print the word + hay. Ifthe first letter of the word is not a vowel it puts the first letter of the word at the end of the word + ay

the code:

VOWELS = ['a','e','i','o','u']

def pig_latin[phrase]:
    #We make sure the input is changed in only lower case letters.
    #The words in your sentence are also putted into a list
    lowercase_phrase = phrase.lower[]
    word_list = lowercase_phrase.split[]
    print word_list

    x = 0

    while x < len[word_list]:

        word = word_list[x]
        if word[0] in VOWELS:
            print word + 'hay'

        else:
            print word[1:] + word[0] + 'ay'
        x = x+1

pig_latin[raw_input['Enter the sentence you want to translate to Pig Latin, do not use punctation and numbers please.']]

My problem: If i enter for example: "Hello my name is John" in the_raw input at the end of the code i will get the following output:

ellohay
ymay
amenay
ishay
ohnjay

But i actually want the following output:

ellohay ymay amenay ishay ohnjay

If someone could explain me how to achieve this output it would be appriciated

Python is powerful — you can condense many algorithms into a single line of Python code. So the natural question arises: can you write a while loop in a single line of code? This article explores this mission-critical question in all detail.

  • How to Write a While Loop in a Single Line of Python Code?
  • Method 1: Single-Statement While Loop One-Liner
  • Method 2: Multi-Statement While Loop One-Liner
  • Method 3: Nested Compound Statements While Loop One-Liner
  • Related Video: One-Line For Loop
  • Where to Go From Here
  • Programmer Humor
  • Python One-Liners Book: Master the Single Line First!

How to Write a While Loop in a Single Line of Python Code?

There are three ways of writing a one-liner while loop:

  • Method 1: If the loop body consists of one statement, write this statement into the same line: while True: print['hi']. This prints the string 'hi' to the shell for as long as you don’t interfere or your operating system forcefully terminates the execution.
  • Method 2: If the loop body consists of multiple statements, use the semicolon to separate them: while True: print['hi'], print['bye']. This runs the statements one after the other within the while loop.
  • Method 3: If the loop body consists nested compound statements, replace the inner compound structures with the ternary operator: while True: print['hi'] if condition else print['bye'].

Exercise: Run the code. What do you observe? Try to fix the infinite loop!

Next, you’ll dive deep into each of these methods and become a better coder in the process.

Before we move on, I’m excited to present you my brand-new Python book Python One-Liners [Amazon Link].

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book is released in 2020 with the world-class programming book publisher NoStarch Press [San Francisco].

But enough promo, let’s dive into the first method—the profane…

Method 1: Single-Statement While Loop One-Liner

Just writing the while loop into a single line of code is the most direct way of accomplishing the task. Say, you want to write the following infinite while loop in a single line of code:

while True:
    print['hi']
'''
hi
hi
...
'''

You can easily get this done by writing the command in a single line of code:

# Method 1: Single-Line While Loop
while True: print['hi']

While this answer seems straightforward, the interesting question is: can we write a more complex while loop that has a longer loop body in a single line?

Related Article: If you’re interested in compressing whole algorithms into a single line of code, check out this article with 10 Python one-liners that fit into a single tweet.

Let’s explore an alternative Python trick that’s very popular among Python masters:

Method 2: Multi-Statement While Loop One-Liner

As it turns out, you can also use the semicolon to separate multiple independent statements and express them in a single line. The statement expression1; expression2 reads “first execute expression1, then execute expression2“.

Here’s an example how you can run a while loop until a counter variable c reaches the threshold c == 10:

c = 0
while c < 10: print[c]; c = c + 1
'''
0
1
2
3
4
5
6
7
8
9
'''

This way, you can easily compress “flat” loop bodies in a single line of Python code.

But what if the loop body is not flat but nested in a hierarchical manner—how to express those nested while loops in a single line?

Method 3: Nested Compound Statements While Loop One-Liner

You often want to use compound statements in Python that are statements that require an indented block such as if statements or while loops.

In the previous methods, you’ve seen simple while loop one-liners with one loop body statement, as well as multiple semicolon-separated loop body statements.

Problem: But what if you want to use a compound statement within a simple while loop—in a single line of code?

Example: The following statement works just fine:

# YES:
if expression: print['hi']

You can also add multiple statements like this:

# YES:
if expression: print['hi']; print['ho']

But you cannot use nested compound statements in a while loop one-liner:

# NO:
while expression1: if expression2: print['hi']

Python throws an error does not work because both the while and if statements are compound.

However, there’s an easy fix to make this work. You can replace the if expression2: print['hi'] part with a ternary operator and use an expression rather than a compound statement:

# Method 3: One-Line While Loop + Ternary Operator
while True: print['yes'] if True else print['no']

You can also use nested ternary operators to account for possibly nested if blocks:

Related Video: One-Line For Loop

Python One Line For Loop [A Simple Tutorial]

You can find out more about the single-line for loop in my detailed article here.

Where to Go From Here

Knowing small Python one-liner tricks such as the list comprehension and single-line for loops is vital for your success in the Python language. Every expert coder knows them by heart—after all, this is what makes them very productive.

If you want to learn the language Python by heart, join my free Python email course. It’s 100% based on free Python cheat sheets and Python lessons. It’s fun, easy, and you can leave anytime.

Programmer Humor

It’s hard to train deep learning algorithms when most of the positive feedback they get is sarcastic. — from xkcd

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover [1] tips and tricks, [2] regular expressions, [3] machine learning, [4] core data science topics, and [5] useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets [and negative characters sets], and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do you print a while loop on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print[] function call. print["It's me."]

How do you print a while loop in one line?

How to Write a While Loop in a Single Line of Python Code?.
Method 1: If the loop body consists of one statement, write this statement into the same line: while True: print['hi'] . ... .
Method 2: If the loop body consists of multiple statements, use the semicolon to separate them: while True: print['hi'], print['bye'] ..

How do you print on the same line in Python?

Use a carriage return "\r" to print over the same line Use the syntax print[string, end = "\r"] to make the next stdout line begin at the beginning of the current line.

How do I print multiple loops in one line Python?

Summary: To write a nested for loop in a single line of Python code, use the one-liner code [print[x, y] for x in iter1 for y in iter2] that iterates over all values x in the first iterable and all values y in the second iterable.

Chủ Đề