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
Tundra Tactical
2 hours ago🛑{LIVE NOW!!} The Great Tundra Nation Gun Show!!!! Presented By MGS Trade School
7,545 watching -
23:23
MYLUNCHBREAK CHANNEL PAGE
8 hours agoThe Sunken Basilica
43.9K3 -
LIVE
GamerGril
3 hours agoShould I Get A Zoob Job 💞Dying Light The Beast💞
313 watching -
5:00:18
MattMorseTV
6 hours ago $207.50 earned🔴No Kings "protest" TOTAL CHAOS.🔴
284K346 -
1:28:51
Darkhorse Podcast
4 hours agoCan the internet make you sick? The 297th Evolutionary Lens with Bret Weinstein and Heather Heying
17K9 -
LIVE
TinyPandaface
4 days agoYour FACE is a Gaming Channel! | Homebody PART 2!
63 watching -
1:21:31
Michael Franzese
17 hours agoTrump Derangement Syndrome Is On The Way Out | Live with Michael Franzese
99.4K98 -
LIVE
ZWOGs
2 hours ago🔴LIVE IN 1440p! - ARC RAIDERS SERVER SLAM - Come Hang Out!
34 watching -
9:22
Colion Noir
8 hours agoArmed Woman Drags Gunman Out of Store Before Firing Two Shots
79.7K40 -
1:04:17
Jeff Ahern
4 hours ago $1.23 earnedThe Saturday Show with Jeff Ahern
22K7