-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_notes
More file actions
2699 lines (2165 loc) · 86 KB
/
python_notes
File metadata and controls
2699 lines (2165 loc) · 86 KB
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
Python coding
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
python --> means 2.7.3
python3 --> means 3.10.1
***
print("Hello")
# will show "Hello" in the terminal window
message = "Hello"
print(message)
# will give the same result, but this time we used a variable
print --> is a function
message --> is a variable
"Hello" --> is the value of the variable
# text that is not code is shown in orange
variables
# variables can contain letters, numbers, and underscores. They cannot start with a number
# variable names cannot contain spaces, instad we can use underscore
# don't use python programming words to describe variables
# variable names should be consise, but understandable
# be careful to use letter l and O because they can be confused with 1 and 0
# strings
# a string is a series of characters which can have single or double quotes, ie. "this is the text", or 'this is the text'
upper --> capital letters
lower --> small letters
title --> First letter in first and second name is in capital letters
name = "ada lovelace"
print(name.title())
# this will print Ada Lovelace
name = "ada lovelace"
print(name.upper())
# this will print ADA LOVELACE
# combining strings is called concatenation
# adding whitespace & tabs to strings
\t - tab
\n - return, add whitespace between the lines
# remove whitespace
rstrip() --> stripping whitespace on the right side of the string
lstrip() --> stripping whitespace on the left side of the string
strip() --> stripping whitespace on both sides of the string
# printing a .py file directly in terminal instead from geany
- go to the right folder cd xx/xx
- python nameoffile.py
# print
- first write all variables, then print
name = "emma goldman"
print(name)
#numbers
3**2 --> means 3 elevated to 2
examples:
3**3=27 (3*3*3)
6**4+1296 (6*6*6*6)
# for every calculation Python return a result
# numbers with a decimal point is called a float
#str() function
age = 23
message = "Happy birthday + str(age) + "rd birthday!"
print(message)
# if we use the variable without str(), Pyhton don't understand how to interpret it
# for calculations in Geany, we use:
print(8+3) to show result in terminal window
# comments
# if we want to commnt out project in Python we can use #, Python will ignore what follows after this
# say hello to everyone.
print("Hello Pyhton People")
- Pyhton will only interpret and print the second line.
# lists
[] --> indicates a list
# elements in the list are separated by comma
['shoes', jacket' , 'gloves']
# if we want to refer to a specific element in the list we write:
colors = ['red' , 'green' , 'white' , 'black']
print(colors[0])
# the first element on the list is numbered 0 (index)
# we can add upper, lower or title to format the element
colors = ['red' , 'green' , 'white' , 'black']
print(colors[0].title())
bicycles = ['trek' , 'cannondale' , 'redline' , 'specialized']
print(bicycles[-1])
# -1 shows the last element on the list
# -2 shows the second last item om the list
# -3 returns the third item from the end and so forth.
# changing, adding and removing elements from the list
example:
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# with motorcycles[0] = 'ducati' we change the value of the fist item on the list, from honda to ducati.
# append means to add an item, insert mean to at at the specified places in the list. Appending is useful if we don't have the complete list from the beginning and want to add continuously. Insert us useful if we already have a list but need to add something and it needs to be in a specific order.
# removing elements from the list
- can be done according to position or value
- del statement is removal
- example:
del motorcycles[0] --> indicates which position is the list should be removed
# pop() method
- With the pop method you can choose any position in the list to print.
first_owned = motorcycles.pop(0)
print(motorcycles.title())
- we can use both pop() and [x] to point to a position in a list, but pop will remove the item while [x] will not
- we can use both del and pop() to remove an iten from a list. If we want to continue to work with the removed ite, we need to use pop() method
# Removing item by value
- remove() method can be used when we want to remove an item without knowing it's position.
list.remove('whateveritemwewanttoremovefromthelist')
- to be able to understand why we are using remove() we can name the variable and we can point to the variable to print statments about it.
- remove() only removes the first value and if we want it to remove a value every time it occurs, we need a loop
# printing a message to people on a list
guests = ['Kerstin' , 'Elsa' , 'Erika' , 'mother' , 'Louise' , 'Marie' , 'Birgitta' , 'Sandra']
print("Hello " + guests[2] + message + "\n")
- when we use pop() to remove values from alist and want to remove several, the number we want to remove will always be 0
# Sorting a list aphabetically with the sort() method
- It's permanent
- we can also do it in reverse order by writing reverse=True
list.sort() --> for alphabetical order
list.sort(reverse=True)
# sorted() method
- will organize the list in an alphabetical way but not permanently. It can also be used with reverse=True
print(sorted(list, reverse=True))
# reverse() method
- this method will print the list in the reverse order. It's permanent, but can be changes back using the reverse() again.
# len() to find the length of a list
- len(list) --> in interpreter
- print(len(list)) --> in ie. geany
# looping
- can be used if we want to use the same action for every item in a list
- for list in list: --> to print each item on a new line/row. This way we can collectivize action for a list, instead of doing an individual action for each item on the list
- We can choose any name for the variable, ie. for guest in guests, or for cat in cats
- to use singular and plural in the way shown will help us to know if we are work with one item or a list
- we can include as many lines as we want
- A print that is outside of the indent concludes the loop. It will be printed only once.
- indentation is used to show that one line is connected to another
- indentation also helps with organization of blocks of code
- we have to be careful to use it correctly as:
# indent error stops the entire program. Syntax error runs until the point where there is a problem/error
- the : tells python to include what follows in the loop
# To know the index number of an item
- If we don't know the position of an item in a list and want to point to this item, we can:
- print(listname.index('nameofitem')) --> to know the index number of a specific item
- list[list.index('nameofitem')] --> if we want to print the name directly in the message
# range() function
- the range(1,5) will only show the numbers 1-4 and not 5.
- for value in range(1,5):
# for the loop it's difficult to understand how to write variable within that will function according to expectations.
Example:
for value in range(1,51):
print(value, "fuck you, I won't do what you tell me")
names = ['anna', 'sven', 'danny', 'marie', 'olga']
for name in names:
print(name.title())
# for each line a new number will be printed. The message "fuck you..." will be printed next to each number. Because it's a loop and we told python to print the text repeatedly after print the value which is within range 1-51
#Squares
squares = []
# this defines an empty list calles squares
for value in range(1,11):
#we are looping and using values from 1-10
square = value**2
# we are setting a variable inside the loop **2 (square)
squares.append(square)
# every new value is added to the list
print(squares)
# printing complete list outside of the loop
- squares.append(value**2)
# we can write squares.append(value**2) directly to be more concise
# we should focus on writing code that is understandable first and not efficient
#list comprehension
squares = [value**2 for value in range(1,11)]
print(squares)
# as above but concise
threes = [value*3 for value in range(1,31)]
for three in threes:
print(three)
# when it is written 'multiplies' --> it means all number divided by three (3,x,3)
# if it is written multiplied by --> value*3
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
#prints the smallest value
max(digits)
# prints the biggest value
sum(digits)
# prints the totals sum of values in the list
numbers = list(range(1, 500))
# defining range of values
# press q if we want to stop an operation in the terminal
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
# printing the first four
# It is included as in last exercise, the last number is not printed
# when first index isn't specified it starts from the beginning of the list
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
# when the index at the end is not specified -
# it will be printed until the end of the list
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3])
# print the third player from the end
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
# print the last three players
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
# print the three first players each on a new line
# specifying which numbers is don't direcly in for line
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
# [:] refers to the whole my_foods list
# if we remove [:] the two lists will be printed exactly the same
# we want the two list to have a new and each a different item added
my_foods.append('cannoli')
friend_foods.append('ice cream')
# adding a new item on each list
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
# the two prints show the same list because one = the other
items = ['hairbrush', 'tshirt', 'pants', 'socks', 'toothbrush', 'sweater', 'hoodie', 'glasses', 'shoes', 'computer', 'camera']
print("The first three items in the list are:")
for item in items[:3]:
print(item.title())
print("\n\n")
# printing the first three items on the list
print("Three items from the middle of the list are:")
for item in items[4:7]:
print(item.title())
print("\n\n")
# printing three items on index 4, 5 and 6
print("the last three items in the list are:")
for item in items[-3:]:
print(item.title())
# printing the last three items on the list
# tuple
# values that cannot change are called immutable
# an immutable list is called a tuple
dimensions = (200, 50)
print(dimensions[0])
#printing value in first position
print(dimensions[1])
# printing value in the second position
dimensions[0] = 250
print(dimensions[0])
# the value of index 0 cannot be change,
# when it is defined in the first variable
# if we want immutable values for the rectangle;
# it is good that python communicates and error
# PEP8 and styling code
https://www.python.org/dev/peps/pep-0008/
- code length should be no longer than 79 characters
- Some teams use a code length of 99 characters
- comment length should be no longer than 72 characters
- The code should aim to be neat and easy to read
- And also so it's possible to have three windows open at the same time
- Use blank lines to group parts of the program
- There may be code written with older python which doesn't support current style guide
# In Geany --> go to: edit - preferences - editor - indentation (chose replace tabs by spaces, tab width set to 4)
- ctrl I --> creates an indent
- ctrl U --> decreases an indent
- ctrl E --> makes text into a comment in the code
number = 42
number==42
True --> == testing an argument
# list with values printed differently
cars = ['audio', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
# if the car is a bmw it will be printed with upper case letters
else:
print(car.title())
# if it's any other car, it will be printed with first letter upper case
# if --> is a conditional test
car = 'bmw'
car == 'bmw'
# first car equals bmw
# second conditional test on if it's a bmw
# respons is True
car == 'audi'
# would return False
# Checking equality is case sensitive
car = 'Audi'
car == 'audi'
# will get the response: False
# managing case sensitivity when checking equality
car = 'Audi'
car.lower() == 'audi'
True
# we make sure all letters are lower case when testing
# if car is printed it will show 'Audi'still. It doesn't change the variable permanently
# can for example be used to check availability of usernames
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# the requested topping is mushrooms
# if the requested topping is not anchovies, print 'Hold the anchovies!'
# != mean NOT
# mathematical comparison
age = 19
# defining that the age is 19
age < 21
# asking if the number is less than 21
age <= 21
# asking if the number is smaller or equals 21
age > 21
# asking if the number is higher than 21
age >= 21
# asking if the number is highers than or equals 21
# checking multiple conditions
age_o = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21
# asking if age_0 is bigger than or equals 21, and
# if at the same time age_1 is bigger than or equals 21, which as false
age_1 = 22
# age_1 now equals 22
age_0 >= = 21 and age_1 >= 21
# with the change of age_1 variable, the conditions are not met for both
age_0 = 18
# changing variable to 18
age_0 >= 21 or age_1 >= 21
# asking if age_0 or age_1 is bigger than or equals 21
# the condition is met for age_1 which was changed to 22
# when using or the conditions don't have to be met for both
# checking if a certain value is in the list
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
# if the user is not on the list banned_users then a message will be printed\
# including the users name
banned_users = ['andrew', 'carolina', 'david']
user = 'andrew'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
else:
print(" good try!")
# if the user is on the list on banned_users the else option will be printed
# boolean expression (another name for a conditional test)
game_active = True
can_edit = False
# used to keep track of certain conditions, such as if a game is running\
# or if a user can edit content on a website
***
a = 1 a = 1
b = a ==1 b = a == 2
b b
# returns True # returns False
***
if user_name in list_comrades \
and user_password == comrade_password \
or user_name in list_xweser_comrades \
and user_password == xweser_password:
# important to define the whole comparison after 'or" function
# not to think about it as spoken language, but define every step again
# otherwise the function misbehave
# when there are two lists --> on that is a general and one that is xweser, that have different login
# variable return_comrade = True/False if the criteria are met
return_comrade = (user_name in list_comrades
and user_password == comrade_password
or user_name in list_xweser_comrades
and user_password == xweser_password)
if not return_comrade:
# the variable return_comrade is used
# statement: if variable: means it needs value True as a return for action
# if not variable: means that the variable value is not True (is False)
# that the conditions were not met.
# in this case if False (if not True)
# the "not a correct login" message prints
print(
"We are sorry, but your user name and password "
"does not match, please try again."
)
# if-elif-else
# admissions for anyone under age 4 is free.
# admission for anyone between the ages of 4 and 18 is $5.
# admission for anyone age 18 or older is $10.
age = 12
if age < 4:
print("Your admission cost is $0.")
# tests if the person is 4 years old
elif age < 18:
print("your admission cost is $5.")
# is another conditional test that will only run if the previous fails
# because the first test was False, this run and proves True
# the text is printed
else:
print("Your admission cost is $10.")
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
# this code is more efficient and easier to modify
# using multiple elif blocks
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
# this adds and extra condition. if the person is less than 65 years it cost 10
# but if not then it cost 5, so everyone older than 65 will pay 5
# we can also do the code without else: at the end
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
# the last elif mean that if a person is more than or equal to 65 then \
# the cost is 5
# the else block points to everything that is not included in if or elif
# testing multiple conditions
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
# all three are independent tests and evaluated
# mushrooms andextra cheese are found in the list and are printed
# print last text message
# the code wouldn't work with elif since elif stops after a test passes
# because of this only mushrooms would be added and printed together\
# with the text message in the end
# checking for special items
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
# if the requested topping is green peppers,
# it will be printed that we are out right now
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
# all other items on the list will be added
# checking that a list is not empty
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
# using multiple lists
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
# this list could also be made as a tuple if there is a stable selection
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
# if the item in requested toppings is also on the list of available\
# toppings, then it will be added
# if not, then a message will be shared that we don't have it
# because it's a for loop it will go through and check all items
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
# if-elif-else in for loop
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# ~ print(numbers)
for number in numbers:
if number == 1:
# be careful how to write condition
# 1 == numbers mean if 1 is in numbers
# if 1 in numbers will print 'st' every time it finds number 1
# and because it's a loop it will repeat even for other numbers
print(str(number) + "st")
elif number == 2:
# it's also possible to write elif 2 == number:
# watch out for if it's singular or plural reference to list
# number or numbers
print(str(number) + "nd")
elif number == 3:
print(str(number) + "rd")
else:
print(str(number) + "th")
# make sure else is in the for loop
# code structure
users = ['admin', 'tor', 'greta', 'linnea', 'ben']
if users:
for user in users:
if user == 'admin':
# if the user in the list is called 'admin'
print("Hello " + user.title() + ", there is no new updates.")
# printing 'hello admin, there is no updates'
else:
print("Welcome " + user.title() + "!")
# for any other user printing 'Welcome user!'
else:
print("We need to find some users!")
# else on line 8 is outside of the loop
# this code runs only if the first if statement "if users" falls:
# if the list is empty
# a simple dictionary
alien_0 = {'color': 'green', 'points': 5}
# dictionary storing different values about a particular item
print(alien_0['color'])
print(alien_0['points'])
# printing 'green' and '5'
# a dictionary wrapps the information in {}
# a key-value pair is a set of value associated with each other
# every key is connected to its value by a colon
# the key-value pairs are separated by commas
# one key value pair is {'color': 'green'}
# 'color' is a key and the value is 'green'
# we can store as many as we want
# starting with an empty directory
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
# adding values to the dictionary
print(alien_0)
# this prints the dictionary as one line:
# {'color': 'green', 'points': 5}
# accessing values in a dictionary
print(alien_0['color'])
# this print the value green only
new_points = alien_0['points']
# new points equals alien_0 points which is 5
print('You just earned ' + str(new_points) + ' points!')
# adding new key-value pair
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x position'] = 0
alien_0['y position'] = 25
print(alien_0)
# starting with an empty dictionary
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
# works like adding a new key-value pair
# normally we start with empty dictionaries
# modifying values in a dictionary
alien_0 = {'color': 'green'}
print('The alien is now ' + alien_0['color'] + '.')
alien_0['color'] = 'yellow'
print('The alien is now ' + alien_0['color'] + '.')
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x_position: " + str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
# remember to include colon after the condition
# if the alien's speed is slow, it will move one unit to the right
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
# the original speed is medium
# the alien will move two units to the right
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
# the new position is the old position + the x_increment
print("New x_position: " + str(alien_0['x_position']))
# printing the new position
# removing key-value pair
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
# this deleted the selected value, in this case 'points'
# the deleted key-value pair is removed permanently
# using for loop to print value in a dictionary
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
# creating a dictionary containing information about a person
# this is stored in several key-value pair
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
# making a dictionary with favorite languages
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() + ".")
# printing Sarah's favorite language
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
print("\n")
# key() method
# returns a list of all keys
for name in favorite_languages.keys():
print(name.title())
# this for loop is the same as:
# for name in favorites_languages:
print("\n")
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " + name.title() +
", I see you favorite language is " +
favorite_languages[name].title() + "!")
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
# looping through dictionaries keys in order
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
# with sorted() we can organize keys in alphabetical order
print("\n")
# looping through all values in a dictionary with values() method
# this returns a list without keys
print("The following languages have been mentioned:")
for language in sorted(favorite_languages.values()):
print(language.title())
# pulls all values from the list
# values() method don't check for repeats
print("\n")
# using set to not repeat value
for language in set(favorite_languages.values()):
print(language.title())
# set() identifies unique items
# therefore there is nor repetition of values when printing
# nesting
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
# making a dictionary with three aliens
aliens = [alien_0, alien_1, alien_2]
# including the three aliens in a list
for alien in aliens:
print(alien)
# printing the list
aliens = []
# creating an empty list
for alien_number in range(30):
# defining how many time to loop:
# each time a new alien is created
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
# adding a new alien and key-value pairs to the dictionary
aliens.append(new_alien)
# adding the new alien to the list
for alien in aliens[0:3]:
# for the first three aliens
if alien['color'] == 'green':
# if the aliens color is green
alien['color'] = 'yellow'
# it will be changed to yellow
alien['speed'] = 'medium'
# and the speed will be changed from slow to medium
alien['points'] = 10
# the points will change from 5 to 10
elif alien['color'] == 'yellow'
# if the alien color is yellow, it will change to red
alien['color'] = 'red'
alien['speed'] = 'fast'
# the speed will change to fast
alien['points'] = 15
# the points will change to 15
print("\n")
for alien in aliens[:5]:
# creating a for loop to print the first five aliens
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
# printing the total number of aliens
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
# adding items to the lists
print("********************")
for name, languages in favorite_languages.items():
if language == 1:
print("\n" + name.title() + "'s favorite languages are:")
else:
print("\n" + name.title() + "'s favorite language is:")
for language in languages:
print("\t" + language.title())
# the item/or items will all be printed
print(len(languages))
# adding dictionary to list
# for loop with str()
person_3 = {}
person_3['first name'] = 'sam'
person_3['last name'] = 'kant'
person_3['age'] = 13
person_3['city'] = 'barcelona'
people = []
people.append(person)
people.append(person_2)
people.append(person_3)
for each_person in people:
for name, info in each_person.items():
print(name.title() + ": " + str(info).title())
print("\n")
****
FORMATING OF VARIABLES IN STRINGS
# THE SECOND EDITION OF THE BOOK IS DIFFERENT:
# The introduce method is called F-STRINGS
# Instead of: variable_0 + variable_1
# The new way is: f"{variable_0} {variable_1}"
# where "f" stands for format.
# In practice it can look like this:
# Crash Course Book - edition 1:
variable_0 = "This is the way we used in the edition: "
variable_1 = "ONE"
message_one = variable_0 + variable_1
print(message_one)
# Crash Course Book - edition 2:
variable_0 = "This is the way we used in the edition: "
variable_2 = "TWO"
message_two = f"{variable_0} {variable_2}"
# the "" are quite confusing in this new format.
# the "quotations " mark the f-string beginning and end
# no + sign used, just space, for easier reading (styling the code)
print(message_two)
# This can be done with longer strings as well, for example
name = 'leo'
surname = 'peltier'
full_name = f"{name} {surname}"
print(f"Sending you my love, {full_name.title()}.")
# only 'f' stayed before the "quotations"
# no + sign
# .title in {} together with the variable
# Everything (but 'f') within "quotations" to mark/define it as one string
# all of that in print(brackets)
***
# input() function
- pauses the program and waits for the user to enter some text
message = input("Tell me something,and I will repeat it back to you: ")
print(message)
# the user is asked to enter information which will then be repeated back
# the text edition won't be able to run this program
# we need to use terminal
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
# input() makes the request and then waits for input
# when entering name, the greeting and name is printed
# the name in print refers to the answer
prompt = "If you tell us who your are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")
# building a multi-line string
# the first one is variable
# the second using += is adding a string to the first string called 'prompt'
# this will be printed on a new line
# using int()
age = input("How old are you? ")
# if anser ie. with 15
# writing age, terminal will return '15'
# if writing age >= 18 there will be an error
# it's not possible to compare a string with a numerical value
# if we write age == 15 it will return False
age = int(age)
age >= 15
# returns True because the string is converted to a numerical representation
# the comparison is therefore possible
# modulo operator
# divides on number by anther number and returns what remains
ie.
4 % 3 → returns 1
5 % 3 → returns 2
6 % 3 → returns 0 (when a number is even 0 is returned)
number = input("Enter a number, and I'll tell your if it's even or odd: ")
number = int(number)
if number % 2 == 0:
# even numbers can be divided by two
# when writing 6 % 3 it returns zero because nothing remains
# while if I write 5 % 3 it will return 2
# so this means that if this condition is met, the number is even
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")
# while loop
current_number = 1
# assigning current number the value 1
while current_number <= 5:
# as long as the current number is less than or equal to 5
print(current_number)
# printing the current number, which the first time is 1
current_number += 1
# adding 1 to the value of the current number, which then become two etc
# the loop stops running when it reaches 5
# repeating a message using input()
message = input("Tell me something,and I will repeat it back to you ")
print(message)
# the user is asked to enter information which will then be repeated back
# the text edition won't be able to run this program
# we need to use terminal to run the program:
go to the repository
python nameofproject.py
prompt = "Tell me something,and I will repeat it back to you --> "
# request to make an input
prompt += "Enter quit to end the program: "
# if the input is quit. the program will stop running
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# using the variable active = True as the condition for the program to run
active = True
# variable that the program is in an active state
while active:
message = input(prompt)
# when the program is active the message is the input
if message == 'quit':
# if the message is 'quit'