Python Fundamentals – Branching and Iteration

In the previous note, we have seen how computers work, instruct computers to make our work done, and introduce python, primitive operations, object and types of objects, etc.  We will read more about different kinds of objects, statements, branching, loops, and iterations in this note.

Strings

String in python is enclosed in quotation marks or single quotes. The letters, special characters, spaces, digits, even a character are strings in python.

For example, str = "hello string". In the example, we create a string object named str and store a string called “hello string”.

Concatenation

As strings are immutable data objects, once values are assigned, they can’t be altered. This property makes the string object threadsafe and easily accustom to mutable datatypes such as dictionaries, etc. To concatenate, we use a plus symbol. For example

strvar1 = "Hello"
strvar2 = strvar1 + "World"
print(strvar2)

Input

Input is a function that prints whatever is entered in the quotes, takes input from the users, and stores it in the associated variable. In the below example, the text is the associated string variable.

text = input("Enter the input")
print(text)
# It prints whatever was entered by us

Input function always returns string object to get input as an integer, and we need to cast it. However, if we are typecasting and the user enters the wrong data type, we will get the error. For example:

text = input("Type number")
num = int(text)
print(type(num))

Comparison Operators

We can compare int to int,  float to float, float to int, and string to string data types. However, we can not make comparisons with int to string and float to string, and vice versa. The result of these comparisons always returns in boolean, either true or false.

i = 10
j = 20
print(i < j)

These are many comparison operators, and a few of them are as follows:

  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to
  • == equality 
  • != inequality

Logical Operators

The logical operators are used in python for conditional statements. Let us consider an example where a and b are two variable names. Here not, and, or are logical operators. 

  • not a, it means True if a is False and False if a is True
  • a and b, True if both are True
  • a or b, True if either or both are True

Control Flow – Statements

There are few control flow statements such as 

If statement

Usually, a program contains multiple expressions, statements, conditions, etc. The expressions will be evaluated, only if the condition has a value True. Otherwise, it will be escaped from the flow of execution.

For example, 

if <condition>
   <expression>
   <expression>

if <condition>
   <expression>
else:
   <expression>
   <expression>

 148 total views,  1 views today

Scroll to Top
Scroll to Top