2017-10-11 12 views
-1

Python-Neuling hier- könnten Sie bitte die folgendenPython-Neuling hier-Python Iterationen

greeting = 'Hello!' 
count = 0 
for letter in greeting: 
    count += 1 
    if count % 2 == 0: 
     print(letter) 
    print(letter) 
print('done') 
+1

Es gibt Tutorials dafür. – Julien

+1

Dieser Code wird nicht ausgeführt, da er mit Einrückungsfehlern gespickt ist. Korrekter Einzug ist _vital_ in Python. –

Antwort

0

Vermeidung der Vertiefung Fehler erklären, ich erkläre, was Ihr Code tut.

In Ihrem Programm haben Sie eine Variable namens Gruß mit dem Wert "Hallo!" und auch eine Zählung mit dem Wert 0.

gruß = 'Hallo!' count = 0

Danach eine for-Schleife us die Schleife durch die Begrüßung verwendet, d. H. Bis zum Ende jedes Wortes Hallo!. Wenn Sie es jedoch selbst überprüfen möchten, können Sie den Brief ausdrucken.

für Brief in Gruß: print (Brief)

jetzt zum Problem kommen, wo Sie auch den Wert der Zählung um 1 von 1, wo die Ausführung steigt der Wert erhöht haben auf jeder Schleife.

Dann haben Sie eine Bedingung, um zu überprüfen, ob die Zahl gerade ist oder nicht count% 2 == 0 gefolgt von der print-Anweisung, die nach dem Erfolg der Bedingung ausgeführt wird. Dies bedeutet, dass der Buchstabe an der geraden Position nur gedruckt wird.

Das ist, was Ihr Programm tut.

0
greeting = 'Hello!' <-- set greeting variable. 
count = 0 <-- set count variable. 
for letter in greeting: <-- this loop will loop six times because greeting contains of six character. 
    count += 1 <-- each times of loop will increase value of count by one. 
    if count % 2 == 0: <-- this line will print a index of character that % 2 = 0 (eg. 2%2 = 0, 4%2 = 0, ...) 
     print(letter) 
    print(letter) <-- this line will print any index of character of greeting. (ps. this line will error because indentation errors.) 
print('done') <-- print 'done'. 

So wird das Ergebnis so aussehen:

H
e
e
l
l
l
o
!
!
erledigt