Home > database >  Trying to understand If statements when trying to incorporate user Input
Trying to understand If statements when trying to incorporate user Input

Time:10-23

I'm an absolute beginner - like I'm Today-years-old with this.

So I'm mucking about with a silly little piece of code to try and help me understand If statements:

print ('How many sausages have you eaten today?')
userInput = ('>5' or '<5')
if userInput input == int ('> 5'):
    print ('Whoa! Slow down Fatty!')
elif userInput input == ('< 5'):
    print ('Ok, but better call it a day now')

I'm trying to alter the printed message based on how many sausages the user inputs - e.g. above 5 or below 5. I know that I'm doing something (probably many things) wrong. Can anyone help to tidy this up?

CodePudding user response:

Here is a fixed version:

There is some notes to help you understand

# To get an input you need to use input()
userInput = input('How many sausages have you eaten today?')
# Turn the input from text to a number with int()
userInput = int(userInput)
if userInput > 5:
    print ('Whoa! Slow down Fatty!')
elif userInput < 5:
    print ('Ok, but better call it a day now')

CodePudding user response:

Your code has a few problems. First, you cannot use int() to get user input. Instead, you must use input(). Second, you cannot convert inequalities into integers. Like this:

print('How many sausages have you eaten today?')
userInput = int(input())
if userInput > 5:
    print('Whoa! Slow down Fatty!')
else:
    print('Ok, but better call it a day now')

Notice how I get user input with input(), which will return a string. Then, I convert it to an integer with int(). If the user inputs something that is not an integer, then the program will crash because the input to int() must be able to be converted into an integer.

In the if-else statement, I check if userInput, which is an integer, is greater than 5. I also used an else statement, not an elif, because if userInput is exactly 5 then neither statement would have been true.

  • Related