Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python if Usage Example

Python if Usage Example

Document Object Reference Manual Python3 Examples

The following example uses the if...elif...else statement to determine whether a number is positive, negative or zero:

Example (Python 3.0+)

Filename : test.py

author by : www.runoob.com

User enters numbers

num

=

float

(

input

(

"

Enter a number:

"

)

)

if

num

0

:

print

(

"

Positive

"

)

elif

num

==

0

:

print

(

"

zero

"

)

else

:

print

(

"

Negative numbers

"

)

The output of the code above is:


输入一个数字: 3
正数

We can also implement this with nested if statements:

Example (Python 3.0+)

Filename :test.py

author by : www.runoob.com

Nested if statements

num

=

float

(

input

(

"

Enter a number:

"

)

)

if

num

=

0

:

if

num

==

0

:

print

(

"

zero

"

)

else

:

print

(

"

Positive

"

)

else

:

print

(

"

Negative numbers

"

)

The output of the code above is:


输入一个数字: 0
零

Document Object Reference Manual Python3 Examples