0

(I am new to Python so forgive me in advance) I have to write a program that calculates the total of integers from 1 to the user input. So if I input 4, it would add 1+2+3+4. I also added an argument that makes a number that is less than 1 print "invalid number". I am stuck on adding a sentinel that is a letter. Thank you

value = input("Enter a number or press J to terminate: ")
if value < 1:
    print("Invalid number")
else:
    i = 1
    while value > 1:
        i = i + value
        value = value - 1
    print(i)

This is the code that I tried to do:

value = input("Enter a number or J to finish: ")
if value < 1:
    print("Invalid number")
while value ! = "J":
    i = float(value)
else:
    i = 1
    while value > 1:
        i = i + value
        value = value - 1
    print(i)
    value = input("Enter a number or J to finish: ")

Error when J or any number is inputted, '<' not supported between instances of 'str' and 'int'.

maze
  • 1
  • 1
  • First, you understand that ``value = input("Enter a number or J to finish: ")``` value is a string? – Carl_M Nov 25 '22 at 15:51
  • As Carl_M said: you must realize that `value` is a string. Now you're first checking whether value is smaller than 1, which does not make sense for a string. Therefore, it is logical to first check whether it equals `"J"`, and only of it does, try to cast. By the way, this casting (`i = float(value)`) should not be in a while loop, as it will be stuck in an infinite loop if `value` can be casted to a float – QuadU Nov 25 '22 at 15:58

2 Answers2

0

Beginning of an answer.

value = input("Enter a number or J to finish: ")
while value ! = "J":
    i = float(value)
# a placeholder for future code
print(value)
# There is a lot of possible code to achieve the goal.
Carl_M
  • 861
  • 1
  • 7
  • 14
0

the function input() always stores the input as string data-type

so if you give input as 4 means it will consider the 4 as a string not integer

now with this in mind now try:

value = input("Enter a number or J to finish: ")
if value > 1:
   print("BOTH DATA TYPES ARE SAME ")

value = 4

now we are comparing 4 => "string" with 1 => "int", it's not possible to compare "integer" with "string" so the error occurs.

if you want to get input as int then use the following int(input(""))

I hope it'll be helpful, thank you

Hariharan
  • 191
  • 7