-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmynotes.py
2472 lines (2111 loc) · 109 KB
/
mynotes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
INSTALLTION
-----------
Linux
-----
Linux is a varied operating system with a bunch of different ways to install software. I’m assuming
if you are running Linux then you know how to install packages, so here are your instructions:
1. Use your Linux package manager and install the gedit text editor.
2. Make sure you can get to gedit easily by putting it in your window manager’s menu.
a. Run gedit so we can fix some stupid defaults it has.
b. Open Preferences and select the Editor tab.
c. Change Tab width: to 4.
d. Select (make sure a check mark is in) Insert spaces instead of tabs.
e. Turn on Automatic indentation as well.
f. Open the View tab and turn on Display line numbers.
3. Find your Terminal program. It could be called GNOME Terminal, Konsole, or xterm.
4. Put your Terminal in your dock as well.
5. Run your Terminal program. It won’t look like much.
6. In your Terminal program, run Python. You run things in Terminal by just typing the
name and hitting Enter.
a. If you run Python and it’s not there, install it. Make sure you install Python 2, not
Python 3.
7. Type quit() and hit Enter to exit Python.
=================================================================================================================
excerise 1:
print "hi "
print "hello again"
print "I'm typing this"
Example of an error message
$ python ex/ex1.py
File "ex/ex1.py", line 3
print "I like typing this.
^
SyntaxError: EOL while scanning string literal
It’s important that you can read these, since you will be making many of these mistakes. Even I
make many of these mistakes. Let’s look at this line by line.
1. Here we ran our command in the Terminal to run the ex1.py script.
2. Python then tells us that the file ex1.py has an error on line 3.
3. It then prints this line for us.
4. Then it puts a ^ (caret) character to point at where the problem is. Notice the missing "
(double- quote) character?
5. Finally, it prints out a SyntaxError and tells us something about what might be the error.
Usually these are very cryptic, but if you copy that text into a search engine, you will find someone else who’s had that error and myou can probably fi gure out how to fix it.
#********#
*WARNING!*
#********#
If you are from another country and you get errors about ASCII encodings,then put this at the top of your Python scripts:
# - *- coding: utf- 8 - *-
It will fi x them so that you can use Unicode UTF- 8 in your scripts without a problem.
======================================================================================================================
Comments are very important in your programs. They are used to tell you what something does in English, and they also are used
to disable parts of your program if you need to remove them temporarily.
ex 2:
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
========================================================================================================================
Number and Maths
+ plus - minus / slash * asterisk % percent < less- than > greater- Than <= less- than- equal
>= greater- than- equal
ex3:
print "i will count my hens"
print "Hens", 25+30/6
print"Now i will count eggs", 3
print float(3+2+1-5+4%2-1/4+6)
print "is it true that 3+1<5-7"
print float(3+1<5-7)
print "what is 3+2", 3+2
print "what is 5-7", 5-7
print "oh that's why it is false"
print "now let's find out area of a circle with radius 5 cm", float(3.14*5*5)
What is the order of operations?
In the United States we use an acronym called PEMDAS, which stands for Parentheses Exponents
Multiplication Division Addition Subtraction. That’s the order Python follows as well.
==========================================================================================================================
Variables And Names
A variable is nothing more than a name for something so you can use the name rather than the something as you code.
ex4:
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
if cars >= drivers:
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
” Every time you put " (double- quotes) around a piece of text, you have been making a string"
ex 5:
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
Conversion Meaning Notes
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal. (1)
u Unsigned decimal.
x Unsigned hexadecimal (lowercase). (2)
X Unsigned hexadecimal (uppercase). (2)
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()). (3)
s String (converts any python object using str()). (4)
% No argument is converted, results in a "%" character in the result.
Notes:
(1) The alternate form causes a leading zero ("0") to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.
(2) The alternate form causes a leading '0x' or '0X' (depending on whether the "x" or "X" format was used) to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.
(3) The %r conversion was added in Python 2.0.
(4) If the object or format provided is a unicode string, the resulting string will also be unicode.
How can I round a fl oating point number?
You can use the round() function like this: round(1.7333).
I get this error TypeError: 'str' object is not callable.
You probably forgot the % between the string and the list of variables.
================================================================================================================================
Strings and Text
----------------
strings are allways enclosed in double quotes ("") or in single quotes ('') this is how python knows that we are making a string.
string may conatin format charecters, FOR EG %d , %s .you simply put the formatted variables in the string, and then a
% (percent) character, followed by the variable. The only catch is that if you want multiple formats in your string to print multiple variables, you need to put them inside ( ) (parentheses) separated by , (commas).
Python has join() method to concatenate a string.
''.join(['the','quick','brown','fox','jumps','over','dog'])
>>> print ‘red’ + ‘yellow’
Redyellow
>>> print ‘red’ * 3
Redredred
>>> print ‘red’ + str(3)
red3
>>> print ‘red’ + 3
Traceback (most recent call last):
File “”, line 1, in
TypeError: cannot concatenate ‘str’ and ‘int’ objects
>>>
String Formating with % Operator
--------------------------------
x = ‘apples’ y = ‘lemons’
z = “In the basket are %s and %s” % (x,y)
String Formating with {} Operator
---------------------------------
When you use the curly braces or {} operators, they serve as place-holders for the variables you would like to store inside a string. In order to pass variables to a string you must call upon the format() method. One benefit of using the format() method is that you do not have to convert integers into a string before concatenating the data. It will do that automatically for you. This is one reason why it is the preferred operator method.
Fname = “John”
Lname = “Doe”
Age = “24”
print “{} {} is {} years old.“ format(fname, lname, age)
ex 6: Strings
x = "There are %d types of people." % 10 #here we define a variable x which holds a string and we are inserting 10 in bet the string
binary = "binary" #here we declared and initialized the varibale biinary with value equals binary
do_not = "don't" #here we decalared and initialized another variable do_not
y = "Those who know %s and those who %s." % (binary, do_not)#here we are inserting two variable inside a string
print x #printing var x
print y #printing var y
print "I said: %r." % x #inserting a string in a string
print "I also said: '%s'." % y #inserting string in a string
hilarious = False #declaring and initializing the variable
joke_evaluation = "Isn't that joke so funny?! %r" #initializing the variable
print joke_evaluation % hilarious #printing two var holding strings using % operator
w = "This is the left side of..." #def a var
e = "a string with a right side." #def a var
print w + e #concatenating and printing two strings
What is the difference between %r and %s?
We use %r for debugging, since it displays the “raw” data of the variable, but we use %s and others for displaying to users.
==============================================================================================================================
More printing
-------------
ex 7:
print "Mary had a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And everywhere that Mary went."
print "." * 10 # what'd that do? ans print '.' 10 times
end1 = "C" # def a var end1-end12
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12
Couldn’t you just not use the comma , and turn the last two lines into one single- line print?
Yes, you could very easily, but then it’d be longer than 80 characters, which in Python is bad style.
================================================================================================================================
Printing, Printing
------------------
ex 8:
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
I tried putting Chinese (or some other non- ASCII characters) into these strings, but %r prints out
weird symbols.
Use %s to print that instead and it’ll work.
=================================================================================================================================
Printing , Printing, Printing
-----------------------------
# Here's some new strange stuff, remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the days: ", days
print "Here are the months: ", months
print """
There's something going on here.
wit the three double- quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
Why do the \n newlines not work when I use %r?
That’s how %r formatting works; it prints it the way you wrote it (or close to it). It’s the “raw” format for debugging.
=================================================================================================================================
What is That?
-------------
This use of the \ (backslash) character is a way we can put diffi cult- to- type characters into a string.
There are plenty of these “escape sequences” available.
Escape What it does.
\\ Backslash (\)
\' Single- quote (')
\" Double- quote (")
\a ASCII bell (BEL)
\b ASCII backspace (BS)
\f ASCII formfeed (FF)
\n ASCII linefeed (LF)
\N {name} Character named name in the Unicode database (Unicode only)
\r ASCII carriage return (CR)
\t ASCII horizontal tab (TAB)
\u xxxx Character with 16- bit hex value xxxx (Unicode only)
\U xxxxxxxx Character with 32- bit hex value xxxxxxxx (Unicode only)
\v ASCII vertical tab (VT)
\o oo Character with octal value oo
\x hh Character with hex value hh
ex 10:
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
When I use a %r format none of the escape sequences work.
That’s because %r is printing out the raw representation of what you typed, which is going to
include the original escape sequences. Use %s instead. Always remember this: %r is for debugging;
%s is for displaying.print fat_cat
=================================================================================================================================
Asking Question
---------------
print "how old are you?",
age=int(raw_input())
print "what is your weight?",
weight=raw_input()
print "how tall are you?",
tall=raw_input()
print "hey i want to ask some more question"
print"do you know about stuxnet",
#Notice that we put a , (comma) at the end of each print line. This is so that
#print doesn’t end the line with a new line character and go to the next line.
presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. See the docs for raw_input().
Example:
name = raw_input("What is your name? ")
print "Hello, %s." % name
This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code.
Note: This is for Python 2.x in python 3 is renamed to input() but note that input is a vulnerable method as it inputs everything as python code so we can input malicious python code.
How do I get a number from someone so I can do math?
That’s a little advanced, but try x = int(raw_input()), which gets the number as a string from
raw_input() then converts it to an integer using int().
What’s the difference between input() and raw_input()?
The input() function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it.
The raw_input() function in Python 2.x evaluates things before returning.
So as an example you can take a look at this -
>>> input("Enter Something : ")
Enter Something : exit()
This would cause the program to exit (as it would evaluate exit()).
Another example -
>>> input("Enter something else :")
Enter something else :__import__("os").listdir('.')
['.gtkrc-1.2-gnome2', ...]
"
"This would list out the contents of current directory , you can also use functions such as os.chdir() , os.remove() , os.removedirs() , os.rmdir()
"
=================================================================================================================================
Prompting People
----------------
For raw_input, you can also put in a prompt to show to a person so he knows what to type. Put a string that you want for the prompt inside the () so that it looks like this:
y = raw_input("Name? ")
age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
raw_input(...)
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.
input(...)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
=================================================================================================================================
Parameters, Unpacking, Variables
--------------------------------
we will cover one more input method you can use to pass variables to a script (script being another name for your .py fi les). You know how you type python ex13.py to run the ex13.py fi le? Well the ex13.py part of the command is called an “argument.” What we’ll do now is write a script that also accepts arguments.
ex 13
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
run command: python ex13_arguments.py heelo hi chai
output:
The script is called: ex13_arguments.py
Your first variable is: heelo
Your second variable is: hi
Your third variable is: chai
Python feature set.
The argv is the “argument variable,” a very standard name in programming that you will fi nd
used in many other languages. This variable holds the arguments you pass to your Python script
when you run it.
Line 3 “unpacks” argv so that, rather than holding all the arguments, it gets assigned to four
variables you can work with: script, first, second, and third. This may look strange, but
“unpack” is probably the best word to describe what it does. It just says, “Take whatever is in
argv, unpack it, and assign it to all these variables on the left in order.”
the real name of what we are refering to feature is module
these are also known as liberaries
you can get errors when you donot pass enfough arguments
study drill question answer
from sys import argv
ScriptName, first, second, third = argv
print "What is your fourth variable?"
fourth = raw_input()
print "What is your fifth variable?"
fifth = raw_input()
print "What is your sixth variable?"
sixth = raw_input()
print "The script is called: ", ScriptName
print "Your first variable is: ", first
print "Your second variable is: ", second
print "Your third variable is: ", third
print "Your fourth variable is: ", fourth
print "Your fifth variable is: ", fifth
print "Your sixth variable is: ", sixth
print "For your script %r, these are the variables: %r, %r, %r, %r, %r,
and %r." % (ScriptName, first, second, third, fourth, fifth, sixth)
What’s the difference between argv and raw_input()?
The difference has to do with where the user is required to give input. If they give your script
inputs on the command line, then you use argv. If you want them to input using the keyboard
while the script is running, then use raw_input().
Are the command line arguments strings?
Yes, they come in as strings, even if you typed numbers on the command line. Use int() to con-
vert them just like with raw_input().
==================================================================================================================================================
Prompting And Passing
---------------------
ex14: prompting and passing
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
output
------
python ex14_PromptAndPassing.py abhishek
Hi abhishek, I'm the ex14_PromptAndPassing.py script.
I'd like to ask you a few questions.
Do you like me abhishek?
> yes
Where do you live abhishek?
> cooler
What kind of computer do you have?
> apple
Alright, so you said 'yes' about liking me.
You live in 'cooler'. Not sure where that is.
And you have a 'apple' computer. Nice.
I don’t understand what you mean by changing the prompt?
See the variable prompt = '> '. Change that to have a different value. You know this; it’s just a
string and you’ve done 13 exercises making them, so take the time to fi gure it out.
=================================================================================================================================================
Reading Files
-------------
ex15 :
1 from sys import argv #import argv from the sys module
2 script, filename = argv #defines script and filenames are arguments
3 txt = open(raw_input(filename)) #calls a method open on the file passed as an argument
#in above line we can use open , raw_input, or open(raw_input())
4 print "Here's your file %r:" % filename #print the filename
5 print txt.read() #call the read command on the file being passed as an argument
txt.close()
6 print "Type the filename again:" # simple print statement
7 file_again = raw_input("> ") #again ask name of the file
8 txt_again = open(file_again) #call open method on the file name which is passed recently
9 print txt_again.read() #call read method on the file being passedrecently
txt_again.close()
Lines 1–3 should be a familiar use of argv to get a fi lename.
line 5 where we use a new command open.
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
read(...)
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
Line 7 we print a little line, but on line 8 we have something very new and exciting. We call a
function on txt. What you got back from open is a file, and it’s also got commands you can
give it. You give a fi le a command by using the . (dot or period), the name of the command, and
parameters. Just like with open and raw_input. The difference is that when you say txt.read()
you are saying, “Hey txt! Do your read command with no parameters!”
argparse --- https://docs.python.org/dev/library/argparse.html
Does txt = open(filename) return the contents of the fi le?
No, it doesn’t. It actually makes something called a “fi le object.”
=================================================================================================================================================
Reading and Writing Files
-------------------------
close—Closes the fi le. Like File- >Save.. in your editor.
• read—Reads the contents of the fi le. You can assign the result to a variable.
• readline—Reads just one line of a text fi le.
• truncate—Empties the fi le. Watch out if you care about the fi le.
• write(stuff)—Writes stuff to the fi le.
ex 16 :
from sys import argv
script, filename = argv
print "this is your script name %r" % script
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL- C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target1 = open(filename)
target2 = target1.read()
print "raw data in file \n %r" % target2
print "\n\n\n\n"
print "formatted data in file %s"%target2
target1.close()
target = open(filename, 'w')
print "Truncating the file.Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
What does 'w' mean?
It’s really just a string with a character in it for the kind of mode for the fi le. If you use 'w', then
you’re saying “open this fi le in ‘write’ mode”—hence the 'w' character. There’s also 'r' for
“read,” 'a' for append, and modifi ers on these.
What are the modifi ers to the fi le modes we can use?
The most important one to know for now is the + modifi er, so you can do 'w+', 'r+', and 'a+'.
This will open the fi le in both read and write mode and, depending on the character used, posi-
tion the fi le in different ways.
Does just doing open(filename) open it in 'r' (read) mode?
Yes, that’s the default for the open() function.
=================================================================================================================================================
More Files
----------
ex17_morefiles.py -- program to copy one file to another
long code:
from sys import argv
from os.path import exists
script , fromfile, tofile = argv
print "copying file %s from %s" % ( fromfile, tofile)
in_file = open(fromfile, 'r')
indata = in_file.read()
print "the input file is %d bytes long" % len(indata)
print "does the output file exist %r" % exists(tofile)
print "press ctrl+c to quit the program or Enter to continue"
raw_input("?")
out_file = open(tofile, 'w')
out_file.write(indata)
print "Allright Alldone !"
in_file.close
out_file.close
short code:
from sys import argv
script , fromfile, tofile = argv
(open(tofile, 'w')).write(((open(fromfile, 'r')).read()))
I get a Syntax:EOL while scanning string literal error.
You forgot to end a string properly with a quote. Go look at that line again.
===========================================================================================================================================
Names, Variables, Code, Functions
---------------------------------
Functions do three things:
1. They name pieces of code the way variables name strings and numbers.
2. They take arguments the way your scripts take argv.
3. Using #1 and #2, they let you make your own “mini- scripts” or “tiny commands.”
You can create a function by using the word def in Python
First we tell Python we want to make a function using def for “define.”
On the same line as def, we then give the function a name. In this case, we just called
it print_two, but it could be peanuts too. It doesn’t matter, except that your function
should have a short name that says what it does.
Then we tell it we want *args (asterisk args), which is a lot like your argv parameter but
for functions. This has to go inside () parentheses to work
Then we end this line with a : colon and start indenting.
To demonstrate how it works, we print these arguments out, just like we would in a script.
FUNCTION CHECKLIST
------------------
ex18_Function.py
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r arg2: %r" % (arg1, arg2)
# this will only take one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this will print none as no arguments
def print_no():
print "i'm not gonna do anything"
print_two('zed', 'shaw')
print_two_again('abhishek', 'gautam')
print_one('abhishekGautam')
print_no()
1. Did you start your function defi nition with def?
2. Does your function name have only characters and _ (underscore) characters?
3. Did you put an open parenthesis ( right after the function name?
4. Did you put your arguments after the parenthesis ( separated by commas?
5. Did you make each argument unique (meaning no duplicated names)?
6. Did you put a close parenthesis and a colon ): after the arguments?
7. Did you indent all lines of code you want in the function four spaces? No more, no less.
8. Did you “end” your function by going back to writing with no indent (dedenting we call it)?
And when you run (“use” or “call”) a function, check these things:
1. Did you call/use/run this function by typing its name?
2. Did you put the ( character after the name to run it?
3. Did you put the values you want into the parenthesis separated by commas?
4. Did you end the function call with a ) character?
Use these two checklists on the remaining lessons until you do not need them anymore. Finally,
repeat this a few times: “To ‘run,’ ‘call,’ or ‘use’ a function all mean the same thing.”
What does the * in *args do?
That tells Python to take all the arguments to the function and then put them in args as a list. It’s
like argv that you’ve been using, but for functions. It’s not normally used too often unless specifi -
cally needed.
===============================================================================================================================================
Functions and Variables
-----------------------
The variables in your function are not connected to the variables in your script.
Multiple assignments
--------------------
In Python, multiple assignments can be made in a single statement as follows:
a, b, c = 5, 3.2, "Hello"
ex19_Func2.py
def cnc(chesecount, crackercount): #def keyword define we are making a function and cnc is name of func and there are 2 arguments
print "The chese count is %d" % chesecount #simple print statement
print "The Cracker count is %d" % crackercount #simple print statement
print "that's enfough for party man" #simple print statement
cnc(10, 20) #function call
amt_chese=20 #def var
amt_cracker=30 #def var
print "we can pass parameter in form of varibale" #print statement
cnc(amt_chese, amt_cracker) #passing arg via variable
print "we can even do maths while passing the argument" #print statement
cnc(10+30, 30+40) #passing no as arg and doing maths
print "we can combine both variables and maths" # print statement
cnc(amt_chese+10, amt_cracker+20) #arg and mix using var and maths
We can give it straight numbers. We can give it variables. We can give
it math. We can even combine math and variables.
Write at least one more function of your own design, and run it 10 different ways. pg 88
Is it bad to have global variables (like on lines 13 and 14) with the same name as function
variables?
Yes, since then you’re not quite sure which one you’re talking about. But sometimes necessity
means you have to use the same name, or you might do it on accident. Just avoid it whenever
you can.
is there a limit to the number of arguments a function can have?
It depends on the version of Python and the computer you’re on, but it is fairly large. The practical
limit, though, is about fi ve arguments before the function becomes annoying to use.
================================================================================================================================================
Functions and Files
-------------------
ex20_funcnFile.py
from sys import argv #import argv from sys liberary
script, input_file = argv #define the arg
def print_all(f): #def a func print_all
print f.read() #print the content of filef
def rewind(f): #def a func rewind
f.seek(0) #?????????????
def print_a_line(line_count, f): #def a func print_a_line which prints a line and tells line count
print line_count, f.readline() #print a line
current_file = open(input_file) #open a file and store the file object in current_file
print "First let's print the whole file:\n" #simple print statement
print_all(current_file) #calling a function
print "Now let's rewind, kind of like a tape." #simple read statement
rewind(current_file) #calling a func rewind
print "Let's print three lines:"
current_line = 1 #def a var and initialize it
print_a_line(current_line, current_file) #calling a func
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
seek method
-----------
fileObject.seek(offset[, whence])
Parameters
offset -- This is the position of the read/write pointer within the file.
whence -- This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.
It has a “read head,” and you can “seek” this read head around the fi le to positions, then work with
it there. Each time you do f.seek(0), you’re moving to the start of the fi le. Each time you do f.readline(), you’re reading a line from the fi le and moving the read head to right after the \n that ends that fi le.
Why are there empty lines between the lines in the fi le?
The readline() function returns the \n that’s in the fi le at the end of that line. This means that
print’s \n is being added to the one already returned by readline(). To change this behavior
simply add a , (comma) at the end of print so that it doesn’t print its own \n.
Why does seek(0) not set the current_line to 0?
First, the seek() function is dealing in bytes, not lines. So that’s going to the 0 byte (fi rst byte) in
the fi le. Second, current_line is just a variable and has no real connection to the fi le at all. We
are manually incrementing it.
How does readline() know where each line is?
Inside readline() is code that scans each byte of the fi le until it fi nds a \n character, then stops
reading the fi le to return what it found so far. The fi le f is responsible for maintaining the current
position in the fi le after each readline() call, so that it will keep reading each line.
===============================================================================================================================================
Functions Can Return Something
------------------------------
ex21_fcontd.py
def add(a, b):
return a+b
def sub(a, b):
return a-b
def mul(a, b):
return a*b
def div(a, b):
return a/b
c=10
d=20
a=add(c, d)
s=sub(c, d)
m=mul(c, d)
e=div(c, d)
print a
print s
print m
print e
print "magic time"
print "can you do this your self",
print add(c, sub(c, mul(c, div(c, d))))
===============================================================================================================================================
ex22 -->learntsofar.py
===============================================================================================================================================
ex23 --> read some code
===============================================================================================================================================
Some more reading
-----------------
ex24_knowmore.py
print "Let's Know Every Thing" #simple print statement
print "you did \'t know everthing about \t tabs and \n new line of \\ charecters" #print statement with many escape charecters
poem = """
\t twinkle twinkle
little star \n how i wonder what you are
\t up above the sky so high
\n\t like a twinkle in the sky
""" #defining a string in multiple line
print poem #print the poem variable
five = 10-2-6+3 #doing caltn and storing five variable
print "the result is ", five # printing a string and variable
def secret_formula(started): #def a function
jelly_beans = started * 500 #simple calc
jars = jelly_beans / 1000 #simple calc
crates = jars / 100 #simple calc
return jelly_beans, jars, crates #returning 3 values
start_point = 10000 #initializing a variable
beans, jars, crates = secret_formula(start_point) #***********Point to notice
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)#**************point to notice
=================================================================================================================================================
Even More Practice
------------------
string.split = split(s, sep=None, maxsplit=-1)
split(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator.
(split and splitfields are synonymous)
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
(END)
list.pop = pop(...)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
ex25_knowmore2.py
def break_words(stuff):
"""This function will break up words for us"""
words = stuff.split(' ')
return words
def sort_words(words):
"""SORTED WORDS"""
print "Sorted Words: ", sorted(words)
return sorted(words)
def print_first_words(words):
""" PRINT FIRST WORD AFTER POPING IT OFF"""
word = words.pop(0)
print word
def print_last_word(words):
"""Print last word after poping it off"""
word = words.pop(-1)
print word
def sort_sentenses(sentense):
"""TAKE SENTENSE BREAK IT INTO WORDS AND RETURN THE SORTED SEQUENCE OF THE WORDS"""
words = break_words(sentense)
print words
def print_first_and_last(sentense):
"""PRINTS THE FIRST AND LAST WORDS"""
words = break_words(sentense)
print_first_words(words)
print_last_word(words)
def print_first_and_last_sorted(sentense):
"""breaks the sentense and sorts the words and then print first and last"""
words = break_words(sentense)
word = sorted(words)
print_first_words(word)
print_last_word(word)
a = raw_input("Enter the String: ")
print "PRINT FIRST AND LAST"
print_first_and_last(a)
print 'PRINT FIRST AND LAST SORTED'
print_first_and_last_sorted(a)
print 'PRINT SORTED SENTENSES'
sort_sentenses(a)
print 'SORT WORDS'
sort_words(break_words(a))
=================================================================================================================================================
in ide from ex25 import * --> import all form ex25
===============================================================================================================================================
Congratulations, Take a Test!
-----------------------------
ex26
pending
===============================================================================================================================================
Modernizing Logic
-----------------
Logic on a computer is all about seeing if some combination of these characters
and some variables is True at that point in the program.
The Truth Tables
----------------
ex27_truthtables.py