Basics of Python

Like humans, computers use multiple languages to communicate— in this case, programming languages. A programming language is simply a particular way to talk to a computer—a way to use instructions that both humans and the computer can understand.

 

different programming languages

 

Do you know Python Programming and its Application?

Well, don’t you worry! You’ll learn that in this lesson.

Topic Covered in the Lesson

  1. Introduction to Python
  2. Algorithm Basics and Flowcharts.
  3. Make projects in Python IDE (Integrated Development Environment)
  4. Different elements in programming.
  5. Inbuilt functions in Python
  6. Different types of operators.
  7. Input and Output functions

Key Learning Outcomes

At the end of  the lesson, you will be able to:

  1. What is a Program and Programming Analogy?
  2. What is Python Programming?
  3. What are the different elements in programming?
  4. What are the different types of operators used in programming?
  5. Know about input and output functions

Let’s begin!

What is a Program?

A program is a set of instructions that a computer follows to complete a task. The computer receives the information, handles it, utilizes it, and then gives an output based on it by following a program.

 

 

We are surrounded by computers and computer programs; Smartphones, cars, washing machines are all computers, and they follow different programs to carry out different tasks. E.g. when you search for a contact in your phone, a program already fed into the phone finds the correct number for you. Washing machines also have different programs that decide which task the machine will do. E.g. programs control how hot the water will be, or for how long the machine will wash the clothes.

 

Process involved in Programming

According to Linda Liukas, a Finish computer programmer, children’s writer, and programming instructor, programming consist of three parts:

  1. Planning the program
  2. Writing the program in a programming language into a code
  3. Testing and debugging the program

 

 

Programming Analogy

Getting Dressed

On days that you have to go to school, your mother and father are behind you in the morning, asking you to wake up, while you keep saying ‘5 more minutes!’ until you realize it is late and you don’t have time to take bath. So, you decide to just wash your face, brush your teeth, and get dressed.  To get dressed, you follow a particular sequence of steps, like the one given below:

  1. Take off the pajamas
  2. Take off the undergarments from the previous day
  3. Wear a fresh pair of undergarments
  4. Put on the school uniform
  5. Wear accessories such as the belt, tie, and ID card
  6. Wear socks

    Here, as you can see, you followed a set of instructions to complete a task, which is getting dressed (though hastily, and without taking a bath!).

    Now, you know that to properly get dressed, you need to follow the order; you won’t wear a fresh pair of undergarments before taking off the previous ones, nor would you put on the uniform first and then wear undergarments (unless you’re Clark Kent!).

    Similarly, you must write the program in a particular order so that the computer does the task given to it correctly, and we get the result that we expect.

What is Python?

Python is a extensively used in general-purpose and high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed for code readability, and its syntax allows programmers to express their concepts in fewer lines of code.

It is used in various fields and some of are as mentioned:

  • Electronics and Robotics
  • Web and software development
  • Algorithm development and mathematical calculation

Installing the Software

To begin your programming journey, follow our instructions given below carefully and you’ll be well on your way!

  • Installation of Application

We will be using Pydroid 3 for python programming for Android. So go to the playstore or click the link below to install Pydroid on your smartphone.

https://play.google.com/store/apps/details?id=ru.iiec.pydroid3&hl=en_IN&gl=US

  1. After installing the app on your smartphone, you have to click on LET’S START.
  2. You have to select I am absolutely new to this and click on continue
  3. Next, you have to select first option, Learning Python 3 and click continue
  4. Just skip and click on continue.
  5. Now Select simple terminal and press continue.
  6. Here is our Pydroid 3 Interface.

  • Writing our first program:

    Just type in the following code after you start the interpreter.

				
					# Script Begins 
print("Hello! Welcome to Python Programming")
# Scripts Ends

				
			

Pydroid 3 Interface :

 

Output:

 

Other Platforms:

There are certain online interpreters like https://www.onlinegdb.com/online_python_compiler or https://www.online-python.com/ that can be used to run Python programs without installing an interpreter.

Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software. You can download from https://thestempedia.com/product/pictoblox/download-pictoblox/

Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you’re running, type “python” in the terminal emulator. The interpreter should start and print the version number.

https://thestempedia.com/product/pictoblox/download-pictoblox/

macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install Python from https://thestempedia.com/product/pictoblox/download-pictoblox/

Activity 1: Introduce yourself

Let’s perform a simple activity of introducing ourselves in python.

Here, we can use the print statement as follows.

				
					print("Hello everyone!")
print("My name is Pankaj Kumar Verma")
print("I am studying in 7th grade")
print("My hobbies are playing cricket and listening to music")
print("Thank You")
				
			

Output:

Algorithm Basics

Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language.

From the data structure point of view, following are some important categories of algorithms −

  • Search − Algorithm to search an item in a data structure.
  • Sort − Algorithm to sort items in a certain order.
  • Insert − Algorithm to insert item in a data structure.
  • Update − Algorithm to update an existing item in a data structure.
  • Delete − Algorithm to delete an existing item from a data structure.

 

Characteristics of an Algorithm

Not all procedures can be called an algorithm. An algorithm should have the following characteristics −

  • Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs should be clear and must lead to only one meaning.
  • Input − An algorithm should have 0 or more well-defined inputs.
  • Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.
  • Finiteness − Algorithms must terminate after a finite number of steps.
  • Feasibility − Should be feasible with the available resources.
  • Independent − An algorithm should have step-by-step directions, which should be independent of any programming code.

 

How to Write an Algorithm?

There are no well-defined standards for writing algorithms. Rather, it is problem and resource dependent. Algorithms are never written to support a particular programming code. As we know that all programming languages share basic code constructs like loops (do, for, while), flow-control (if-else), etc. These common constructs can be used to write an algorithm. We write algorithms in a step-by-step manner, but it is not always the case. Algorithm writing is a process and is executed after the problem domain is well-defined. That is, we should know the problem domain, for which we are designing a solution.

Example

Let’s try to learn algorithm-writing by using an example.

Problem − Design an algorithm to add two numbers and display the result.

Step 1 − START

Step 2 − declare three integers a, b & c

Step 3 − define values of a & b

Step 4 − add values of a & b

Step 5 − store output of step 4 to c

Step 6 − print c

Step 7 − STOP

Algorithms tell the programmers how to code the program. Alternatively, the algorithm can be written as −

Step 1 − START ADD

Step 2 − get values of a & b

Step 3 − c ← a + b

Step 4 − display c

Step 5 − STOP

In design and analysis of algorithms, usually the second method is used to describe an algorithm. It makes it easy for the analyst to analyze the algorithm ignoring all unwanted definitions. He can observe what operations are being used and how the process is flowing.

Writing step numbers is optional.

We design an algorithm to get a solution to a given problem. A problem can be solved in more than one way.

Hence, many solution algorithms can be derived for a given problem. The next step is to analyze those proposed solution algorithms and implement the best suitable solution.

 

Flowchart and Symbols

Flowcharts graphically represent the flow of a program. There are four basic shapes used in a flow chart. Each shape has a specific use:

  • oval:  start / end
  • parallelogram:  input / output
  • rectangle:  calculations
  • diamond:  selection structures

Arrows connect the basic shapes in a flowchart. The shapes and arrows of a flowchart describe the flow of a program from start to end. Flowcharts typically flow from the top to the bottom or flow from the left to the right. Below is the description of a simple program:

The program starts. Then the program prints out “Output!”. Finally, the program ends.

A flowchart that describes this simple program is shown.

The Python code that corresponds to this flowchart is:

				
					# start
print("Output!")
# end

				
			

Variable and Data Types

Variables play an important role in  programming because they enable us to write flexible programs. Rather than entering data directly into a program, we can use variables to represent the data.

In other words, variable is a symbolic name for a information. The variable’s name represents what information the variable contains. They are called variables because the represented information can change but the operations on the variable remain the same. 

In general, a program should be written with “Symbolic” notation, such that a statement is always true symbolically. For example if I want to know the sum of two grades, We can write “sum = (grade_1 + grade_2) ;” and the variable sum will then contain the sum of the grades regardless of the scores stored in the variables, grade_1 and grade_2.

Variable Types 

Python has four standard data types −

  1. Numbers
  2. String
  3. List
  4. Tuple
  • Numbers

Number data types store numeric values. Number objects are created when you assign a value to them.

For example :

				
					var1=1

var2=10
				
			

Python supported four different numerical types as

  • Int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

For example,

An complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex using the function complex(x,y). The real part can be accessed using the function real() and imaginary part can be represented by imag().

				
					import cmath
# Initializing real numbers
x = 8
y = 9
# converting x and y into complex number
z = complex(x,y);

# printing real and imaginary part of complex number
print ("The real part of complex number is : ",end="")
print (z.real)
print ("The imaginary part of complex number is : ",end="")
print (z.imag)
				
			

Output:

  • String

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes.

				
					str1="Hello World"
				
			
  • List

Lists are the most versatile of Python’s  data types. A list contains items separated by commas and enclosed within square brackets ([]),all the items belonging to a list can be of different data type. The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

For example −

				
					list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print (list1)          # Prints complete list
print (list1[0])       # Prints first element of the list
print (list1[1:3])     # Prints elements starting from 2nd till 3rd 
print (list1[2:])      # Prints elements starting from 3rd element
print (tinylist * 2)  # Prints list two times
print (list1 + tinylist)  # Prints concatenated lists

				
			

Output:

  • Tuple

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

For example –

				
					tuple1 = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print (tuple1)               # Prints the complete tuple
print (tuple1[0])            # Prints first element of the tuple
print (tuple1[1:3])          # Prints elements of the tuple starting from 2nd till 3rd 
print (tuple1[2:])           # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2)       # Prints the contents of the tuple twice
print (tuple1 + tinytuple)   # Prints concatenated tuples

				
			

Output:

Variable Creation

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

				
					x = 5
 y = "John"
 print(x)
 print(y)

				
			

Variables do not need to be declared with any particular type, and can even change type after they have been set.

				
					x = 4  # x is of type int
 x = "Sally"  # x is now of type str
 print(x)

				
			

Casting

If you want to specify the data type of a variable, this can be done with casting.

				
					x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0

				
			

Rules for creating variable names in python

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)

Variable Manipulation

Multi Words Variable Names:

Variable names with more than one word can be difficult to read. There are several techniques you can use to make them more readable:

  • Camel case: Each word, except the first, starts with a capital letter
    myVariableName = “John”
  •  Pascal Case: Each word starts with a capital letter
    MyVariableName = “John”
  • Snake Case: Each word is separated by an underscore character
    my_variable_name = “John”

For Example:

				
					x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

				
			

Output:

Many Values to Multiple Variables:

Python allows you to assign values to multiple variables in one line:

				
					myvar = "John"

 my_var = "John"

 my_var = "John"

 myVar = "John"

 MYVAR = "John"

 myvar2 = "John"
				
			

One Value to Multiple Variables:

And you can assign the same value to multiple variables in one line:

For Example:

				
					x = y = z = "Orange"
print(x)
print(y)
print(z)

				
			

Output:

Output Variables

The Python print statement is often used to output variables. To combine both text and a variable, Python uses the + character:

For Example:

				
					x = "awesome"
print("Python is " + x)

				
			

Output:

You can also use the + character to add a variable to another variable:

For Example:

				
					x = "Python is "
y = "awesome"
z =  x + y
print(z)

				
			

Output:

In-built Functions

In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories:
Data Types Keyword
Text Type str
Numeric Types int, float, complex
Sequence Type list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview

Output Variables

You can get the data type of any object by using the type() function:

For Example

Print the data type of the variable x:

				
					x = 5
print(type(x))

				
			

Output:

Python Operators

Python divides the operators in the following groups:

  • Arithmetic operators
  • Comparison operators
  • Logical operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

For Example:

				
					value1 = 6
value2 = 5
# using the addition operator
result = value1 + value2
print(result)

				
			

Output:

Python Comparison Operators

Comparison operators are used to compare two values:

For Example:

				
					a = 51
b = 15
c = 3
 
print( a == b )

				
			

Output:

Python Logical Operators

Logical operators are used to combine conditional statements:

 

Logical AND Operator

Logical operator returns True if both the operands are True else it returns False.

Logical and operator

For Example:

				
					# Python program to demonstrate
# logical and operator
a = 10
b = 10
c = -10
if a > 0 and b > 0:
    print("The numbers are greater than 0")
				
			

Output:

Logical OR Operator

Logical or operator returns True if either of the operands is True.

For Example:

				
					# Python program to demonstrate
# logical or operator
a = 10
b = -10
c = 0
if a > 0 or b > 0:
   print("Either of the number is greater than 0")
else:
   print("No number is greater than 0")
				
			

Output:

Logical NOT Operator

Logical not operator work with the single boolean value. If the boolean value is True it returns False and vice-versa.

For Example:

				
					  
    a = 10
  
if not a:
    print("Boolean value of a is True")
  
if not (a%3 == 0 or a%5 == 0):
    print("10 is not divisible by either 3 or 5")
else:
    print("10 is divisible by either 3 or 5")

				
			

Output:

Input and Output in Python

How to Take Input from User in Python

Sometimes a developer might want to take user input at some point in the program. To do this Python provides an input() function.

input(‘abc’)

where abc is an optional string that is displayed on the string at the time of taking input.

Note: Python takes all the input as a string input by default. To convert it to any other data type we have to convert the input explicitly. For example, to convert the input to int or float we have to use the int() and float() method respectively.

For Example:

				
					name = input("Enter your name: ")
# Output
print("Hello, " + name)
print(type(name))

				
			

Output:

Enter your name. Here we will write Python. So the output will be,

ACTIVITY 2: Find the student result cleared the examination

Let’s code to display output whether the student passed in examination or not.

Step1 - Flowchart!

Now, let us write Python code according to flowchart!

Step 2 - Let's Code!

The code is pretty simple. Let’s get straight to it. Follow the steps below:

  • First, open the Pydroid 3 on your smartphone and start the syntax by initializing a variable for passing marks with 50 marks.
				
					Passing_marks = 50

				
			
  • Next, we will ask the user to enter the name. For that, we will take input from the user by using the input function and assign it to the name variable.
				
					passing_marks = 50
name = input("Enter your Student name: ")
				
			
  • Now, we will ask the user to enter the marks. For that, we will take input from the user by using the input function and assign it to the marks variable.
				
					passing_marks = 50
name = input("Enter your Student name: ")
obtained_marks= int(input("Enter your marks: "))

				
			
  • Here we will check whether the marks given by the user are equal to or greater than passing marks. So here we will be using or operator and an if statement for checking which will be discussed in detail in the next session. If the condition is true then a print statement can be used to print the student is passed.
				
					passing_marks = 50
name = input("Enter your Student name: ")
obtained_marks= int(input("Enter your marks: "))
if (obtained_marks > passing_marks or obtained_marks == passing_marks):
				
			
  • If the condition is true then a print statement can be used to print the student is passed with ‘+’ operator.
				
					passing_marks = 50
name = input("Enter your Student name: ")
marks= int(input("Enter your marks: "))
if (obtained_marks > passing_marks or obtained_marks == passing_marks):
    print("The student named " + name + " has passed the examination by scoring " + str(obtained_marks) + " marks.")

				
			
  • Similarly we will check if the student is scoring less than the passing marks and print the statement.
				
					passing_marks = 50
name = input("Enter your Student name: ")
marks= int(input("Enter your marks: "))
if (obtained_marks > passing_marks or obtained_marks == passing_marks):
    print("The student named " + name + " has passed the examination by scoring " + str(obtained_marks) + " marks.")
if (obtained_marks < passing_marks):
    print("The student named " + name + " could not pass the examination.")
				
			

Finally, run the code!

Output:

Next Session

Session 9

Conditional Statements

Download PictoBlox – Coding and AI Project Making App

Incase of any difficulty with PictoBlox, please feel free to write us at support@thestempedia.com

Copyright 2021 – Delhi Government All rights reserved | Managed by Valeur Fabtex Private Limited | Technology Partner – STEMpedia