Actions

Python for beginners: Difference between revisions

From Algolit

(Created page with "== Literary Python for Beginners == === LETTER * WORD * SENTENCE === * Introduction to the objects string & list with their different attributes * uses the shell or integrat...")
 
 
(19 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Literary Python for Beginners ==
+
Next pages: [[Python_for_beginners/collections|Collections]] // [[Python_for_beginners/loops_and_conditions|Loops and Conditions]] // [[Python_for_beginners/anthology|Create anthology]]
  
=== LETTER * WORD * SENTENCE ===
+
'''=== VARIABLES ==='''
  
 
* Introduction to the objects string & list with their different attributes
 
* Introduction to the objects string & list with their different attributes
* uses the shell or integrated development environment
+
* uses the shell
  
** run python 2.7 – installed by default on all platforms
 
  
$ python
+
'''# USING STRINGS'''
  
>>>
+
A string is a chain of characters / text and can contain any type of characters
  
 +
A string is defined by " "
  
** install python idle 2.7 – ways to interact with Python: shell + editor
 
  
 +
'''* Write text using STRING'''
  
 +
>>> print("La Cambre")
  
'''# USING STRINGS'''
+
** Exercise: Write your name'''
  
A string is a chain of characters / text and can contain any type of characters
+
>>> ...
  
A string is defined by " "
 
  
'''* write letter using STRING'''
+
'''* Adding text'''  
  
>>> "a"  
+
>>> print("Brussels"+"Paris")
  
'''* write several letters'''
+
>>> print("Brussels "+"Paris")
  
>>> "a, b, c, d"
+
** Exercise: Write your address'''
  
'''* write combinations'''
 
  
>>> "a" + "b"
+
'''* Composing a sentence'''
  
>>> 3
+
>>> print("Paris", "to", "London", "via", "Brussels")
  
>>> "a" + "and" + "b"  
+
>>> print("Paris to London via Brussels")
  
>>> "a" + " and " + "b"
+
** Exercise: Write your favourite expression'''
  
>>> "a" + "+ " + 3 + " is a3"  ***
 
  
>>> 3*3
+
'''* Multiply'''
  
>>> "a" + "+ " + "3" + " is a3"
+
>>> print(3*3)
  
>>> 3 * "algolit" + " in wtc25"  
+
>>> 3 * "algolit" + " in Brussels"  
  
 
+
** Exercise: Write 'I write the alphabet' 3 times.
** Exercise: Write 'I write the alphabet 3 times.'
 
  
 
Note: there are always different possible solutions  
 
Note: there are always different possible solutions  
  
  
'''* write string as variable'''
+
'''* Write a string as a variable'''
  
 
** Avoids having to retype your string each time you use it
 
** Avoids having to retype your string each time you use it
Line 62: Line 59:
 
>>> letter = "a"  
 
>>> letter = "a"  
  
>>> print letter  
+
>>> print(letter)
  
 
>>> word = "algolit"  
 
>>> word = "algolit"  
  
>>> print word  
+
>>> print(word)
  
>>> sentence = "I learn to read and write again at wtc25"  
+
>>> sentence = "I learn to read and write again in Python."  
  
>>> print sentence, letter
+
>>> print(sentence, letter)
  
** Exercise: print your letter, word, sentence
+
** Exercise: Print your letter, word, sentence
  
  
'''* add punctuation'''
+
'''* Add punctuation'''
  
>>> print letter + " " + word + " " + sentence + "."  
+
>>> print(letter + " " + word + " " + sentence + ".")
  
>>> print letter + "! " + word + "? " + sentence + "."  
+
>>> print(letter + "! " + word + "? " + sentence + ".")
  
 
>>> letter = "i"  
 
>>> letter = "i"  
Line 88: Line 85:
  
  
'''* calculate!'''
+
'''* Calculate!'''
  
 
** the length of the string
 
** the length of the string
  
>>> len(letter)  
+
>>> print(len(letter))
>>> len(word)
+
>>> print(len(word))
>>> len(sentence)  
+
>>> print(len(sentence))  
 
+
>>> print(len(word))+2)
 
 
** we can also consider the letter/word/sentence as fields or grids, in which each letter occupies a specific position
 
 
 
Note:  computer starts to count from 0
 
 
 
>>> word[0]
 
>>> word[3]
 
 
 
** Exercise: what is the middle letter of your sentence?
 
 
 
 
 
'''* Slicing and concatenating strings in order to select letters & compose new words'''
 
 
 
** find last letter
 
 
 
>>> zin[-1]
 
 
 
** find last but one letter
 
 
 
>>> word[-2]
 
 
 
** find first two letters
 
 
 
>>> word[0:2]
 
 
 
or
 
 
 
>>> word[:2]
 
 
 
** find 3 letters in the middle
 
 
 
>>> word[2:5]
 
 
 
** find from 3rd letter till end
 
 
 
>>> word[2:]
 
 
 
** Exercise: If the word is "solidarity" is, what do you read here?
 
word[:5] + word[3:]
 
 
 
** Exercise: rewrite the word as 'liquidity', using slicing
 
 
 
 
 
'''* write with capitals'''
 
 
 
>>> print letter.lower()
 
 
 
>>> print sentence.upper()
 
 
 
 
 
'''* write first word of sentence with capital letter'''
 
 
 
>>> print sentence.capitalize()  
 
 
 
 
 
'''* note the difference'''
 
 
 
>>> sentence.title()  
 
 
 
>>> word.title()
 
 
 
 
 
[[Some_Python_Vocabulary]]
 
 
 
[[Loops_and_conditions]]
 
 
 
[[Anthology]]
 
 
 
# Some Python vocabulary
 
## the string or string object is a MODULE in Python
 
 
 
# A MODULE simply is a file, which contains Python statements.
 
Normally among these there are:
 
* definition statements -> the execution of the module defines some functions
 
* class statements -> the execution of the module defines some classes.
 
A module may also contain names (variables) and other directly executable
 
Python statements.
 
# you can write your own definitions/functions and save them I a file that you can import into another python-file
 
# such a document is an external module, called at the beginning of a script using 'import name_module'
 
# CLASSES contain METHODS, a series of FUNCTIONS that are part of a class
 
# the string-module contains classes with functions that allow you to calculate the length of the sting, slice etc
 
 
 
# Anything in Python can be an OBJECT, because it can be assigned to a variable or can be an argument (input) for a function - OBJECT ORIENTED PROGRAMMING
 
 
 
# an ATTRIBUTE is is a way to move from one object to the other
 
# “Apply the power of the almighty dot” - objectname.attributename – and magic!
 
 
 
# !!! to know the attributes of an object: dir()
 
# This means the object has a method  called __dir__()
 
# dir() calls this method and prints the list of attributes
 
 
 
dir(letter)
 
 
 
# choose for example .endswith()
 
sentence = "This is so exciting!"
 
suffix = "ing!"
 
print sentence.endswith(suffix)
 
len(sentence)
 
print sentence.endswith(suffix,20) -> False
 
print sentence.endswith(suffix,16) -> True
 
print sentence.endswith(suffix,16,20) -> True
 
 
 
# Exercise: think of formula that gives TRUE for suffix 'is'
 
# a long string can be annotated using 3 """ a lot of words """
 
# if you have a very long string, you better use:
 
very_long_string = (
 
    "For a long time I used to go to bed early. Etc etc …."
 
  )
 
 
 
### From STRINGS to LISTS
 
 
 
# DISADVANTAGE fo STRINGS: they're immutable
 
# that is the reason you want to change your string into a list
 
sentence.split()
 
# and save it as a new variable
 
list_words = sentence.split()
 
 
 
# some of the attributes of string can be used for lists
 
# Exercise: which previously mentioned attributes function for lists?
 
 
 
# change a list
 
list_words[3] = "wtc25"
 
print list_words
 
 
 
# remove words
 
list_words[2:3] = []
 
note: list_words[2] = [] → this removes your 3rd element and replaces it by an empty sublist ('nested list')
 
 
 
# put back words
 
list_words[2:3] = ["so", "exciting"]
 
 
 
# you can shorten a list
 
list_words[-3:]
 
# and save the shortened list into a new variable – the old continues to exist
 
yezzzz = list_words[-3:]
 
 
 
# you can combine lists, group two in one
 
text = [list_words, yezzzz]
 
# and you can call an element of a sublist
 
word = text[1][2]
 
 
 
# you can concatenate lists, merge two into one
 
print  list_words + yezzzz
 
poem =  list_words + yezzzz
 
 
 
# you can add words to your list
 
poem.append("is")
 
print poem
 
 
 
# you can sort your list alphabetically
 
poem.sort()
 
 
 
 
 
 
 
# you transform your list into a string again
 
" ".join(poem)
 
# detail: the whitespace / try without
 
" ".join(poem) + "?"
 
 
 
# you can empty your list // we have a brand new sheet of paper!!
 
poem[:] = []
 
 
 
 
 
 
 
### LOOPS & CONDITIONS
 
 
 
# using scripts (modules)
 
# shell is ok to try out lines of code, but for longer bits we use script, or module
 
# save file as .py
 
#!/usr/bin/env python
 
# -*- coding: utf-8 -*-
 
 
 
 
 
# REMIX SONG using STRING, LIST and FOR, IN, IF, WHILE
 
 
 
# Prince, Purple Rain
 
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 songs 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)
 
http://oulipo.net/fr/contraintes/anaerobie
 
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.
 
 
 
# Print your song 9 times
 
amount = 0
 
while (amount < 10):
 
  print(song)
 
  amount = amount + 1
 
else:
 
print "Python can also 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 gedicht
 
  amount = amount + 1
 
else:
 
print "Python can also be a printing factory!"
 
 
 
 
 
# write your text to a file
 
with open('song.txt', 'a') as f:
 
f.write("title song" + "\n" + song)
 
 
 
### TEXT
 
 
 
# you can print any text file
 
# note: in this case the text is in the same folder as the script, otherwise adapt path
 
with open('peter_rabbit.txt') as f:
 
    for line in f:
 
        print line
 
 
 
# now you can call operations on this text
 
new_text = []
 
with open('peter_rabbit.txt') as f:
 
    for line in f:
 
for word in line:
 
if len(word) >= 5:
 
newtext.append(word)
 
print(“ “.join(new_text))
 
 
 
 
 
# remove punctuation
 
import string
 
def remove_punct(f):
 
tokens = (' '.join(line.replace('\n', '') for line in f)).lower()
 
for c in string.punctuation:
 
tokens= tokens.replace(c," ")
 
return tokens
 
 
 
tokens = remove_punct(f)
 
  
# random choice & shuffle
+
** and more
from random import choice, shuffle
 
names = [peter, benjamin, flopsy, tod, tom, samuel, pie, ginger, moppet, nutkin, timmy, tailor, johnny, mice, tittlemouse, tiggy, rabbit, jemima, jeremy, robinson, pigling]
 
  
def select(names):
+
a_number = len(word)+2
    name = choice(names)  
+
print(a_number)
    return name
+
a_number += 3
 +
print(a_number)
  
mix = shuffle(names)
+
** Exercise: Compose a sentence word by word, specifying each word as a variable. The length of the sentence is 20.
  
# proposal to publish an anthology as a pdf
 
* play with search for words in texts with certain suffixes from texts, remove letters
 
* write new text to file
 
  
* once all files are finished:
+
'''What you've learned'''
$ cat partfilename* > outputfilename
+
 
$ pandoc input.txt -o output.pdf
+
* variable
 +
* value
 +
* assignment operator (=)
 +
* difference between variables and values
 +
* integers
 +
* print()

Latest revision as of 15:04, 21 November 2020

Next pages: Collections // Loops and Conditions // Create anthology

=== VARIABLES ===

  • Introduction to the objects string & list with their different attributes
  • uses the shell


# USING STRINGS

A string is a chain of characters / text and can contain any type of characters

A string is defined by " "


* Write text using STRING

>>> print("La Cambre")

    • Exercise: Write your name

>>> ...


* Adding text

>>> print("Brussels"+"Paris")

>>> print("Brussels "+"Paris")

    • Exercise: Write your address


* Composing a sentence

>>> print("Paris", "to", "London", "via", "Brussels")

>>> print("Paris to London via Brussels")

    • Exercise: Write your favourite expression


* Multiply

>>> print(3*3)

>>> 3 * "algolit" + " in Brussels"

    • Exercise: Write 'I write the alphabet' 3 times.

Note: there are always different possible solutions


* Write a string as a variable

    • Avoids having to retype your string each time you use it
    • You can change values at any time of the writing process

>>> letter = "a"

>>> print(letter)

>>> word = "algolit"

>>> print(word)

>>> sentence = "I learn to read and write again in Python."

>>> print(sentence, letter)

    • Exercise: Print your letter, word, sentence


* Add punctuation

>>> print(letter + " " + word + " " + sentence + ".")

>>> print(letter + "! " + word + "? " + sentence + ".")

>>> letter = "i"

>>> print letter + "! " + word + "? " + sentence + "."

    • Exercise: change content of one of variables, over and over, see how result changes


* Calculate!

    • the length of the string

>>> print(len(letter)) >>> print(len(word)) >>> print(len(sentence)) >>> print(len(word))+2)

    • and more

a_number = len(word)+2 print(a_number) a_number += 3 print(a_number)

    • Exercise: Compose a sentence word by word, specifying each word as a variable. The length of the sentence is 20.


What you've learned

  • variable
  • value
  • assignment operator (=)
  • difference between variables and values
  • integers
  • print()