forked from CalebCurry/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04-basic-io.py
More file actions
108 lines (79 loc) · 2.4 KB
/
04-basic-io.py
File metadata and controls
108 lines (79 loc) · 2.4 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
########## SPLIT ##########
msg = "Pay attention to each word that I say..."
words = msg.split() #returns list
print(words)
msg = "this,is,important,data" #How to parse CSV
print(msg.split(","))
########## SPLIT STRING BY LINE ##########
#This may have came from a file, for example.
msg = """\
Hey there.
My name is Caleb!
What's your name?
You're name is NERD? Weird...
Bye for now!"""
print(msg) #to see how it is stored...
print(msg.split('\n'))
########## INPUT USING SPLIT ##########
print("List your favorite foods separated by ', '")
print("Example input: ")
print("Kale, bok choy, brussel sprouts")
foods = input().split(', ')
for food in foods:
print("You said " + food)
#an obvious downfall is that this is very touchy.
#instead, we could ask one food per line
########## LOOPING TO GET USER INPUT ##########
fav_foods = []
while True:
print("Enter a food. q to quit: ", end="")
fav = input()
if str.lower(fav) == 'q':
break
fav_foods.append(fav)
print("all foods:", fav_foods)
########## LIST AS STACK ##########
#Consider a stack of plates.
#The last one you add is the first to be removed.
#The data structure depends on adding to the end of a list:
stack = []
stack.append("added")
#and removing from the end of the list
stack.pop()
fav_foods = []
while True:
print("Enter a food. q to quit, r to remove: ", end="")
fav = input()
if str.lower(fav) == 'q':
break
if str.lower(fav) == 'r':
popped = fav_foods.pop()
print("removed " + popped)
print("all foods:", fav_foods)
continue
fav_foods.append(fav)
print("all foods:", fav_foods)
print("final foods:", fav_foods)
########## QUEUE VARIATION ##########
#The difference with a queue is that the first added is the first removed
#consider a line to a roller coaster
#first in line rides ride first.
#The data structure depends on adding to the end of a list:
stack = []
stack.append("added")
#and removing from the FRONT of the list
stack.pop(0) #remove index 0
fav_foods = []
while True:
print("(QUEUE) Enter a food. q to quit, eat to remove: ", end="")
fav = input()
if str.lower(fav) == 'q':
break
if str.lower(fav) == 'eat':
popped = fav_foods.pop(0)
print("removed " + popped)
print("all foods:", fav_foods)
continue
fav_foods.append(fav)
print("all foods:", fav_foods)
print("final foods:", fav_foods)