简体   繁体   中英

Need help with While Loop

I am extremely new to programming so it's taking a lot to re-wire. my brain to think like a computer programmer.

I need to create a script in Python using a while loop that does this:

zebra arbez
ebraz zarbe
braze ezarb
razeb bezar
azebr rbeza

Keep in mind that the script should be able to do this with any word. For example, right now a = 'zebra' . If a = 'cat' the the script should look like:

cat tac
atc cta
tca cat

I've figured out how to do it with a for loop...just can't figure out exactly how to implement it with a while loop.

My for loop:

a = 'zebra'
for i in range(len(a)):
    print a[i:] + a[:i], (a[i:] + a[:i])[::-1]

If anyone could help me out, or give me hints...I'd really appreciate it! thanks!

for (initialization_expression;loop_condition;increment_expression){
  // statements
}

is basically just a nice way of writing

initialize_expression;
while(loop_condition){
    // statements
    increment_expression
}

Deconstruct your for loops into this format and you should have your solution.

Here is some code that will work for any sized word, using a While loop:

word = "alpha"
index = 0

while (index < len(word)):
    print word + "   " + word[::-1]
    word = word[1:] + word[0]
    index += 1

The following code seems to work as well, but I am not sure if this is what your teacher wants

a = 'zebra'
b=''
while a: 
    print a+b, (a+b)[::-1]
    b+=a[0]
    a=a[1:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM