If Statements | Development | Online Course With Appy Pie Academy

If Statements

Lesson Details:
July 10, 2020


I: Introduction

In today’s world, programming is considered to be an important skill that is required in order to get a job in a lot of industries. Computer programmers are a type of professional who need to have a deep knowledge about the different programming languages. In this article I will analyze Python and Ruby and will try to compare them to one another.

II: Body

If statements

Python has a simple if statement structure that is very similar to that of other programming languages such as for example Java or C++. The if statement syntax in Python is:

if [condition]: [statements]

The [condition] is what can be used to determine if the [statements] should be executed or not. If the condition in the parentheses is true then the statements in the brackets below it will be executed. If the condition in the parentheses is false, then the statements below it will not be executed. Here is an example:

import math def calculate_square_root(num): if num < 0 xss=removed xss=removed xss=removed xss=removed>= 0 : return math.sqrt(num) x = calculate_square_root(3) print (x) y = calculate_square_root(-4) print (y) z = calculate_square_root(-2) print (z) y = calculate_square_root(1) print (y) y = calculate_square_root(5) print (y) y = calculate_square_root(0) print (y) y = calculate_square_root(500) print (y)

In this example we have imported math again so that we can use its functions and methods in our program again. We have created a function named calculate_square_root which takes one parameter as an input and returns a value depending on whether it is negative, positive or zero. In this example we use four different inputs for this function and for each input we will see how it behaves differently depending on whether it was negative, positive or zero. In the first example we give 3 as a parameter and a value of 1 is returned since 3 doesn’t match any of the conditions that were defined inside the function. In the second example we give -4 as a parameter and 0 is returned since it matches none of the conditions either. In the third example we give -2 as a parameter and 0 is returned again since the condition matches. In the fourth example we give 1 as a parameter and 1 is returned because it doesn’t match any of the conditions either. In the fifth example we give 5 as a parameter and 0 is returned since it matches none of the conditions either. In the last example we give a parameter of 500 and a value of 1 is returned because it doesn’t match any of the conditions either. With all of these examples, you can now see how else statements work and how they can be used by themselves or together with if statements.

III: Conclusion

loader
Course content