Premium Only Content
The With Statement |Section 5|Celestial Warrior
Please take a look at the following code:
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))
The code prints outthe output of thec_to_f function multiple times in the terminal.
For this exercise,please write the outputin a text file instead of printing it out in the terminal.
The text file content will look like this:
50.0
-4.0
212.0
Please don't writeany messagein the text file when input is lowerthan -273.15.
One solution could be to open a file once and then iterate inside the functionwhile the file is open:
temperatures=[10,-20,-289,100]
def writer(temperatures):
with open("temps.txt", 'w') as file:
for c in temperatures:
if c>-273.15:
f=c*9/5+32
file.write(str(f)+"\n")
writer(temperatures)#Here we're calling the function, otherwise no output will be generated
Or even better, you could treat both the temperature input and the file path as function arguments:
temperatures=[10,-20,-289,100]
def writer(temperatures, filepath):
with open(filepath, 'w') as file:
for c in temperatures:
if c>-273.15:
f=c*9/5+32
file.write(str(f)+"\n")
writer(temperatures, "temps.txt")#Here we're calling the function, otherwise no output will be generated
In real life you may want to build a website with Python so you connectthe function callwriter()with a button on the website. The user enters some values in a text box, and types in a file name and thenpresses the button. The button executes the writer()function by using the input that user entered in the text box as input values for the function. Once the button is pressed,the generatedfile downloads on the user's browser.
Sure, that's a bit of a demanding project to do but Iwill take you step by step in later sections on how to do such web applications.
-
LIVE
FreshandFit
1 hour agoAfter Hours w/ Supporter Questions
5,651 watching -
LIVE
AdmiralSmoothrod
3 hours agoescape from tarkov - the best and brightest - party games later?
942 watching -
LIVE
Barbarian Mowz
5 hours agoBarbaric Stream!! - Knights of the Old Republic!
759 watching -
LIVE
PandaSub2000
5 hours agoLIVE 10pm ET | LEGO STAR WARS: SKYWALKER SAGA
401 watching -
12:40
Scammer Payback
3 days agoHACKED Scammers Reaction to being Destroyed
11.6K10 -
1:31:09
Badlands Media
19 hours agoEye of the Storm Ep. 208: Speaker Johnson’s Re-Election and the Vegas Cybertruck Incident Decoded
46K12 -
1:36:46
Kim Iversen
6 hours agoLee Harvey Oswald and Cuba: The New Evidence That Changes Everything
48.5K30 -
2:19:43
TheSaltyCracker
4 hours agoCybertruck Bomber Manifesto Leaked ReeEEeE Stream 01-03-25
104K162 -
1:44:12
Roseanne Barr
4 hours ago $8.32 earnedSquid Game? | The Roseanne Barr Podcast #81
46.9K26 -
1:13:27
Man in America
8 hours ago🚨 2025 WARNING: Disaster Expert Predicts 'ABSOLUTE CHAOS' for America
23.2K13