Simultaneous Assignment
A very cool feature of Python is that it allows for simultaneous assignment. The syntax is as follows:
var1, var2, var3 = value1, value2, value3
# sum_avg3.py
# A simple program to sum and average three numbers
# Illustrates the use of multiple input
def main():
print("This program computes the sum and the average of three numbers.")
x, y, z = eval(input("Enter three numbers separated by a comma: "))
sum = x + y + z
avg = sum/3
print("The sum of the three numbers is:", sum)
print("The average of the three numbers is:", avg)
main()
We introduced multiple input on one line in the previous lab. The following link demonstrates more detail on Simultaneous Assignment in Python.
https://www.webucator.com/how-to/how-do-simultaneous-assignment-python.cfm
Definite Loops
What if you want to add more than three numbers? What if you are going to add 10 or 100 numbers?
Detailed loop structures will be presented in later labs.
Python makes loop concept easy. The simplest kind of loop is called a definite loop.
Python knows how many times to go around the body of the loop.
A Python for loop has this general form:
for <variable> in <sequence>:
<body>
The body of the loop is indented under the loop heading. The <variable> after the
keyword for is called the loop index.
It takes on each successive value in the sequence, and the statements in the body are executed once for each value. Often the
sequence portion consists of a list of values.
To loop through a set of code a specified number of times, the range() function is used in the definite loop structure.
The range() function returns a sequence of numbers, by default it starts from 0 and increments by 1 (by default). It ends at a specified number.
range(5) is not the values of 0 to 5, but the values 0 to 4.
Now the following example is extended from the earlier example. This example uses a for loop to add multiple numbers.
def main():
print("This program calculates the sum of 5 integers.")
total = 0 #initialize the sum of all numbers.
for i in range(5):
num = eval(input("Enter a number: "))
total = total + num
#total += num
print("The sum of 5 numbers is:", total)
main()
The output of the program is below:
This program calculates the sum of 5 integers.
Enter a number: 345
Enter a number: 5684
Enter a number: 32
Enter a number: 923
Enter a number: 5
The sum of 5 numbers is: 6989
Example Program
The following program is taken from the previous lab. The previous example converts Celsius temperature to
Fahrenheit once.
The following example has a loop so that it executes 5 times before quitting.
# convert_loop.py
# Loop to perform 5 temperature conversions
def main():
print("This program converts celsius to fahrenheit five times.")
for i in range(5): #definite loop
c = eval(input("What is the Celsius temperature? "))
f = 9.0 / 5.0 * c + 32
print("The temperature", c, "in Celsius is: ",f, " Fahrenheit.")
main()
The program loops fives times by using
for i in range(5):
For more examples of range() functions, check out the following links:
https://www.w3schools.com/python/ref_func_range.asp
https://www.learnpython.org/en/Loops
Output Formatting
The format() method is a built-in method for Python strings.
{<index>:<format-specifier>}
Examples:
# convert_loop.py
# Loop to perform 5 temperature conversions
def main():
print("This program converts celsius to fahrenheit five times.")
for i in range(5): #definite loop
c = eval(input("What is the Celsius temperature? "))
f = 9.0 / 5.0 * c + 32
#The following statement displays c and f values using the .format() method
print("The temperature {0} in Celsius is {1}".format(c,f)," Fahrenheit.")
#The following statement diplays c and f as 2 decimal places
print("The temperature {0:.2f} in celsius is {1:.2f}".format(c,f)," Fahrenheit.")
main()
The code
print("The temperature {0} in celsius is {1}".format(c,f)," Fahrenheit.")
The {0} and {1} are index positions. Therefore, {0} is c and {1} is f
format(c,f) c and f are Celsius and Fahrenheit values to be printed in such order. You cannot change the order of values.
The str.format() is used in print() function, where str is a string that contains text
that is written to be the screen, as well as certain format specifiers included in curly braces {}.
The format function contains the list of variables that are to be printed.
>print("Hi, {0}; you have {1:0.2f}".format("John", 345.1234),"in the account.")
Hi, John, you have 345.12 in the account.
The {0}, and 1 in {1:0.2f} are index positions. Therefore, {0} is "John" and {1} is 345.1234
{1:0.2f}, 1 is the index position, after the :, 0 means use as much as space as you need.
2f means the precision is 2 decimal places. f means fixed-point number.
There are different ways to format numbers using Python's str.format(),
including float and integer formatting.
In addition to float (f) and exponential (e) scientific format types, there are two more that are commonly used:
d for integers (digits) and s for strings. The detailed documentation is here:
https://docs.python.org/3/library/string.html#formatspec
The program below illustrates most of the formatting you will need for writing strings, integers, or floats.
The example is from https://physics.nyu.edu/pine/pymanual/html/chap4/chap4_io.html#file-input
string1 = "How"
string2 = "are you my friend?"
int1 = 34
int2 = 942885
float1 = -3.0
float2 = 3.141592653589793e-14
print(' ***')
print(string1)
print(string1 + ' ' + string2)
print(' 1. {} {}'.format(string1, string2))
print(' 2. {0:s} {1:s}'.format(string1, string2))
print(' 3. {0:s} {0:s} {1:s} - {0:s} {1:s}'
.format(string1, string2))
print(' 4. {0:10s}{1:5s}'
.format(string1, string2))
print(' ***')
print(int1, int2)
print(' 6. {0:d} {1:d}'.format(int1, int2))
print(' 7. {0:8d} {1:10d}'.format(int1, int2))
print(' ***')
print(' 8. {0:0.3f}'.format(float1))
print(' 9. {0:6.3f}'.format(float1))
print('10. {0:8.3f}'.format(float1))
print(2*'11. {0:8.3f}'.format(float1))
print(' ***')
print('12. {0:0.3e}'.format(float2))
print('13. {0:10.3e}'.format(float2))
print('14. {0:10.3f}'.format(float2))
print(' ***')
print('15. 12345678901234567890')
print('16. {0:s}--{1:8d},{2:10.3e}'
.format(string2, int1, float2))
Here is the output:
***
How
How are you my friend?
1. How are you my friend?
2. How are you my friend?
3. How How are you my friend? - How are you my friend?
4. How are you my friend?
***
(34, 942885)
6. 34 942885
7. 34 942885
***
8. -3.000
9. -3.000
10. -3.000
11. -3.00011. -3.000
***
12. 3.142e-14
13. 3.142e-14
14. 0.000
***
15. 12345678901234567890
16. are you my friend?-- 34, 3.142e-14
More on output format:
https://www.techbeamers.com/python-format-string-list-dict/
https://thepythonguru.com/python-string-formatting/
https://mkaz.blog/code/python-string-format-cookbook/
https://python-reference.readthedocs.io/en/latest/docs/functions/format.html
Debugging
Debugging a Python program involves identifying and resolving errors in the code.
Here are some effective methods and tools for debugging Python programs:
- Print Statements: Basic and quick checks.
- Logging: Structured and level-specific logging.
- Debugger (pdb): Interactive and detailed debugging.
- IDE Debugging Tools: Advanced and user-friendly debugging interfaces.
Choose the method or combination of methods that best suits your debugging needs.
Replit Debugger
Replit Python Debugger
https://docs.replit.com/replit-workspace/workspace-features/debugging
Using Debugger in Replit
Spyder Debugger
https://docs.spyder-ide.org/current/panes/debugging.html
PDB debugging
https://realpython.com/lessons/getting-started-pdb/
Lab Assignment
1. Modify the program invest.py so that:
- The number of years for the investment is also a user input.
- Make sure to change the final message to reflect the correct number of years.
- The future value after n years is formatted to 2 decimal places.
def main():
print("This program calculates the future value")
print("of a 10-year investment.")
principal = eval(input("Enter the initial principal: "))
apr = eval(input("Enter the annual interest rate: "))
for i in range(10):
principal = principal * (1 + apr)
print("The value in 10 years is: ",principal)
main()
Here is a sample output:
This program calculates the future value of n years investment.
Enter the initial principal: 1000
Enter the number of years you are investing: 5
Enter the annual interest rate: 0.03
The value in 5 years is: $1159.27
2. Modify the program sum_avg.py so that:
- The program asks the user how many numbers they want to enter.
- The user enters the numbers and the program calculates the sum and the average.
def main():
print("This program calculates the sum of 5 numbers.")
total = 0 # initialize the sum of all numbers.
for i in range(5):
num = eval(input("Enter a number: "))
total = total + num
print("The sum of 5 numbers is:", total)
main()
Here is a sample output after the required modification:
This program asks the user how many numbers they want to enter.
The user enters the numbers, and the program calculates the sum and the average.
Enter how many numbers you would like to add: 4
Enter a number: 11
Enter a number: 22
Enter a number: 33
Enter a number: 44
The sum of 4 numbers is: 110
The average of 4 numbers is 27.5
Demonstrate your code to your lab instructor if the lab is in person.