https://stackoverflow.com/questions/26263755/invalid-syntax-for-print-function-in-for-loop
The difference starts at the hardware level; specifically the cpu register that access memory in RAM. How big is that register. It can be 32 bit or 64 bit. This makes a difference in the block of RAM that the operating system decides to allocate to the program that is run.
Then there is software. Some software is compiled for 32 bit machines and some for 64 bit machines. Software that is 64 bit cannot be run on 32 bit CPU . However most 32 bit software can run on 64 bit machines.
If the operating system that is running is 64 bit then we can safely assume that the CPU is 64 bit.
The interpreter is a useful tool for experimentation and testing the syntax. We can also type multiple lines on it:
Ex:
>>> for x1 in "spam":
... print(x1)
...
s
p
a
m
In the above we are writing a "for" loop and the interpreter expects that we type in another statement since the "for" loop needs a body so prints "..." and we place our statement in it ( indented ) . Now we may want to type in more statements so anther "..." is given. If we are done ( as in this case ) we can just hit "Enter" .
If we type in single statements the interpreter remembers the values of variables.
Ex:
>>>
>>> x1=5
>>> course="131B"
>>> x1
5
>>> course
'131B'
>>>
If we come out of the session then all the values are lost. Starting a new session in the interpreter cleans the slate so to speak.
>>>
>>> x1=5
>>> course="131B"
>>> x1
5
>>> course
'131B'
>>> exit()
[amittal@hills ~]$ python3
Python 3.6.2 (default, Aug 7 2017, 08:38:15)
[GCC 6.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x1' is not defined
>>>
In Python we do not have to declare variables before their use but we do need to assign a value to the variables before we can use them.
A key difference between the interpreter and the python executable is that in the interpreter we can print the value of variables just by typing the variable name whereas in a file "*.py" we have to explicitly use the print function.
All the types in Python are objects. We have Numbers and Strings. A list is a an ordered collection that can contain other objects. The objects can be of different types. A list can contain other lists that may contain a variety of objects from a String to a Number and even other lists. A dictionary can contain key, value pairs. Each item is a key and a value. And just like the list we can have different kinds of objects for keys or values. A tuple is like a list but can't be changed once the values have been assigned to it.
This is used to manipulate numbers. We have the usual operations of "*", "/", "+" and "-" . We have the modulus operator that is used to find the remainder :
>>> 8 % 3
2
>>>
The ** when applied to numbers means to the power.
>>> 2 ** 3
8
>>>
We can use the method call "str" to convert a number to a string and also "len" to calculate the length of the string.
Thus :
>>> len( str( 2 ** 1000000) )
301030
>>>
In Python we can import a module. A module is a unit that provides us with functions and additional features.
>>>
>>> import math
>>> math.pi
3.141592653589793
>>>
>>> import random
>>> random.random()
0.3093351259900545
>>>
>>>
>>> random.choice( [1,2,3] )
1
>>> random.choice( [1,2,3] )
3
>>> for x1 in range(5):
... print( x1 )
...
0
1
2
3
4
The range function returns a range object that is a class type and represents a sequence of numbers. As we see
in the above example "range(5)" gives us numbers from 0 to 4 . We can convert a range to a list:
>>> list( range(4) )
[0, 1, 2, 3]
>>>
>>>
A String is a sequence of characters. A literal string can be represented as some word in quotes such as "Test" .
We can also access individual characters with the indexing using the square brackets.
>>> str1="Test"
>>> str1[0]
'T'
>>> str1[3]
't'
>>>
>>>
We can also use the function "len" to find the length of a string .
>>> len(str1)
4
>>>
>>>
>>>
We can use negative indexes also. If we say "str1[-1]" then that means the last element. We can also think of it as str1[ len(str1) - 1 ]
In our case
str1[ 4 -1 ]
str1[3]
will give us "t"
Slicing allows us to cut a section of the string.
Ex:
>>> str1="Test"
>>> str1[1:3]
'es'
>>>
There are 2 numbers and a colon between them . The first number is when the indexing starts and continues till the position of the second number but not including the index. So the index starts for 1 and goes to 2 .
What does str1[-3: -1] do ? We have to go by positions. the first number "-1" points to the last element and the "-3" is going from the right so we have the string:
>>> str1="Test"
>>> str1[-3:-1]
'es'
>>>
>>>
If we have 2 strings:
str1 = "Thise"
str2 = "eclasse"
How can we compose a string by taking out the wrong characters in the 2 strings.
str3 = str1[0:4] + " " + str2[1:6]
>>> str1 = "Thise"
>>> str2 = "eclasse"
>>>
>>> str3 = str1[0:4] + " " + str2[1:6]
>>> str3
'This class'
If we don't have a number then the default numbers come into play. The first number by default is 0 and the second number is the length of the string.
>>> str1[:] + " " + str2[:]
'Thise eclasse'
str1="This"
str1[1:]
"his"
str1[:4]
"This"
Putting invalid values gives us an empty string:
>>> str1="This"
>>> str1[-1:-3]
''
>>>
We can also make copies of strings using the command:
>>> str1="cat"
>>> str1 * 3
'catcatcat'
>>>
Type Specific vs General Methods
The methods we have seen being used are general . These are methods such as len and slicing operations.
>>> str1="Class"
>>> len( str1 )
5
>>>
>>>
>>> str1[0:2]
'Cl'
>>>
>>> list1=[ 10 , 20, 30]
>>> len( list1 )
3
>>> list1[0:2]
[10, 20]
>>>
Both the "len" operation and the slicing methods can be applied to a sequence object. A type can also have methods that are specific to it only and cannot be applied to other objects.
Ex: find
str1 = "Spam"
print( str1.find( "am" ) )
print ( str1.find( "cat" ) )
Output:
[amittal@hills String]$ python3 str_find1.py
2
-1
The "find" method prints the "index" of the word that is specified in the argument to "find" and if it does not find a match then it prints "-1" .
Similarly the method "replace" can replace a matched string.
>>> str1 = "The dog eats the food."
>>> str1.replace( "dog" , "cat" )
'The cat eats the food.'
>>> str1
'The dog eats the food.'
>>>
We can see in the above example that the original "str1" did not get changed. The "replace" produced a new string with the word replaced.
The "split" method will produce a list of words that are separated. If we don't specify a separator character then the
>>> str1 = "The dog eats the food."
>>> str1.split()
['The', 'dog', 'eats', 'the', 'food.']
>>>
>>>
>>> str1 = "The,dog,eats,the,food."
>>> str1.split(",")
['The', 'dog', 'eats', 'the', 'food.']
>>>
The "strip" method will strip the spaces at the ends of the string.
>>> str1 = " The,dog,eats,the,food. "
>>> str1.strip()
'The,dog,eats,the,food.'
The "strip" works on new lines and tabs also.
>>> str1 = " The,dog,eats,the,food. \t\n "
>>> str1.strip()
'The,dog,eats,the,food.'
A tab is what is printed out when we hit the "tab" key. It looks like a bunch of spaces but isn't. It has a value of 10 in the ascii chart and is a character by itself.
The "rstrip" method will strip out spaces only on the right hand side.
Ex:
>>> str1 = " The,dog,eats,the,food. "
>>> str1.rstrip()
' The,dog,eats,the,food.'
>>>
Formatting
Python strings have support for formatting. Formatting is important when we don't have a constant string and need to create a string based on variables.
There are 2 ways of doing it.
>>> "%s are in a %s" % ("We" , "Course." )
'We are in a Course.'
>>>
In the above example we are using "%" to create 2 different parts. The left part is our string but has "%s" as placeholders. On the right hand side we provide values for those place holders. Using integers:
>>> "Temperture is %d" % ( 100 )
'Temperture is 100'
>>>
There are many different formatting options similar to "%d" and "%s" . The other way to do formatting is:
>>> "Temperture is {} ".format( "Very high." )
'Temperture is Very high. '
>>> '{:d}'.format(296999)
'296999'
Immutability
When we create a string object the string object cannot be modified. We can create a new string object and assign it to the the same variable.
Ex:
>>> str1="This"
>>> str1="Class"
>>> str1
'Class'
>>>
The variable "str1" has been assigned a new String variable. The property __repr__ lets us print out the address of the object.
>>> str1="Test"
>>> str1.__repr__
<method-wrapper '__repr__' of str object at 0x7f31b5704148>
>>> str1="Class"
>>> str1.__repr__
<method-wrapper '__repr__' of str object at 0x7f31b57040a0>
>>>
>>>
We can see that when we assigned the string "Class" to "str1" we created a new object at address:
"0x7f31b57040a0" .
Once we create the object we cannot modify the same String object.
>>> str1="Test"
>>> str1[0] = 'R'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
str1 = "Shrubbery"
print( str1.__repr__ )
list1 = list( str1 )
list1[1] = "c"
str2 = ''.join( list1 )
print( str2.__repr__ )
Output:
<method-wrapper '__repr__' of str object at 0x7fefa329a5f0>
<method-wrapper '__repr__' of str object at 0x7fefa3281970>
Even though we changed the original string we did it by creating a new object and not modifying the original object. Using the type conversion :
list( str1 )
converts the string to a list by placing each character in the list . The type "bytearray" is another type that can hold characters.
B1 = bytearray( b'spam')
print( B1.__repr__ )
B1.extend( b'eggs')
print( B1.__repr__ )
print( B1 )
This time we use the method "extend" to add another string to the original object.
Output:
<method-wrapper '__repr__' of bytearray object at 0x7f8b8d32e030>
<method-wrapper '__repr__' of bytearray object at 0x7f8b8d32e030>
bytearray(b'spameggs')
In the above case we can see that the object address did not change and the value of the String object did get changed in place.
The list type is a sequence and is mutable. It represents a collection of objects . The objects can be of different types. Python does not have arrays but similar functionality can be provided for by lists.
Lists will support the basic sequence operations .
Ex:
list1 = [ 1,5 ]
print( list1 )
print( list1[0:1] )
list1.append( 11 )
print( list1 )
list1 = list1 + [ 6, 7]
print( list1 )
list1 = list1 * 2
print( list1 )
print( len( list1 ) )
Output:
[amittal@hills List]$ python3 list1.py
[1, 5]
[1]
[1, 5, 11]
[1, 5, 11, 6, 7]
[1, 5, 11, 6, 7, 1, 5, 11, 6, 7]
10
The above program shows some of the operations that can be performed on a list. Many of these operations can be applied to any sequence type.
>>> list1 = [ 1 ,2 ]
>>> list1[2] = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
A list cannot grow automatically as the above example shows. We can use the "append" method to add an object to the end of the list.
List Specific Type Operations
Append will append an object to a list.
>>> list1 = [ 1, 2 ]
>>> list1.append( 3 )
>>> list1
[1, 2, 3]
>>>
The operation "pop" does the opposite and that is remove the element.
>>> list1
[1, 2, 3]
>>> list1.pop(1)
2
>>> list1
[1, 3]
In the above example the "pop" function will remove the element at position 1 and the new list is printed out.
>>> list1
[1, 2]
>>>
>>> list1.insert( 1 , 10 )
>>> list1.insert( 0, 5 )
>>> list1
[5, 1, 10, 2]
>>>
The above shows the "insert" method being used. We can specify the index position along with the element.
>>> list1
[5, 1, 10, 2]
>>> list1.sort()
>>> list1
[1, 2, 5, 10]
>>>
The "sort" method sorts the list.
>>> list2 = list1.sort()
>>> list2
>>> type( list2 )
<class 'NoneType'>
>>>
The sort method does not return another list. in fact we can see that it does not return anything. It modifies the list in place.
>>> list1.reverse()
>>> list1
[10, 5, 2, 1]
>>>
The method "reverse" reverses the list.
List Comprehensions
We can use a "for" loop inside a list to create a new list. The for loop will iterate over a sequence.
Ex:
>> list2 = [ [x1, x1*2] for x1 in range(5) ]
>>>
>>>
>> list2
[[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
In the above example we have the variable "x1" that iterates over a sequence. A sequence can be thought of as a list of elements ( in this case the elements 0,1,2,3,4 ) . Now for each of those values we create a list of elements where the first element is "x1" and the next element is "x1*2" . Each of these mini list of 2 elements is placed inside the big list giving us:
[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
>>> list3 = [ sum(x1) for x1 in list2 ]
>>> list3
[0, 3, 6, 9, 12]
From the "list2" we can create another list. The function "sum(x1)" will calculate the sum of the elements in each mini list and thus we have list3.
Let's say we have a string:
>>> str1 = "The dog runs."
And we have to create a list where each element in the list is the word in the string repeated twice. We can use comprehension in the following way:
>>> list1 = [ x1 + " " + x1 for x1 in str1.split() ]
>>> list1
['The The', 'dog dog', 'runs. runs.']
The "split" function generates a list of the words and for each word we are doing "x1 + " " + x1" to generate the double word separated by a space. We can also use the technique "x1*2" but then we wouldn't get the space in between the words.
>>> str1 = "The dog runs."
>>> list1 = [ x1*2 for x1 in str1.split() ]
>>> list1
['TheThe', 'dogdog', 'runs.runs.']
>>>
It is worth noting that every comprehension statement can be converted into normal statements also. The above can also be written as:
>>> list1=[]
>>> str1 = "The dog runs."
>>> for x1 in str1.split() :
... list1.append( x1 * 2 )
...
>>> print( list1 )
['TheThe', 'dogdog', 'runs.runs.']
>>>
In the Python interpreter we cannot just use the "print" statement right after the "for" loop.
https://stackoverflow.com/questions/26263755/invalid-syntax-for-print-function-in-for-loop
A set contains unordered collection of elements. Like the dictionary; a set is represented by the curly brackets. However if we start with the empty braces then we end up with a dictionary instead of a set.
>>>
>>> set1={}
>>> type( set1 )
<class 'dict'>
>>>
>>> set1 = {None}
>>> type( set1 )
<class 'set'>
>>> len( set1 )
1
Since we inserted only 1 element ( the blank element ) Python knows that our collection is a set. We can create a set in different ways.
>>> set1 = set ( "apple" )
>>> set1
{'p', 'a', 'e', 'l'}
>>>
A set only contains unique elements so the extra "p" got taken out. Another thing to notice is that the order is different from what we initially put in the set.
>>> set1 = {None}
>>> set1.add( 10 )
>>> set1.add( 20 )
>>> set1
{10, 20, None}
>>> len( set1 )
3
>>>
We can have operations on sets:
>>> X1 = set( "ham" )
>>> Y1 = set( "hat" )
Union of 2 sets
>>> X1 | Y1
{'h', 'a', 'm', 't'}
Intersection of 2 sets
>>> X1 & Y1
{'h', 'a'}
Deifference
>>> X1 - Y1
{'m'}
>>> Y1 - X1
{'t'}
Elements that are not in common to the 2 sets
>>> X1-Y1 | Y1-X1
{'m', 't'}
>>> X1-Y1 & Y1-X1
set()
>>>
Concept of Text Files. Ultimately files contain bytes whether they are text files or binary files. So what is the difference ? One difference is in opening the files. If we do a "cat" in Unix on a text file we will see content that we can read and for a binary file we will see gibberish characters. Both files are stored as bytes. Recall that the ASCII chart contains mappings in the range 0-127 for the English language. Other languages may contain different mappings but let's stick with the ASCII chart right now. The chart will
map the bytes to characters and when we open or print the file contents we will see text content. Mostly we will see the bytes as 0-127 but for other languages we might see the higher numbers also.
Encoding and Decoding
We will see these terms a lot when discussing text and binary files. First we need to use a mapping . This is known by different terms but we can use the term mapping or encoding. As an example we can say that we want to use Ascii scheme.
In this scheme "A" is represented as 65 . So if we want to store the character "A" in the computer we need to find the number. We do this by looking up the mapping chart. The number we find is 65 . This is encoding.
Now let's say it's time to print the variable. We get the value of the variable and that is 65 . Now we need to find the character associated with this number so we "decode" to get the character "A".
The above mapping scheme is "Ascii" but is not the only scheme around. Ascii cannot handle languages that need more than 255 characters. A different scheme "Unicode" can take care of all the languages in the world and the characters they represent. The unicode can store a character in multiple bytes and not just 1 byte to accommodate the large number of characters found in different languages. The default coding in Python is Ascii .
A binary file can basically store anything . It may be an image file or numbers stored in their 4 byte or 2 byte representations. There is no one single chart doing the mappings. The data is not text data but can be machine executable code or a proprietary format such as Microsoft Word.
Let's write a program to write some text to a file.
Ex:
fileObject1 = open('data.txt', 'w')
fileObject1.write('Hello\n') # Write strings of characters to it
fileObject1.write('world\n') # Return number of items written in Python 3.X
fileObject1.close()
We can also read back the data:
Ex:
file1 = open('data.txt') # 'r' (read) is the default processing mode
text = file1.read() # Read entire file into a string
print(text)
In the above the whole contents of the file are read into the variable "text" .
When writing to a file using the above approach we can only write strings.
Ex:
fileObject1 = open('data.txt', 'w')
fileObject1.write('Hello\n') # Write strings of characters to it
var1=15
fileObject1.write( var1 ) # Return number of items written in Python 3.X
fileObject1.close(
Output:
[amittal@hills Files]$ python3 file3.py
Traceback (most recent call last):
File "file3.py", line 4, in <module>
fileObject1.write( var1 ) # Return number of items written in Python 3.X
TypeError: write() argument must be str, not int
We can use Unicode to write out the characters in other languages.
Ex:
first_name = u'\u0905' + u'\u091c' + u'\u092f'
print( first_name )
[amittal@hills Files]$ python3 uni1.py
अजय
The unicode characters can be specified using the "\u" and then 2 hexadecimal characters after it. However the encoding is actually different.
first_name = u'\u0905' + u'\u091c' + u'\u092f'
print( first_name )
print( first_name.encode('utf-8') )
Output:
[amittal@hills Files]$ python3 uni1.py
अजय
b'\xe0\xa4\x85\xe0\xa4\x9c\xe0\xa4\xaf'
1)
Using range and the list comprehension complete the following line:
>>> list1=[ for x1 in range(5) ]
>>> list1
>>> list1
[[0, 0], [2, 3], [4, 6], [6, 9], [8, 12]]
The range will produce numbers from 0 to 4 . We want to produce a list containing objects that are list of 2 numbers with the x1 multiplied by 2 and 3 for each value of x1 .
2)
Given a string
str1="The dog runs."
Complete the following comprehension statement to print a list that has each word repeated.
['The The', 'dog dog', 'runs. runs.']
3)
A list can contain digits from 1 to 9. The list is missing one of the digits. Find the
missing digit.
Example given a list
list1 = [ 1,5,6,8,9,7,4,3]
your program should print:
4
4)
#A list will contain some numbers
#Find the highest occurrence and print the number and the occurrence.
list1 = [ 5,5,6,8,9,7,5,3,6,5]
Use the below skeleton to get started
dict1 = {}
maxValue = 1
maxNumber = list1[0]
for x1 in list1 :
if not x1 in dict1 :
else:
print( maxValue )
print( maxNumber )
5)
Write a Python script that will take a sentence and create a list of the characters in it without the space:
6)
A fibonacci sequence has the first 2 numbers as 1 and 1 . The next number is the sum of the previous 2 numbers. Write
a python script that will print the first 10 Fibonacci numbers.
1)
>>> list1=[ [x1*2 , x1*3] for x1 in range(5) ]
>>> list1
[[0, 0], [2, 3], [4, 6], [6, 9], [8, 12]]
2)
>>> list1 = [ x1 + " " + x1 for x1 in str1.split() ]
>>> list1
['The The', 'dog dog', 'runs. runs.']
3)
#A list will contain the numbers
list1 = [ 1,5,6,8,9,7,4,3]
for x1 in range(1,10):
if not x1 in list1:
print( x1 )
4)
#A list will contain some numbers
#Find the highest occurence
list1 = [ 5,5,6,8,9,7,5,3,6,5]
dict1 = {}
maxValue = 1
maxNumber = list1[0]
for x1 in list1 :
if not x1 in dict1 :
#print( x1 )
dict1[x1] = 1
else:
dict1[x1] = dict1[x1] + 1
if ( maxValue < dict1[x1] ) :
maxValue = dict1[x1]
maxNumber = x1
print( maxValue )
print( maxNumber )
5)
str1="This is a sentence."
list1=[]
for word1 in str1.split():
list1 = list1 + list( word1 )
print( list1 )
list1=[]
for word1 in str1.split():
for ch1 in word1:
list1 = list1 + ch1
print( list1 )
list1=[]
list1 = [ x1 for x1 in str1 if x1 != ' ' ]
print( list1 )
6)
list1=[None]
list1=list1*8
print( list1 )
list1[0] = 1
list1[1] = 1
for x1 in range(2,8):
#print( x2 )
list1[x1] = list1[x1-1] + list1[x1-2]
print( list1 )