Python Tutorials

 

Basic Operators

This section explains how to use basic operators in Python.
number = 1 + 2 * 3 / 4.0 print(number)

  2.5

remainder = 11 % 3 print(remainder)

  Using two multiplication symbols makes a power relationship.

squared = 7 ** 2
cubed = 2 ** 3
print
(squared)
print(cubed)
49
8

Python if Statement

The simple Python if statement

You use the if statement to execute a block of code based on a specified condition.

The syntax of the if statement is as follows:

if condition: if-block

The if statement checks the condition first.

If the condition evaluates to True, it executes the statements in the if-block. Otherwise, it ignores the statements.

Note that the colon (:) that follows the condition is very important. If you forget it, you’ll get a syntax error.

The following flowchart illustrates the if staetement:

For example:

age = input('Enter your age:') if int(age) >= 18: print("You're eligible to vote.")
Code language: Python (python)

                

This example prompts you to input your age. If you enter a number that is greater than or equal to 18, it’ll show a message "You're eligible to vote" on the screen. Otherwise, it does nothing.

The condition int(age) >= 18 converts the input string to an integer and compares it with 18.

Enter your age:18
You're eligible to vote.

The following shows the syntax of the if...else statement:

if condition:
if-block;
else
:
else
-block;
Code language: Python (python)

In this syntax, the if...else will execute the if-block if the condition evaluates to True. Otherwise, it’ll execute the else-block.

The following flowchart illustrates the if..else

The following example illustrates you how to use the  if...else statement:

age = input('Enter your age:')
if
int(age) >= 18:
print("You're eligible to vote.")
 else: print("You're not eligible to vote.")

                
Back Next