0
temp = input("Please enter the tempreture. ")
temp2 = temp[0,1]
if temp[2] or temp[3] == "C" or "c":
    new = (temp2*9/5)+32
    print(temp + " converted into Farenheit is " + new + ".")
elif temp[2] or temp[3] == "F" or "f":
    print("        ")
else:
    print("You have done something wrong?")

This is homework and I wanted to use the input to convert the temperature. The input would be 77C or 77F. Is there any way that I can set it as 77 as an integer so I can use it in calculations?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Jojo Fan
  • 21
  • 1

3 Answers3

0

You will have to implement slicing to accomplish this.

First let's define our temperature

temp1 = '31c'

Then we can convert the 31 to an integer by doing the following

temp1 = int(temp1[:2])
rishi
  • 652
  • 1
  • 6
  • 20
0

There are a few things at play here:

  • To obtain the last character of a string, use index [-1], e.g.: example_string[-1]. Negative indices count backwards from the end. Negative indices can also be used in slices: example_string[2:-1].
  • To check the identity of a letter, you first convert it into lowercase and compare this result against the lowercase version of the letter.
  • Changing between types is called casting. Casting to an int is done like so: int(example_string). Attempting to do perform undefined casts will result in a ValueError.

As this is homework, I won't spoil the end result for you.

stfwn
  • 362
  • 2
  • 14
0

If you want to remove the last character you can use a string slice with a negative index:

if tempStr[-1].lower == 'c':
    tempStr = tempStr[:-1]

A slice is two values separated by a colon. The value before the first colon is the first character, the value after the colon is the last character (actually the character after the last character). A negative index counts backwards from the back of the string, rather than forwards from the front.

Alternatively you might want to remove the 'C' or 'F' and convert the rest.

tempStr=tempStr.upper();
if 'F' in tempStr.upper():
    tempStr=tempStr.upper().replace('F','')
    temp_C = int((int(tempStr)-32)*5/9)
Alan Dyke
  • 855
  • 6
  • 14