Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Python) Trying to get an "if not in" to work, where it is searching a frozenset

Here is my code, as I said I am trying to make it so if whatever they enter for the section option is not in either of the frozensets, it prints what I have then restarts the program.

import sys
import os

temp = float(input('Please enter the temperature (In Celsius or Fahrenheit): '))
unit = str(input('Now, is this in Fahrenheit(F) or Celsius(C)? '))

Fahrenheit = frozenset(["F","f","Fahrenheit","fahrenheit","Fah","fah"])
Celsius = frozenset(["C","c","Celsius","celsius","Cel","cel"])
FahandCel = Fahrenheit & Celsius

if unit in Fahrenheit:
    answerC = (temp-32)*5/9
    print('\nYour original temperature of {}F is {}C'.format(temp,answerC))

if unit in Celsius:
    answerF = temp*9/5+32
    print('\nYour original temperature of {}C is {}F'.format(temp,answerF))

if unit not in FahandCel:
    print('\nPlease actually enter something obvious next time.\nSuch as, F, C, Fahrenheit, or Celsius.\n\n')
    python = sys.executable
    os.execl(python, python, * sys.argv)

When I launch the program, regardless of what I enter for the second input, it prints out the lines "Please actually enter..." Even if I enter something that is in Fahrenheit or Celsius.

like image 680
rainydevbs Avatar asked Jan 11 '23 20:01

rainydevbs


1 Answers

frozenset.__and__() does set intersection, leaving you with an empty set.

However, it is unlikely that you will have the same unit in both sets, so your code should read as follows, avoiding the need for the set union altogether:

if unit in Fahrenheit:
   ...
elif unit in Celsius:
   ...
else:
   ...

Except you should use FAHRENHEIT and CELSIUS because PEP 8.

like image 180
Ignacio Vazquez-Abrams Avatar answered Jan 31 '23 08:01

Ignacio Vazquez-Abrams