Actions

Python for beginners/loops and conditions

From Algolit

Revision as of 15:29, 21 November 2015 by An (talk | contribs)

* this part is using scripts (modules) in idle

Note: Python uses intendation! Each : is followed by a hard return + 4 spaces (a tab). Wikipedia is not tab friendly... You'll get a syntax error if you forget to use them.


$ save file as .py (add at top file : #!/usr/bin/env python)


# REMIX SONG using STRING, LIST and FOR, IN, IF, WHILE

(#) Prince, Purple Rain (using a hashtag = making a comment)

song = (

“I never meant to cause you any sorrow\n”

“I never meant to cause you any pain\n”

“I only wanted to one time to see you laughing\n”

“I only wanted to see you\n”

“Laughing in the purple rain.”

)


* transform string in list of words

song = song.split()


* double all words of list and print again as song

remix1 = [word*2 for word in song]

print(" ".join(remix1))

remix1 = remix1[:16]

print(" ".join(remix1))


* FOR, IN, IF

** rewrite the song with the words that count more than 4 letters

remix2 = [word for word in song if len(word) <= 4]

remix2 = "°*@".join(remix2)

print(remix2)


** transform all letters of song in lowercaps

remix2 = remix2.lower()


** Capitalize the song and end with a dot // Hèhè, a new sentence!

print(remix2.capitalize() + ".")


** print a list of words of the song + next to each word its length

for word in song:

print(word, len(word))


** print a list of words of the song + next to each word its position in the sentence

for position in range(len(song)):

print position, song[position]


** rewrite song by copying words with r to the beginning of the song

for word in song[:]: # Loop over a copy of the list

if "r" in word:

song.insert(0, word)

print("\n".join(song))


** create an Anaerobe of the song (remove all r's)

song = [woord.replace("r","") if "r" in word else word for word in song]

print(song)

song = " \n".join(song)


    • Exercise: remove letter 't' and rewrite song using capitals, comma's and hard returns


* WHILE

A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. The risk of using 'while' is the possibility of triggering infinite loops.

* Print your song 9 times

amount = 0

while (amount < 10):

print(song)

amount = amount + 1

else:

print("Python can be a printing factory!")


* The reader can decide how many times she would like to see the song

nbr = raw_input("Give a number  :")

amount = 0

while (amount < 5):

print(song)

amount = amount + 1

else:

print("Python can be a printing factory!")


* write your text to a file

with open('song.txt', 'a') as f:

f.write("title song" + "\n" + song)