I started learning my first real language and can't find a solution for my problem:
how can I convert the user input, if someone is typing minus 10 for example instead of -10?
I just want to convert minus to -
I also added my code.
def get_temperatur():
minus = "-"
plus = "+"
while True:
C = input("Input temperature in Celsius: ")
try:
C = float(C)
return C
except ValueError:
print("That is not a valid input")
def convert_to_Kelvin(C):
K = C +273.15
return K
if __name__ == "__main__":
C = get_temperatur()
print("That is " + str(convert_to_Kelvin(C)) + " Kelvin")
def convert_to_Fahrenheit(C):
L = C * 1.8
F = L +32
return F
if __name__ == "__main__":
F = get_temperatur()
print("That is " + str(convert_to_Fahrenheit(F)) + " Fahrenheit")
I expect user input minus to be converted to -
Adding - sign will not make it a negative number, It is still going to be a string and you will get ValueError.
Instead do something like,
if 'minus' in c:
c = 0 - float(c.split('minus')[1].strip())
Note: I am assuming that your string will not contains any other word after number.
i.e. It will be like 'minus 10' and not 'minus 10 xyz'.
def get_temperatur():
minus = "-"
plus = "+"
while True:
C = input("Input temperature in Celsius: ")
try:
if 'minus ' in C:
C = C.replace('minus ', '-')
C = float(C)
return C
except ValueError:
print("That is not a valid input")
The C.replace() function takes in 2 values - the string to be replaced, and what it is to be replaced with. The if statement checks if 'minus '(note the space) is in the string, and if it is, replaces it with '-'
def get_temperatur():
while True:
C = input("Input temperature in Celsius: ")
C.replace("minus ", "-")
try:
C = float(C)
return C
except ValueError:
print("That is not a valid input")
Related
temp = float(input("What is the temperature : "))
def C2F():
"Celsius to Fahrenheit"
f = (temp * 9/5) + 32
return (f)
def C2K():
"Celsius to Kelvin"
k = temp + 273.15
return (k)
def C2R():
"Celsius to Rankine"
r = (temp + 273.15) * 9 / 5
return (r)
print ("F = %.2f" % C2F())
print ("K = %.2f" % C2K())
print ("R = %.2f" % C2R())
How can i add multiple inputs to this code. I have to add input unit , output unit and user_response for correct,incorrect and invalid outputs
You could do it like this - but it is quite a rewrite.
You would need to add more conversion math for the missing cases (F to C, F to K etc.) to calculate the missing ones as well:
def convert(frm, to, value):
# you may want to make more smaller methods that do the calculation
# like def C2F(v): return (v * 9/5) + 32
# and call them inside your if statements
if frm == to:
print("Nothing to convert - same units.")
return value
if frm == "C" and to == "F":
print("Celsius to Fahrenheit")
return (value * 9/5) + 32
if frm == "C" and to == "K":
print("Celsius to Kelvin")
return value + 273.15
if frm == "C" and to == "R":
print("Celsius to Rankine")
return (value + 273.15) * 9 / 5
print(frm, to,"not supported.")
return "n/a"
def tryParseFloat(v):
"""Try parsing v as float, returns tuple of (bool, float).
If not a float, returns (False, None)"""
try:
return (True, float(v))
except:
return (False, None)
Main code:
allowed = {"K", "F", "C", "R"}
print(("Input two units (Celsius,Kelvin,Fahrenheit,Rankine) to convert from/to\n"
"and a value to convert (separated by spaces).\nEnter nothing to leave.\n"
"Example: K F 249 or Kelvin Rank 249\n\n"))
while True:
whatToDo = input("Your input: ").strip().upper()
if not whatToDo:
print("Bye.")
break
# exactly enough inputs?
wtd = whatToDo.split()
if len(wtd) != 3:
print("Wrong input.")
continue
# only care about the 1st letter of wtd[0] and [1]
if wtd[0][0] in allowed and wtd[1][0] in allowed:
frm = wtd[0][0]
to = wtd[1][0]
# only care about the value if it is a float
isFloat, value = tryParseFloat(wtd[2])
if isFloat:
print(value, frm, "is", convert(frm, to, value), to)
else:
print(wtd[2], " is invalid.") # not a number
else:
print("Invalid units - try again.") # not a known unit
Sample run & output:
Input two units (Celsius,Kelvin,Fahrenheit,Rankine) to convert from/to
and a value to convert (separated by spaces).
Enter nothing to leave.
Example: K F 249 or Kelvin Rank 249
Your input: f k 24
F K not supported.
24.0 F is n/a K
Your input: c f 100
Celsius to Fahrenheit
100.0 C is 212.0 F
Your input: c k 100
Celsius to Kelvin
100.0 C is 373.15 K
Your input: caesium kryptonite 100
Celsius to Kelvin
100.0 C is 373.15 K
Your input:
Bye.
To reduce the amount of code you might want to implement:
C2F, C2K, C2R, R2C, K2C, F2C
and for missing ones combine them (if you are ok with Is floating point math broken?) , f.e.:
def K2R(value):
return C2R(K2C(value)) # convert K to C and C to R for K2R
How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check.
Then program should check if input given by user belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.
n = int(input("How many numbers do you want to check:"))
x = 0
def tribonnaci(n):
sequence = (0, 1, 2, 3)
a, b, c, d = sequence
while n > d:
d = a + b + c
a = b
b = c
c = d
return d
while x < n:
num = input("Number to check:")
if num == "":
print("FAIL. Give number:")
elif int(num) <= -1:
print(num+"\tFAIL. Number is minus")
elif int(num) == 0:
print(num+"\tYES")
elif int(num) == 1:
print(num+"\tYES")
elif int(num) == 2:
print(num+"\tYES")
else:
if tribonnaci(int(num)) == int(num):
print(num+"\tYES")
else:
print(num+"\tNO")
x = x + 1
You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.
>>> x = raw_input()
12345
>>> x.isdigit()
True
You can also use try/catch:
try:
val = int(num)
except ValueError:
print("Not an int!")
For your use, using the .isdigit() method is what you want.
For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.
To validate, you can use an if statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.
This question keeps coming up in one form or another. Here's a broader response.
## Code to check if user input is letter, integer, float or string.
#Prompting user for input.
userInput = input("Please enter a number, character or string: ")
while not userInput:
userInput = input("Input cannot be empty. Please enter a number, character or string: ")
#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
global inputType
def typeCheck():
global inputType
try:
float(userInput) #First check for numeric. If this trips, program will move to except.
if float(userInput).is_integer() == True: #Checking if integer
inputType = 'an integer'
else:
inputType = 'a float' #Note: n.0 is considered an integer, not float
except:
if len(userInput) == 1: #Strictly speaking, this is not really required.
if userInput.isalpha() == True:
inputType = 'a letter'
else:
inputType = 'a special character'
else:
inputLength = len(userInput)
if userInput.isalpha() == True:
inputType = 'a character string of length ' + str(inputLength)
elif userInput.isalnum() == True:
inputType = 'an alphanumeric string of length ' + str(inputLength)
else:
inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
#Calling function
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")
If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.
try:
if not int(data[find]) > -1:
raise(ValueError('This is not-a-number'))
except:
return
just a reminder.
You can check the type of the input in a manner like this:
num = eval(input("Number to check:"))
if isinstance(num, int):
if num < 0:
print(num+"\tFAIL. Number is minus")
elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers.
print(num + '\tYES')
else:
print(num + '\NO')
else:
print('FAIL, give number')
and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.
I want to get the middle letter of a word, but I want the result to print as a string. How can I do so?
def get_middle(word):
a = int(len(word))
b = int(len(word)/2)
c = int(len(word)/2 - 1)
d = int(len(word)/2 - 0,5)
if a%2==0:
print(str(word[b] + word[c]))
elif a%2==1:
print(str(word[d]))
else:
print("That's not a sring!")
def get_middle(word):
if len(word)%2 == 1:
return word[:int((len(word)-1)/2)]+word[int((len(word)-1)/2)+1:]
I'm making an interest calculator that does compound and simple interest. However, the if statement always runs the simple interest script regardless of input.
I have tried changing variables to strings, integers, and floats. I have tried changing variable names, I have tried removing the first block of code entirely. What the heck is wrong with it???
start = input("simple or compound: ")
if start == "simple" or "Simple":
a = float(input('Starting balance: '))
b = float(input('Rate: '))
c = int(input('Years: '))
final = int(a+((a*b*c)/100))
print(final)
elif start == "compound" or "Compound":
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final2 = int(d*(1+(e/100))**f)
print(final2)
else:
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final3 = int(d*(1+(e/100))**f)
print(final3)
If I input Starting balance as 5000, rate as 5, and years as six into simple it gives 6500. But the same result occurs when I call compound.
This expression is not correct:
start == "simple" or "Simple"
should be
start == "simple" or start "Simple"
code below worked:
start = input("simple or compound: ")
if start == "simple" or start == "Simple":
# print("simple")
a = float(input('Starting balance: '))
b = float(input('Rate: '))
c = int(input('Years: '))
final = int(a+((a*b*c)/100))
print(final)
elif start == "compound" or start == "Compound":
# print("compound")
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final2 = int(d*(1+(e/100))**f)
print(final2)
else:
# print("unknown")
d = float(input('Starting balance: '))
e = float(input('Rate: '))
f = int(input('Years: '))
final3 = int(d*(1+(e/100))**f)
print(final3)
Because of operator precedence
if start == "simple" or "Simple"
is evaluated as
if (start == "simple") or "Simple"
The (...) part is True if the user entered "simple", but the "Simple" part is always True.
I am writing a temperature converter for fun and everything seems to be working except I am getting a 'TypeError: Can't convert 'float' object to str implicitly' message. From what I can tell I am converting it to a string after the fact, can anyone tell me what I am doing wrong?
I looked this this question previously "Can't convert 'float' object to str implicitly"
def tempconverter(startType,Temp):
#conversion types: c -> f c-> K , f -> c, f -> k, k -> c, k -> f
# maybe have them select only their beginning type then show
# all temp types by that temperature
if startType[0].lower() == 'c':
return ('Your temperature ' + Temp +'\n'
+ 'Farenheight: ' + ((int(Temp)*9)/5)+32 + '\n'
+ 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ##
)
elif startType[0].lower() == 'f':
#commented out until first is fixed
#return ((int(Temp)-32)*5)/9
return Temp
elif startType[0].lower() == 'k':
return Temp
print('Welcome to our temperature converter program.')
print('''Please enter your temperature type:
C = Celsius
F = Farenheight
K = Kelvin''')
sType = input('> ')
print('Please enter the temperature you wish to convert.')
sTemp = input('> ')
print(tempconverter(sType,sTemp))
In the line of code:
+ 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ##
The error is caused by this part of it:
Temp+ 273.15
Temp is a string. You can't add a string and a number together.
In this calculation:
((int(Temp)*9)/5)+32
You are not converting your result to str.
Also, you have spelled "Fahrenheit" incorrectly.