Home > Net >  How to print different functions according to a given input
How to print different functions according to a given input

Time:08-17

I'm learning python since few weeks ago and I need some help with a code. I'm triying to run a code that display certain value according to the input given by the user, so if user enters 1, x value is shown. I've tried a lot of different ways to do it but surely I'm skipping or ignoring something. How could I make this work? Thanks. (This code only prints second_statement no matter what the user inputs).

def first_statement(x):
    print("xxxx")

def second_statement(x):
    print("yyyy")

x = input("If you want x thing press 1, otherwise, press 2: ")

if x == 1:
    print(first_statement(x))

else:
    print(second_statement(x))

CodePudding user response:

You can change 1 to '1' in if statement or just convert input to int using int() in input line.

First way

def first_statement(x):
    print("xxxx")

def second_statement(x):
    print("yyyy")

x = input("If you want x thing press 1, otherwise, press 2: ")

if x == '1':
    print(first_statement(x))

else:
    print(second_statement(x))

second way

def first_statement(x):
    print("xxxx")

def second_statement(x):
    print("yyyy")

x = int(input("If you want x thing press 1, otherwise, press 2: "))

if x == 1:
    print(first_statement(x))

else:
    print(second_statement(x))

Error:

Because input gives a string even if you enter a number so you have to convert it to a number using int or float. or use string to compare with the input.

  • Related