Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
ExampleGet your own Python Server
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")Grading
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL
JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL
MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Python If ... Else
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
ExampleGet your own Python Server
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to test whether
b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to
screen that "b is greater than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Grading
try:
marks = float(input("Please enter the marks (0-100): "))
# Validate the marks are within a plausible range (0-100)
if 0 <= marks <= 100:
if marks >= 90:
grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'
print("Grade:", grade)
else:
print("Invalid marks. Please enter a value between 0 and 100.")
except ValueError:
print("Invalid input. Please enter a numeric value.")
Entering five marks , finding the average and grading
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Declare an array of integers , assign cakes and sort
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
Get the value of the first array item:
x = cars[0]
Return the number of elements in the cars array:
x = len(cars)
Print each item in the cars array:
for x in cars:
print(x)
Print each item in the cars array:
for x in cars:
print(x)
Delete the second element of the cars array:
cars.pop(1)
Creating a function
def my_function():
print("Hello from a function")
Calling a function
def my_function():
print("Hello from a function")
my_function()
Arguments
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of parameters
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will
be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
For loop
Server
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL
JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL
MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Python For Loops
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).
This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
ExampleGet your own Python Server
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
ExampleGet your own Python Server
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL
JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL
MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY CYBERSECURITY DATA SCIENCE
Python While Loops
Python Loops
Python has two primitive loop commands:
while loops
for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
ExampleGet your own Python Server
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an indexing
variable, i, which we set to 1.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
ADVERTISEMENT
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example
Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")