Saturday, September 4, 2021

Python - Conditional statements ,if condition in python

 Python - if - Conditional statements


What is the if condition in python?

Decision-making is the anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.

And if-else Python statement evaluates whether an expression is true or false. If a condition is true, the " if " statement executes. Python if-else statements help coders control the flow of their programs. When you're writing a program, you may want a block of code to run only when a certain condition is met.


Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.

if-condition functioning in the below tree chart.





python





S.No.Statement & Description for if condition
1if statements:

An if statement consists of a boolean expression followed by one or more statements.

2if-else statements:

An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.

3nested - if statements:

You can use one if or else if statement inside another if or else if statement(s).


If the code of an if clause consists only of a single line, it may go on the same line as the header statement.


Example:

num = 15
if ( num == 15 ) : print("Your given number is 15")

Result:

Your given number is 15



Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b 
  • Less than: a < b
  • Less than or equals: a <= b
  • Greater than: a > b
  • Greater than or equals: 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.

Indentation:

Python relies on indentation (whitespace at the beginning of a line) to define the scope in the code. Other programming languages often use curly brackets for this purpose.


Elif condition:

The elif keyword is pythons way of saying, if the previous conditions were not true, then try this condition below.


Example:

num_1 = 25
num_2 = 12
if num_1 > num_2:
  print("num_1 is greater than num_2")
elif num_1 == num_2:
  print("num_1 and num_2 are equal")

Result:

num_1 is greater than num_2


Else statement:

The else keyword catches anything which isn't caught by the preceding conditions.


Example:

num_1 = 15
num_2 = 20
if num_1 == num_2:
  print("num_1 and num_2 are equal")
elif num_1 > num_2:
  print("num_1 is greater than num_2")
else:
  print("num_1 is smaller than num_2")

Result:

num_1 is smaller than num_2


Single line if statement:

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line.


Example:

if num_1 > num_2: print("num_1 is greater than num_2")

Result:

num_1 is greater than num_2


Single line if-else statement:

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line.


Example:

num_1 = 222
num_2 = 333
print("Python"if num_1 > num_2 else print("learning")

Result:

learning


if condition using " and "operator:

The and keyword is a logical operator and is used to combine conditional statements.


Example:

num_1 = 100
num_2 = 99
num_3 = 101
if num_1 > num_2 and num_3 > num_2:
  print("Both conditions are True")
else:
    print("Not fallowing condition")

Result:
Both conditions are True


if condition using " or " operator:

The or the keyword is a logical operator and is used to combine conditional statements.


Example:

num_1 = 100
num_2 = 101
num_3 = 102
if num_1 > num_2 or num_3 > num_2:
  print("one of the conditions is True from both conditions")
else:
    print("Not fallowing condition")

Result:
one of the conditions is True from both conditions


Nested If conditional statements:

You can have if statements inside if statements, this is called nested if statements.


Example:

num_1 = 333
if num_1 >= 111:
  print("Given number is greater than 100")
  if num_1 >= 222:
    print("also, the number is above 200")
else:
    print("conditions are not fallowing.")

Result:
Given number is greater than 100 also, the number is above 200


if condition using " pass " Statement:

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.


Example:

num_1 = 100
num_2 = 111

if num_1 > num_2:
  pass
Result:

No output and no error it just passes the statement.


This is all about if condition, if required any notes comment below.

Follow us on Facebook at @EduTech.trainings













Wednesday, September 1, 2021

Python - Dictionaries

 Python

Python - Dictionaries

Dictionaries:

    Another useful data type built into Python is the dictionary. Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. 

    Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

    Each dictionary key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

    Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

    A Python dictionary consists of a key and then an associated value. That value can be almost any Python object. So a dictionary object always has elements as key-value pairs.

Example:

dict_1 = {'Name': 'Priya', 'Age': 14, 'Class': '9th' }

Updating Dictionary keys and values:


You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the example.


Example:
dict = {'Name': 'priya', 'Age': 7, 'Class': '9th'}
dict['Age'] = 15;                                         # update existing entry
dict['School'] = " PVR School";                # Add new entry

print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
print(dict)
Result:
dict['Age']: 15 dict['School']: PVR School {'Name': 'priya', 'Age': 15, 'Class': '9th', 'School': ' PVR School'}



Delete Dictionary keys and values:

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete the entire dictionary in a single operation.


Example:

dict_1 = {'Name''priya''Age'14'Class''9th'}
del dict_1['Name']; # remove entry with key 'Name'
#dict_1.clear();     # remove all entries in dict
#del dict_1 ;        # delete entire dictionary

print ("Age: ", dict_1['Age'])
print(dict_1)
Results:
Age: 14 {'Age': 14, 'Class': '9th'}

python


Built-in  Functions in Dictionaries:


Sr.No.Function with Description
1cmp(dictionary_1,dictionary_2)

Compares elements of both dictionaries.

2len(dictionary_1)

Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

3str(dictionary_1)

Produces a printable string representation of a dictionary

4type(variable)

Returns the type of the passed variable. If the passed variable is the dictionary, then it would return a dictionary type.


Python Dictionary Methods:


keys()

  • keys() - this method returns the list of keys in the dictionary.

Example:

dict_1 = {'name':'Ravi','class':'10th','age':15,'game':'cricket'}
print(dict_1.keys())

Result:

dict_keys(['name', 'class', 'age', 'game'])

values()

  • values()- this method returns the list of values in the dictionary.

Example:

dict_1 = {'name':'Ravi','class':'10th','age':15,'game':'cricket'}
print(dict_1.values())

Result:

dict_values(['Ravi', '10th', 15, 'cricket'])



items()

  • items()- this method returns the list of the keys and values from the dictionary.

Example:

dict_1 = {'name':'Ravi','class':'10th','age':15,'game':'cricket'}
print(dict_1.items())

Results:

dict_items([('name', 'Ravi'), ('class', '10th'), ('age', 15), ('game', 'cricket')])

get()

  • get()-  this method takes the key as an argument and returns None if the key is not found in the dictionary.
  • We can also set the value to return if a key is not found. This will be passed as the second argument in get() method.

Example:

dict_1 = {'name':'Ravi','class':'10th','age':15,'game':'cricket'}
print(dict_1.get('name'))
print(dict_1.get('school','Not found'))

Results:

Ravi Not found

update()

  • You can add an element that is a key-value pair using the update() method.


Example:

dict_1 = {'name':'Ravi','class':'10th','age':15,'game':'cricket'}
dict_1.update({'school''RCM high school'})
print(dict_1)

Results:

{'name': 'Ravi', 'class': '10th', 'age': 15, 'game': 'cricket', 'school': 'RCM high school'}


dict()

  • We can also create dictionary objects from a sequence of items that pair. This is done using the dict() method
  • dict() function takes the list of paired elements as an argument from the dictionary.

Example:

state_city = [ ( 'Andhrapradesh',' Visakhapatnam'),('Karnataka','Bangaluru'),('Telangana','Hyderabad')]
state_city = dict(state_city)
print(state_city)

Results:

{'Andhrapradesh': ' Visakhapatnam', 'Karnataka': 'Bangaluru', 'Telangana': 'Hyderabad'}


pop()

  • pop()- This method removes and returns an element from the dictionary having the given key.

  • This method takes two arguments/parameters (i) key - key which is to be searched for removal, (ii) default - value which is to be returned when the key is not in the dictionary


Example:

dict_1 = {'name':'Ravi','class':'10th','age':15,'game':'cricket','school''RCM high school'}
dict_1.pop('age')
print(dict_1)

Results:

{'name': 'Ravi', 'class': '10th', 'game': 'cricket', 'school': 'RCM high school'}


This is all about Dictionary for any doubts comment below, provide notes based on a request in the comment.











Python - Conditional statements ,if condition in python

 Python - if - Conditional statements What is the if condition in python? Decision-making is the anticipation of conditions occurring while ...