LEARN PYTHON WITH TCPTUTOR : MODULE 1 – PYTHON

Content –

  • Python – Overview

  • Python – Environment Setup- Download links for windows and smartphone.

  • Python – Basic Syntax-Identifier, Reserve words, Lines and Indentation and Multi-line statements.

  • Python – Variable Types-Strings, Lists, Tuple and Dictionary.

  • Python – Basic Operators-Arithmetic, relational, assignment, logical and bitwise.

  • Python – Decision Making-if, if-else and if-elif-else.

  • Python – Loops-while, for and nested loops.

Overview

  • Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language.
  • It was created by Guido van Rossum during 1985 – 1990.
  • Like Perl, Python source code is also available under the GNU General Public License (GPL).
  • Python is named after a TV Show called ‘Monty Python’s Flying Circus’ .
  • Professionally, Python is great for backend web development, data analysis, artificial intelligence, and scientific computing.
  • Professionally, Python is great for backend web development, data analysis, artificial intelligence, and scientific computing.
  • Also used to build productivity tools, games, and desktop apps.
  • Python is very much versatile. Huge number of Python libraries  are available.
  • Python is a high-level, interpreted, interactive and object-oriented scripting language.
  • Python is designed to be highly readable. It uses English keywords frequently whereas the other languages use punctuations. It has fewer syntactical constructions than other languages.
  • Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.
  • Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
  • Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that encapsulates code within objects.
  • Python is a Beginner’s Language: Python is a great language for the beginner level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.
  • Beginner friendly-
    • Easy to Understand
    • Very Flexible : lots of libraries are available for  traditional (e.g. web development, text processing) to the cutting edge (e.g. AI and machine learning), to biotechnology.
    • Slow : As a dynamically typed language, Python is slow because it is too flexible and the machine would need to do a lot of referencing to make sure what the definition of something is, and this slows Python performance down.
    • Additionally, Python has become a go-to language for data analysis. With data-focused libraries like pandas, NumPy, and matplotlib, anyone familiar with Python’s syntax and rules can deploy it as a powerful tool to process, manipulate, and visualize data.

PYTHON FEATURES

  • Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
  • Easy-to-read: Python code is more clearly defined and visible to the eyes.
  • Easy-to-maintain: Python’s source code is fairly easy-to-maintain.
  • A broad standard library: Python’s bulk of the library is very portable and cross platform
  • Interactive Mode:  Support for an interactive mode , allows interactive testing and debugging of snippets of code.
  • Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
  • Extendable:  Addition of  low-level modules to the Python interpreter is possible. These modules enable programmers to add to or customize their tools to be more efficient.
  • Databases: provides interfaces to all major commercial databases.
  • GUI Programming:  supports GUI applications that can be created and ported to many system calls, libraries and windows systems.
  • Scalable: Python provides a better structure and support for large programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features. A few are listed below-

  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

ENVIRONMENT SETUP

FIRST PYTHON PROGRAM

(1) Interactive Interpreter: Invoking the interpreter without passing a script file as a parameter brings up the following prompt-

>>>

Type the following text at the Python prompt and press Enter-

>>>print (“Hello World”)

Hello World

(2) Script from the Command-line: Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active. Python files have the extension.py   , Create test.py

C:\Python34>Python test.py

Hello World

(3) Integrated Development Environment: You can run Python from a Graphical User Interface.

BASIC SYNTAX

Writing something to the console:

>>>print (“Hello World”)

Hello World

Reading Input from Keyboard:

>>> x=input(“something:”)

something:10

>>>x

‘10’

(note: this input is taken as string

x=int(input(“something:”)) takes integer input.)

BASIC SYNTAX – IDENTIFIER

  • A Python identifier is a name used to identify a variable, function, class, module or other object.  An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
  • Python does not allow punctuation characters such as @, $, and % within identifiers.
  • Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
  • Here are naming conventions for Python identifiers-
    • Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
    • Starting an identifier with a single leading underscore indicates that the identifier is private.
    • Starting an identifier with two leading underscores indicates a strong private identifier.
    • If the identifier also ends with two trailing underscores, the identifier is a language defined special name.

BASIC SYNTAX : RESERVE WORDS

BASIC SYNTAX : LINES AND INDENTATION

  • Python does not use braces({}) to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
  • The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.

BASIC SYNTAX : MULTI-LINE STATEMENTS

  • Statements in Python typically end with a new line. Python, however, allows the use of the line continuation character (\) to denote that the line should continue
  • The statements contained within the [], {}, or () brackets do not need to use the line continuation character

BASIC SYNTAX

  • Comments in Python : The Hash(#)

# This is my First Python Program

  • Multiple Statements on a Single Line : The semicolon ( ; )

>>> item_one=10;item_two=20;item_three=30

  • Using Blank Lines : A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.
  • Multiple Statement Groups as Suites :Groups of individual statements, which make a single code block are called suites in Python.

VARIABLES

  • Variables are nothing but reserved memory locations to store values.
  • Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.
  • Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
  • Python allows you to assign a single value to several variables simultaneously.

  • Standard Data Types:
    • The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.
  • Python has five standard data types-
  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary

Number:

>>>Var1= 1

>>>var2 = 10

VARIABLES : STRINGS

  • Python Strings:

>>> str = ‘Hello World!’

print (str) # Prints complete string

print (str[0]) # Prints first character of the string

print (str[2:5]) # Prints characters from 3rd to 5th

print (str[2:]) # Prints string starting from 3rd character

print (str * 2) # Prints string two times

print (str + “TEST”) # Prints concatenated string

Video tutorial :

Open in youtube app : https://youtu.be/iAzShkKzpJo

VARIABLES : LIST

  • Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One of the differences between them is that 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.

print (list) # Prints complete list

print (list[0]) # Prints first element of the list

print (list[1:3]) # Prints elements starting from 2nd till 3rd

print (list[2:]) # Prints elements starting from 3rd element

print (tiny_list * 2) # Prints list two times

print (list + tiny_list) # Prints concatenated lists

Video tutorial:

Open in youtube app: https://youtu.be/ohCDWZgNIU0

VARIABLES : 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 parenthesis.
  • The main difference between lists and tuples is:  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.

>>> tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )

tinytuple = (123, ‘john’)

print (tuple) # Prints complete tuple

print (tuple[0]) # Prints first element of the tuple

print (tuple[1:3]) # Prints elements starting from 2nd till 3rd

print (tuple[2:]) # Prints elements starting from 3rd element

print (tinytuple * 2) # Prints tuple two times

print (tuple + tinytuple) # Prints concatenated tuple

Video tutorial:

Open in youtube app : https://youtu.be/NI26dqhs2Rk

VARIABLES : DICTIONARY

  • Python’s dictionaries are kind of hash-table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
  • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([])

print (dict[‘one’]) # Prints value for ‘one’ key

print (dict[2]) # Prints value for 2 key

print (tinydict) # Prints complete dictionary

print (tinydict.keys()) # Prints all the keys

print (tinydict.values()) # Prints all the values

Video tutorial :

Open in youtube app : https://youtu.be/XCcpzWs-CI4

VARIABLES

Data Type Conversion

  • Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type-name as a function.
  • There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.
  • int(x [,base]) , float(x), str(x) , tuple(s) ,

BASIC OPERATORS

Types of Operator : Python language supports the following types of operators-

  • Arithmetic Operators : +,-,*,/,%,**(Exponent), //(Floor Division)
  • Comparison (Relational) Operators : >,<,>=,<=,!=,==
  • Assignment Operators : =, +=,-= etc
  • Logical Operators: or,and,not
  • Bitwise Operators : &,|,~ (NOT) ,^(XOR)

DECISION MAKING : IF

  • Decision-making is the anticipation of conditions occurring during the execution of a program and specified actions taken according to the conditions. Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the outcome.
  • You need to determine which action to take and which statements to execute if the outcome is TRUE or FALSE otherwise.

IF Statement :

>>> var2 = 0

if var2:

print (“2 – Got a true expression value”)

print (var2)

print (“Good bye!”)

DECISION MAKING : IFELSE

  • IF…ELIF…ELSE Statements

expression:

statement(s)

else:

statement(s)

  • The elif Statement

if expression1:

statement(s)

elif expression2:

statement(s)

elif expression3:

statement(s)

else:

statement(s)

DECISION MAKING : IF_ELIF_ELSE

Example:

>>>amount=int(input(“Enter amount: “))

if amount<1000:

discount=amount*0.05

print (“Discount”, discount)

elif amount<5000:

discount=amount*0.10

print (“Discount”, discount)

else:

discount=amount*0.15

print (“Discount”, discount)

print (“Net payable:”, amount-discount)

>>>Enter amount: 2000

Discount 200.0

Net payable: 1800.0

Video tutorial:

Open in youtube app : https://youtu.be/f4KOjWS_KZs

LOOPS : WHILE LOOP

  • A loop statement allows us to execute a statement or group of statements multiple times.
  • While loop: Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.

while expression:

statement(s)

>>>count = 0

while (count < 9):

print (‘The count is:’, count)

count = count + 1

print (“Good bye!”)

LOOPS : FOR LOOP

For loop: Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

>>>

numbers=[11,33,55,39,20,55,75,37,21,23,41,13]

for num in numbers:

if num%2==0:

print (‘the list contains an even number’)

break

else:

print (‘the list does not contain even number’)

>>>the list does not contain even number

the list does not contain even number

the list does not contain even number

the list does not contain even number

the list contains an even number

LOOPS – NESTED LOOPS

Example:

for i in range(1,11):

  for j in range(1,11):

  k=i*j

  print (k, end=’ ‘)

  print()

Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

LOOP

Loop Control Statements

  • The Loop control statements change the execution from its normal sequence. When the execution leaves a scope, all automatic objects that were created in that scope are destroyed.
  • break : Terminates the loop statement and transfers execution to the statement immediately following the loop.
  • continue: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
  • pass: It is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass statement is also useful in places where your code will eventually go, but has not been written yet i.e. in stubs).

EXAMPLE :

>>> #use of pass

for letter in ‘Python’:

if letter == ‘h’:

pass

print (‘This is pass block’)

print (‘Current Letter :’, letter)

print (“Good bye!”)

ASSIGNMENTS

1.Write a Python program to calculate a) area of a circle and b) volume of a sphere.

2.Write a Python program to calculate Amount of money in piggybank given the coins are Rs10, Rs5 and Rs2.

3.Given 3 sides of a triangle. Write a Python program to check if triangle can be formed or not. If yes, calculate area of that triangle.

4.Write a Python program to calculate average of 3 numbers and show the maximum deviation.

5.Write a Python program to check if a number is Odd or Even number

6.Write a Python program to check if a number is Prime number or not.

7.Write a Python program to print multiplication table of a number.

8.Write a Python program to check if a number is a Perfect number or not. Perfect number: a positive integer that is equal to sum of its proper divisor, Ex 6=3+2+1, 28=14+7+4+2+1)

SOLUTIONS

#Assg1 : Program to calculate area of a circle

print(“Program to calculate area of a circle:”)

r=float(input(“Radius of the circle:”))

pi=3.14

area=pi*r*r

volume=float(3*pi*r*r*r/4.0)

print(“Area of a circle:”,area)

print(“Volume of a sphere:”,volume)

#Assg3: area of  a triangle

print(“\nProgram to calculate Area of  a triangle”)

a=float(input(“Side 1:”))

b=float(input(“Side 2:”))

c=float(input(“Side 3:”))

if ((a+b>c) and (b+c>a) and (c+a>b)):

print(“area calculation possible:”)

s=float((a+b+c)/2.0)

area_sq= s*(s-a)*(s-b)*(s-c)

print(“area_square of triangle:”,area_sq)

print(“area of triangle”,area_sq ** 0.5)

else:

print(“area can not be calculated”)

#Assg4:Mean and maximum deviation

print(“\nProgram finds mean and maximum deviation:”)

a=float(input(“Input 1st number:”))

b=float(input(“Input 2nd number:”))

c=float(input(“Input3rd Number:”))

avg=float((a+b+c)/3.0)

print(“Mean of 3 numbers”,avg)

max=0.0

if (abs(avg-a)> abs(avg-b)) and (abs(avg-a)> abs(avg-c)):

max=abs(avg-a)

elif (abs(avg-b)> abs(avg-a)) and (abs(avg-b)> abs(avg-c)):

max=abs(avg-b)

else:

max=abs(avg-c)

print(“Maximum deviation is”,max)

#Assg7: Write a Python program to print multiplication table of a number  

print(“\nprogram to print multiplication table of a number”)

a=int(input(“Input any number:”))

print(“\nMultiplication Table:”)

for i in range(1,11,1):

print(a,”x”,i,”=”,a*i)

#Assg8 : Program for perfect number

number=int(input(“Enter number: “))

sum1=0

for i in range(1,number):

if number%i==0:

sum1=sum1+i

print(“sum=”,sum1)

if sum1==number:

print(“perfect number”)

else:

print(“not a perfect number”)

#Another  use of  for loop

line=int(input(“Enter number of line :”))

for i in range(1,line+1,1):

for j in range(1,i+1,1):

print (‘ ‘,end=’ ‘)

for j in range(line,i,-1):

print (‘*’,end=’ ‘)

print()

>>>Enter number of line :6

* * * * *

* * * *

* * *

* *

*

Content Credit – Ms. Rachita Ghoshhajra, Assistant Professor, Computer Science and Engineering Department, MCKVIE.

***********END OF MODULE 1*************

***********NEXT MODULE TO BE UPDATED SOON***********

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here