Python Tutorial
#prints zero when input number is 0 int_var = int(input("Please enter an integer: ")); if int_var == 0: print("zero");
int_var = int(input("Please enter an integer: ")); if int_var % 2 == 0: print("even"); # prints even when number is even and not zero else: print('odd'); # prints odd when number is not 0 and not even
int_var = int(input("Please enter an integer: ")); if int_var == 0: print("zero") # prints zero when number is 0 elif int_var % 2 == 0: print("even"); # prints even when number is even and not zero else: print('odd'); # prints odd when number is not 0 and not even
int_var = int(input("Please enter an integer: ")) if int_var % 2 == 0: if int_var == 0: print("zero"); else: print("even"); # prints even when number is even and not zero else: print('odd') # prints odd when number is not 0 and not evenOutput:
$ python test_ifelse.py Please enter an integer: 0 zero $ python test_ifelse.py Please enter an integer: 2 even
str_var = input("Please enter an integer: ");Suppose if we need to get input from user in different format, we type cast it to required format.
int_var = int(input("Please enter an integer: "));This above statement converts input string into integer format.
$ python test_ifelse.py Please enter an integer: sfdsf Traceback (most recent call last): File "test_ifelse.py", line 1, inint_var = int(input("Please enter an integer: ")) File " ", line 1, in NameError: name 'sfdsf' is not defined
condition_is_true if condition else condition_is_false
#!/usr/bin/python a = 10 result = "True" if a <= 10 else "False" print resultOutput:
$ python ternary_test.py TrueAnother way to use ternary operators
(if_condition_is_false, if_condition_is_true)[condition]
#!/usr/bin/python a = 10 #result = "True" if a <= 10 else "False" # Alternate way result = ("False", "True")[a<=10] print resultOutput:
$ python ternary_test.py True
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page