UnderstandingPython
UnderstandingPython
Dear Class,
Please find the basic functions and how they are used with some examples stated below.
I would suggest you to , use an online python editor or Compiler and practice these programs.
https://www.onlinegdb.com/online_python_compiler
print('Good Morning!')
We can also use the print() function to print Python variables. For example,
number = -10.6
name = "Programiz"
# print literals
print(5)
# print variables
print(number)
print(name)
Python Input
While programming, we might want to take the input from the user. In Python, we can use
the input() function.
Syntax of input()
input(prompt)
Run Code
Output
Enter a number: 10
You Entered: 10
In the above example, we have used the input() function to take input from the user and stored the
user input in the num variable.
To convert user input into a number we can use int() or float() functions as:
Python if Statement
An if statement executes a block of code only when the specified condition is met.
Syntax
if condition:
# body of if statement
Here, condition is a boolean expression, such as number > 5, that evaluates to either True or False.
If condition evaluates to False, the body of the if statement will be skipped from execution.
Working of if Statement
if number > 0:
print(f'{number} is a positive number.')
Run Code
Sample Output 1
Enter a number: 10
10 is a positive number.
If user enters 10, the condition number > 0 evaluates to True. Therefore, the body of if is executed.
Sample Output 2
Enter a number: -2
If user enters -2, the condition number > 0 evaluates to False. Therefore, the body of if is skipped
from execution.
Indentation in Python
Python uses indentation to define a block of code, such as the body of an if statement. For example,
x=1
total = 0
if x != 0:
total += x
print(total)
Run Code
Here, the body of if has two statements. We know this because two statements (immediately after if)
start with indentation.
We usually use four spaces for indentation in Python, although any number of spaces works as long
as we are consistent.
You will get an error if you write the above code like this:
# Error code
x=1
total = 0
if x != 0:
total += x
print(total)
Run Code
Here, we haven't used indentation after the if statement. In this case, Python thinks our if statement
is empty, which results in an error.
In the program below, we've used the + operator to add two numbers.
num1 = 1.5
num2 = 6.3
Output
The program below calculates the sum of two numbers entered by the user.
Run Code
Output
In this program, we asked the user to enter two numbers and this program displays the sum of two
numbers entered by user.