number input (\'Please enter a number: .) If Statements If statements allow you
ID: 3725829 • Letter: N
Question
number input ('Please enter a number: .) If Statements If statements allow you to run different code based on conditions that you set. The simplest if statement looks something like this: if condition: code code. If condition evaluates to True, code (which could be many lines of statements) will be run. If condition evaluates to False, then Python will skip to the next line of code after the if statement. For example, this code will print 'Monty', but not 'python': y=0 if x > 1: print('Monty) if y> 1: print 'Python) We want you to prompt the user to enter an integer, and then print the absolute value of that integer You'll need to convert the string you get from input into an integer, as in the previous question. If the user enters a negative number, you need to make it positive (that's what the if statement is for!)Explanation / Answer
#Input from the user obtained is of type string. Using int() function the input string is converted to integer type.
x = int(input("Enter a number: "))
#if the integer is less than zero, then the integer is negative, so it is converted to positive by negating the integer that is already negative to get the absolute value of that integer. If it is not less than zero, then the integer is positive. Hence it is simply returned as its absolute value.
if (x < 0):
print (" Absolute value is: ",-x)
else:
print (" Absolute value is: ",x)
Output:
----------------
Enter a number: -30
Absolute value is: 30
----------
Compiler version: Python 3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.