This is the P2PU Archive. If you want the current site, go to www.p2pu.org!
You haven't posted any discussions yet.
Please review the Flow Control learning resources. Post answers to the practice exercises below.
Q: What are some everyday systems that exhibit flow control?
Q: Can you think of some examples where True/False logic may be too constraining?
Chapter 3: https://github.com/thcipriani/thcipriani.github.com/blob/master/python10...
Chapter 5: https://github.com/thcipriani/thcipriani.github.com/blob/master/python10...
1. An example of an everyday system that exhibits flow control would be HTML form validation.
2. Honestly, I'm having a lot of trouble coming up with a problem where boolean logic isn't a factor or often times at the core of the logic. The constraint for booleans is that their use has the potential to significantly lengthen a piece of code - this is where a switch/case statement may be more appropriate.
Outside of programming the ship of theseus comes to mind...
I'll be interested to see smarter answers than mine.
I saw that exact code somewhere else on the Internet. Is it uniquely yours?
Nope, not mine - I found a webpage called 'answers to unique python problems in the book python for infomatics' and then copied, pasted and pushed to my git repo so that I might have the glory of finishing an assignment on p2pu's website first ;)
I think you probably read the chapters, like I did, and that's where you saw a version of the code. If you've noticed inside the chapters there are examples listed that are different versions of the problems that they ask you to solve at the end of the chapter - they're very helpful and illustrate best practices so I try to follow their examples.
No I saw it on the official python tutorial but okay then.
copy'n'paste is a useful thing, but probably counter productive when it comes to acquiring a new skill... is it not?
yes - that's why I thought it was a funny joke. Let me just state this so it's unambiguous for those who were confused - I didn't copy and paste code.
First of all, these are beginner tutorials and there's not a lot of 'creativity' that comes into doing beginner work - there are only a handful of ways to iterate over a list for example.
I was so offended by this implication I've decided to use python to answer the accusations. I created a script that you can find on my github at the bottom of this page - http://www.tylercipriani.com/python101/ if you call that script with python and pass it the path to your chapter5 python file (e.g. python ./plagiarise.py chapter5.py) it will compare the text of your code with the text on the python.org site on the flow control page (http://docs.python.org/tutorial/controlflow.html) and it will count every time a word you used in your script appears on that page.
You were right - apparently there are 327 words from that site that are in my code, including 'if', 'and', 'for' and 'line' - scandalous! Try it yourself - you'll be surprised how little you can trust yourself not to steal things.
I don't appreciate being accused of stealing - especially by people who haven't posted their assignment.
I post them when I am done; I have theoretical physics to work on not just this class, not only that but I am still working on creating a working quantum algorithm that is why I take so long to post.
Flow Control.
A: Every program have some form of flow control.
A: In most HTML forms
HELP with my try and except example if i put a word or if a number that does belong the program continues to run.
Exercise 3.1
#Calculating hourly rate 1.5 times if work over 40 hours
hours = raw_input("Enter hours worked:")
rate = raw_input("Enter rate at which worked:")
if hours > 40:
over = (int(hours) - 40) * 1.5
hours = 40 + float(over)
pay = float(hours) * float(rate)
print pay
Exercise 3.2
#Calculating hourly rate with try and except
hours = raw_input("Enter hours worked:")
try:
hours = int(hours)
except:
print '\nerror, enter a number\n'
rate = raw_input("Enter rate at which worked:")
try:
rate = int(rate)
except:
print '\nerror, enter a number\n'
if hours > 40:
over = (int(hours) - 40) * 1.5
hours = 40 + float(over)
pay = float(hours) * float(rate)
print pay
Were you able to get your try/except example to work correctly Pein? Can you post the code on Pastie?
yes it was able to work but not the way i wanted, i think while loop was needed to repeat the question until the user enter correct information
The best way to do this is to do a 'while True:' at the very beginning of your try/except loop - add a break only after your true statement and a 'continue' after your except statement - this creates a much more expected program behavior IMHO.
Thanks Tyler. new source code for ex 3.2
#Calculating hourly rate with try and except
while True:
hours = raw_input("Enter hours worked:")
try:
hours = int(hours)
break
except:
print '\nerror, enter a number\n'
continue
while True:
rate = raw_input("Enter rate at which worked:")
try:
rate = int(rate)
break
except:
print '\nerror, enter a number\n'
continue
if hours > 40:
over = (int(hours) - 40) * 1.5
hours = 40 + float(over)
pay = float(hours) * float(rate)
print pay
A1: Traffic lights with IR sensors and pedestrian crossings.
A2: Electric Ovens: they need on/off, temperature and power-level settings and optionally a timer. Dimmer switches and volume controls. Analogue controls in general.
Flow Control example:
Beer bottling plant; the bottles have to be clean etc else the beer doesn't get bottled. The beer needs to be up to standards else it does not get bottled.
Where True/False logic may be too constraining:
If there is some business logic that could have more than two possible outcomes (True/False) several elseifs or a case statement would need to be used.
chap3 examples: http://pastie.org/1864459
chap5 examples: http://pastie.org/1864462
A1: I would say a system that exhibits control flow is a POS system.
A2: programming an AI.
Homework: http://pastie.org/1864679
I have question on Exercise 3.3 and testing code. So I am fine with getting the code right but what I'm struggling with is how to reuse the code several times to test it with different scores as the exercise asks us to do. How can I test the code without having to retype all of the code for each time I test it? Is that even possible in interactive mode? Or is turning code into a script the only way? I would turn it into a script but I don't know how at this point. Any tips would be appreciated.
If you're using IDLE you can go to 'File'>'New Window' and use 'File'>'Save As...' in the resulting window. Save it as chapter3.py. You'll be able to open the script from IDLE by going to 'File'>'Open..' and finding your script - then go to 'Run'>'Run Module' or just hit F5 - the script'll run in the IDLE window. Alternately you can use your favorite text editor and just save the file with the extension 'py' then call it from the command line using the command 'python ./path/to/script.py'. Let me know if you have any further questions.
Check out 'Writing Programs in IDLE's File Editor' here: http://inventwithpython.com/chapter3.html for more detailed info.
Q: What are some everyday systems that exhibit flow control?
A: pumps, elevators, traffic lights, electrical interlocks, multiple user database, security systems..
Q: Can you think of some examples where True/False logic may be too constraining?
A: pressure/temperature regulators, hearing aids, any type of proportional controller.
#Ex 3.1
ot = 0 # overtime hours
hours = input ('Enter Hours: ') #this is a str type
rate = input ('Enter Rate: ') # this is a str type
if int(hours) > 40:
ot = int(hours) % 40 #assigns overtime hours to ot
hours = 40 # must have worked 40 hours if there is overtime
pay = int(hours) * float(rate) + ot * 1.5 * int(rate)
print ('Pay: ' + str(pay))
"""output
>>>
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
>>>
"""
#Ex 3.2
#
ot = 0 # overtime hours
hours = input ('Enter Hours: ') #hours is a str type
try:
hours = float(hours) #hours is now a float
rate = input ('Enter Rate: ') # rate is a str type
try:
rate = float(rate) #rate is now a float
if hours > 40:
ot = hours % 40 #assigns overtime hours to ot
hours = 40 # must have worked 40 hours if there is overtime
pay = hours * rate + ot * 1.5 * rate
else:
pay = hours * rate
print ('Pay: ' + str(pay))
except:
print('please input a number')
except:
print('please input a number')
""" output
>>>
Enter Hours: 24
Enter Rate: 10
Pay: 240.0
>>> ================================ RESTART ================================
>>>
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
>>> ================================ RESTART ================================
>>>
Enter Hours: four
please input a number
>>> ================================ RESTART ================================
>>>
Enter Hours: 45
Enter Rate: ten
please input a number
>>>
"""
#Ex 3.3
#
score = input('please enter score between 0.0 and 1.0 ')
score = float(score)
if score < 0.0 or score > 1.0:
print('score is out of range, your input ' + str(score))
elif score >= 0.9:
print('grade is an A ---> ' + str(int(score*100)) + '%')
elif score >= 0.8:
print('grade is a B ---> ' + str(int(score*100)) + '%')
elif score >= 0.7:
print('grade is a C ---> ' + str(int(score*100)) + '%')
elif score >= 0.6:
print('grade is a D ---> ' + str(int(score*100)) + '%')
else:
print('grade is an F ---> ' + str(int(score*100)) + '%')
""" output
>>>
please enter score between 0.0 and 1.0 -2
score is out of range, your input -2.0
>>> ================================ RESTART ================================
>>>
please enter score between 0.0 and 1.0 1.2
score is out of range, your input 1.2
>>> ================================ RESTART ================================
>>>
please enter score between 0.0 and 1.0 .97
grade is an A ---> 97%
>>> ================================ RESTART ================================
>>>
please enter score between 0.0 and 1.0 .83
grade is a B ---> 83%
>>> ================================ RESTART ================================
>>>
please enter score between 0.0 and 1.0 .77
grade is a C ---> 77%
>>> ================================ RESTART ================================
>>>
please enter score between 0.0 and 1.0 .65
grade is a D ---> 65%
>>> ================================ RESTART ================================
>>>
please enter score between 0.0 and 1.0 .37
grade is an F ---> 37%
>>>
"""
My week 2 exercises: https://github.com/brotherhutch/python101
Q: What are some everyday systems that exhibit flow control?
Factory mass production lines, air traffic control systems, choose your own adventure novels (dating myself I know)
Q: Can you think of some examples where True/False logic may be too constraining?
Analysis in the arts: literature, music, dance, fine art, etc.
Answer to Question 1: Those turning/counter things that you go through when entering an amusement park; stop signs and traffic lights; funnels
Answer to Question 2: Topics or Questions where there is no right or wrong answer (subjective topics) or where there are simply too many ways to do things or too many variables to check...
Exercise 3.1:
hours = raw_input("Enter Number of Hours Worked: \n")
rate = raw_input("Enter Hourly Pay Rate: \n")
fhours = float(hours)
frate = float(rate)
overTime = fhours - 40.0
regularPay = fhours * frate
if overTime > 0.0 :
overPay = overTime * 1.5 * frate + 40.0 * frate
print overPay
else :
print regularPay
Exercise 3.2
try:
hours = raw_input("Enter Number of Hours Worked: \n")
fhours = float(hours)
rate = raw_input("Enter Hourly Pay Rate: \n")
frate = float(rate)
overTime = fhours - 40.0
regularPay = fhours * frate
if overTime > 0.0 :
overPay = overTime * 1.5 * frate + 40.0 * frate
print overPay
else :
print regularPay
except:
print "You did not enter numbers in the beginning"
Exercise 5.1
count = 0
total = 0
query = raw_input("Enter a number: ")
while (query != "done"):
try:
count += 1
total = total + float(query)
query = raw_input("Enter a number: ")
except:
print "Invalid Input"
count -= 1
query = raw_input("Enter a number: ")
print str(total) + " " + str(count) + " " + str(total/count)
Exercise 5.2
count = 0
total = 0
smallest = None
largest = None
query = raw_input("Enter a number: ")
while (query != "done") :
try:
count += 1
total = total + float(query)
value = query
if(smallest is None or smallest > value):
smallest = value
if(largest is None or largest < value):
largest = value
query = raw_input("Enter a number: ")
except:
print "Invalid Input"
count -= 1
query = raw_input("Enter a number: ")
print str(total) + " " + str(count) + " " + str(smallest) + " " + str(largest)
my excercise 5.1
total = 0
count = 0
average = 0
while True:
num = raw_input('Enter a Number(done to exit):')
if num == 'done':
break
else:
try:
num = float(num)
total = total + num
count = count + 1
average = total / count
except:
print 'ERROR, please enter a valid data!'
print 'Total:', total
print 'Number of number(s) entered:', count
print 'Average of numbers:', average
A1. Microwave oven, Fridge Freezers
A2. Still mulling over this one
Exercise 3.1 | http://pastie.org/1877699
Exercise 3.2 | http://pastie.org/1877700
Exercise 3.3 | http://pastie.org/1877701
Q: What are some everyday systems that exhibit flow control?
A: I recently had to enter my address in a form. When I entered my country, the dropdown box with list of cities became enabled. After I had chosen my city, the dropdown box with streetnames became enabled.
Q: Can you think of some examples where True/False logic may be too constraining?
A: Volume control, not only used to turn off and on, but also to adjust the volume.
Exercises chapter 3: http://pastie.org/1877841
Exercises chapter 5: http://pastie.org/1877846
In exercise 5.1 I have also taken into account to prevent division by zero when no valid numbers are entered.
Is the use for single quotes and double quotes in python similar to PHP?
A.1. The automatic kiosks for ticket ordering: First you choose the city, then the kind of spectacle, the day... The system tell you if there is any free seat. You may buy, change, or search for any other show, etc.
A.2. For an automatic door, a True/False logic would be Ok, but if the door has any type of electronic identification system, a True/False logic would be too constraining.
Exercise 3.1 & 3.2 http://pastie.org/1882327
Exercise 3.3 http://pastie.org/1882332
Exercise 5.1 http://pastie.org/1882335
Exercise 5.2 http://pastie.org/1882337
Gas pumps, computer networks, menus, installers, electric doors, validation code for programs (password), music player, etc.
The True/False logic becomes less than adequate when there are more than two possible options. Some examples are AI or in a video game where there are for example many weapons available to choose.
Exercises for Chapter 3: http://pastie.org/1883221
Exercises for Chapter 5: http://pastie.org/1883384
1. Flow control is demonstrated on an auto web site I recently visited. The user selects the make of a car and the site next displays the various models for that make. The user selects a model and the number of years in which that model was made is displayed.
2. Boolean logic is inappropriate where a yes/no answer is not possible. Very often a legal question cannot be answered with a simple yes or no, but rather "it depends" because there are various factors that could change the final answer.
***Exercises for Chapter 3***
Ex. 3.1
hours = raw_input('Enter Hours Worked: ')
rate = raw_input('Enter Rate: ')
if (hours > 40):
ot = hours - 40
otpay = ot * (1.5 * rate)
pay = (40 * rate) + otpay
print 'Your pay = ' + str(pay)
else:
pay = int(hours) * float(rate)
print 'Your pay = ' + str(pay)
Ex. 3.2
try:
input_hours = raw_input('Enter Hours Worked: ')
hours = float(input_hours)
input_rate = raw_input('Enter Rate: ')
rate = float(input_rate)
if (hours > 40):
ot = hours - 40
otpay = ot * (1.5 * rate)
pay = (40 * rate) + otpay
print 'Your pay = ' + str(pay)
else:
pay = int(hours) * float(rate)
print 'Your pay = ' + str(pay)
except:
print 'Error, please enter numeric input'
Ex. 3.3
try:
input_score = raw_input('Enter Test Score for Grade Result: ')
score = float(input_score)
if score <= 1.0 and score >= 0.0:
if score >= 0.9:
grade = 'A'
elif score >= 0.8:
grade = 'B'
elif score >= 0.7:
grade = 'C'
elif score >= 0.6:
grade = 'D'
else:
grade = 'F'
print grade
else:
print 'Bad score'
except:
print 'Bad score'
***Chapter 5***
Ex. 5.1
total = 0
count = 0
avg = 0
while True:
try:
input = raw_input('Enter a number: ')
if input == 'done':
break
n = float(input)
except:
print 'bad idea'
total = total + n
count = count + 1
avg = total/count
print int(total), int(count), float(avg)
Ex. 5.2
total = 0
count = 0
max = 'none'
min = 'none'
while True:
try:
input = raw_input('Enter a number: ')
if input == 'done':
break
n = float(input)
except:
print 'bad idea'
total = total + n
count = count + 1
if max == 'none' or n >= max:
max = n
if min == 'none' or n <= min:
min = n
print int(total), int(count), int(max), int(min)
Exercises 3.1 & 3.2
rate = raw_input("Enter rate:")
hours = raw_input("Enter hours:")
try:
rate = float(rate)
hours = float(hours)
overtime_rate = rate*1.5
standard_hours = 40
if hours >= standard_hours:
overtime_hours = hours - standard_hours
else:
overtime_hours = 0
pay = standard_hours*rate + overtime_hours * overtime_rate
print ''.join(['Pay = ', str(pay)])
except:
print 'Please enter numbers'
Exercise 3.3
score = raw_input("Please enter score between 0 and 1: ")
try:
score = float(score)
if not(score>=0.0 and score <=1.0):
print 'Error: enter a number between 0 and 1'
elif score >= 0.9:
print 'A'
elif score >= 0.8:
print 'B'
elif score >= 0.7:
print 'C'
elif score >= 0.6:
print 'D'
else:
print 'F'
except:
print 'Error: enter a number'
Exercise 5.1
inp = raw_input("Enter a number: ")
total = 0.0
count = 0
while inp != 'done':
try:
inp = float(inp)
count+=1
total += inp
except:
print 'Invalid input'
inp = raw_input("Enter a number: ")
print 'Total: ', total
print 'Count: ', count
print 'Average', total/count
Exercise 5.2
inp = raw_input("Enter a number: ")
maximum = 0.0
minimum = 0.0
while inp != 'done':
try:
inp = float(inp)
if inp > maximum:
maximum = inp
if inp < minimum:
minimum = inp
except:
print 'Invalid input'
inp = raw_input("Enter a number: ")
print 'Maximum: ', maximum
print 'Minimum: ', minimum
# ex5.1
total = 0.0 # sum of the numbers entered
count = 0 # how many numbers entered
while True:
num = input('enter number: ') #num is a type str
if num == 'done':
break
try:
num = float(num) #num is now a type float
except:
print('invalid input')
continue
total += num
count +=1
print('Total: ',total)
print(count,' numbers entered')
if count > 0: # so won't divide by zero is no numbers entered
print('average: ',total/count)
""" output
>>>
enter number: 12
enter number: dr
invalid input
enter number: 23
enter number: 4.7
enter number: 134.87
enter number: 9
enter number: done
Total: 183.57
5 numbers entered
average: 36.714
>>>
"""
# ex5.2 only works for positive and non-zero numbers
max = 0.0
min = 0.0
while True:
num = input('enter number: ') #num is a type str
if num == 'done':
break
try:
num = float(num) #num is now a type float
except:
print('invalid input')
continue
if min == 0.0: #otherwise min will be 0 for only pos numbers entered
min = num
if min > num:
min = num
if max < num:
max = num
print('largest number is: ', max, 'smallest number is: ', min)
""" output
>>>
enter number: 12
enter number: 33
enter number: 454
enter number: df
invalid input
enter number: 6.9
enter number: done
largest number is: 454.0 smallest number is: 6.9
>>>
"""