(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'.
CodePudding user response:
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
CodePudding user response:
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.