Python基础算术程序问题:如何在输出等式中显示实际输入数值
Hey Emily, I totally get what you're aiming for here—right now your print statements are spitting out variable names like odd and num instead of the actual numbers the user typed in. Let's fix that quickly with Python's string formatting tools, which are perfect for this kind of thing.
The Problem with Your Current Code
Your existing print lines use hardcoded strings like 'odd + num =', so Python just prints those exact characters instead of replacing them with the values stored in the variables. We need a way to inject the actual numbers into those strings.
The Best Solution: F-Strings (Python 3.6+)
F-strings are the cleanest and most readable way to do this. Just add an f before your string, then wrap any variable or expression you want to insert in curly braces {}. Here's your updated code:
odd = int(input("Please enter an odd number from 1 to 99: ")) print(odd) # No need to cast to int again—odd is already an integer! num = int(input("Please enter a number from 1 to 200: ")) print(num) # Use f-strings to insert actual values into the output print(f'{odd} + {num} = {odd + num}') print(f'{odd} - {num} = {odd - num}') print(f'{odd} * {num} = {odd * num}') print(f'{odd} / {num} = {odd / num}') # Don't forget to adjust the order for operations where num comes first print(f'{num} + {odd} = {num + odd}') print(f'{num} - {odd} = {num - odd}') print(f'{num} * {odd} = {num * odd}') print(f'{num} / {odd} = {num / odd}')
Alternative: .format() Method
If you're working with an older Python version (pre-3.6), you can use the .format() method instead. It works similarly, but you pass variables to the method instead of embedding them in the string:
print('{} + {} = {}'.format(odd, num, odd + num))
Quick Tweak Note
I also removed the redundant int() casts in your print(int(odd)) lines—since you already converted the input to integers when assigning to odd and num, there's no need to do it again when printing.
Now when you run the program, if the user enters 7 as the odd number and 10 as the regular number, your output will look like this:
7 10 7 + 10 = 17 7 - 10 = -3 7 * 10 = 70 7 / 10 = 0.7 10 + 7 = 17 10 - 7 = 3 10 * 7 = 70 10 / 7 = 1.4285714285714286
That's exactly what you wanted—actual numbers in your arithmetic equations!
内容的提问来源于stack exchange,提问作者Emily Kessel

