Python Tutorial

Week -1:

1. i) Use a web browser to go to the Python website http://python.org . This page contains information about Python and links to Python-related pages, and it gives you the ability to search the Python documentation .

How to Install Python in Windows operating system?

Before installing python in the window system, once check the system is already installed with python or not.

Whether it's available or not, you need to check by searching in the start bar for python by executing the command line argument (cmd) on a windows PC or Windows machine.

If your computer is not installed with python then follow the following steps to download the python for free using website http://www.python.org/

Step:1

Step:2

Step:3

Step:4

Step: 5

Now page setup is progress and install is initialized..

Step: 6

Here, setup is in progress for python 3.6.7 documentation

Step: 7

Then, python 3.6.7 installation is done and setup was made successful ..

Close the python window after installing into your computer.

Step: 1

Go to start button and search for python idle

Step:2 Open the python idle3.6.7 version

As you that Python is a highly level and interpreted programming language. When you write python program in text editor then you need to save file with firstex .py and then upload these files for execution within the Python interpreter, because python files extensions is (.py).

Let us an example“ hello world“ program in python programming language.

Example: firstex.py

print(“Hello World!“)

Explanations

You write the print(“Hello World!“) statement in your text editor and save with filename as firstex.py and then run command line argument (cmd.exe)

Output will be display as:

Hello World!

In the above example, you are started python program by running and also executing.

Kick start for writing a python program

If a python program with less amount of code then it is easy, simple and quick to run and execute on the command line itself instead of write the code on to code file(pychram, sublime, text editor etc..).

Step: 1 . On the Windows computer enter the command line (cmd):

Step: 2 . Here you can write any python programs including the above “Hello World!“ program example.

Step:3

Step:4

ii) Start the Python interpreter and type help() to start the online help utility.

Python 3.6.7 (v3.6.7:6ec5cf24b7, Oct 20 2018, 12:45:02) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license()" for more information.

Step:1

>>> help()

Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out the tutorial on the Internet at https://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam".

help>

step: 2

help > topics

Here is a list of available topics. Enter any topic name to get more help.

ASSERTION DELETION LOOPING SHIFTING

ASSIGNMENT DICTIONARIES MAPPINGMETHODS SLICINGS

ATTRIBUTEMETHODS DICTIONARYLITERALS MAPPINGS SPECIALATTRIBUTES

ATTRIBUTES DYNAMICFEATURES METHODS SPECIALIDENTIFIERS

AUGMENTEDASSIGNMENT ELLIPSIS MODULES SPECIALMETHODS

BASICMETHODS EXCEPTIONS NAMESPACES STRINGMETHODS

BINARY EXECUTION NONE STRINGS

BITWISE EXPRESSIONS NUMBERMETHODS SUBSCRIPTS

BOOLEAN FLOAT NUMBERS TRACEBACKS

CALLABLEMETHODS FORMATTING OBJECTS TRUTHVALUE

CALLS FRAMEOBJECTS OPERATORS TUPLELITERALS

CLASSES FRAMES PACKAGES TUPLES

CODEOBJECTS FUNCTIONS POWER TYPEOBJECTS

COMPARISON IDENTIFIERS PRECEDENCE TYPES

COMPLEX IMPORTING PRIVATENAMES UNARY

CONDITIONAL INTEGER RETURNING UNICODE

CONTEXTMANAGERS LISTLITERALS SCOPING

CONVERSIONS LISTS SEQUENCEMETHODS

DEBUGGING LITERALS SEQUENCES

help>

STEP:3

help > LITERALS

Literals

********

Python supports string and bytes literals and various numeric literals:

literal ::= stringliteral | bytesliteral

| integer | floatnumber | imagnumber

Evaluation of a literal yields an object of the given type (string, bytes, integer, floating point number, complex number) with the given value. The value may be approximated in the case of floating point and imaginary (complex) literals. See section Literals for details.

All literals correspond to immutable data types, and hence the object's identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value.

Related help topics: STRINGS, NUMBERS, TUPLELITERALS, LISTLITERALS,

DICTIONARYLITERALS

help (object)

Object: It is optional parameter, that the object for which the console needs to print its documentation

Example:

help(object)

Output:

Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)

Prints the values to a stream, or to sys.stdout by default.

sep

string inserted between values, default a space.

end

string appended after the last value, default a newline.

file

a file-like object (stream); defaults to the current sys.stdout.

flush

whether to forcibly flush the stream.

(END)

Help on Classes

The help function can also be used on built-in or user defined classes and functions.

Example:1

>>> help(int)

Output:

Help on class int in module built-ins:

class int(object)

| int([x]) -> integer

| int(x, base=10) -> integer

|

| Convert a number or string to an integer, or return 0 if no arguments

| are given. If x is a number, return x.__int__(). For floating point

| numbers, this truncates towards zero.

|

| If x is not a number or if base is given, then x must be a string,

| bytes, or bytearray instance representing an integer literal in the

| given base. The literal can be preceded by '+' or '-' and be surrounded

| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.

| Base 0 means to interpret the base from the string as an integer literal.

| > int('0b100', base=0)

| 4

|

| Built-in subclasses:

| bool

|

| Methods defined here:

|

| __abs__(self, /)
| abs(self)
--More--

To displays the docstring (documentation string) of the user-defined class.

Example:2

class employee:

def __init__(self):

'''The employee class is initialized'''

def print_employee(self):

'''Returns the employee description'''

print('employee description')

help(employee)

Output:

Help on class employee in module __main__:

class employee(builtins.object)

| Methods defined here:

|

| __init__(self)

| The employee class is initialized

|

| print_employee(self)

| Returns the employee description

|

| ----------------------------------------------------------------------

| Data descriptors defined here:

|

| __dict__

| dictionary for instance variables (if defined)

|

| __weakref__

| list of weak references to the object (if defined)

(END)

How to install pycharm python IDE(Integrated Development Environment) into Windows machine.

Step: 1

Step: 2

Step: 3

Step: 4

Step: 5

Step:6

Step:7

Step:8

Step:9

Step:10

Step:11

2. Start a Python interpreter and use it as a Calculator.

def add(x, y): # here we are using add function

return x + y

def subtract(x, y): # This function subtracts two numbers

return x - y

def multiply(x, y): # This function multiplies two numbers

return x * y

def divide(x, y): # This function divides two numbers

return x / y

print("Select operation.")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

while True:

choice = input("Enter choice(1/2/3/4): ") # take input from the user console

if choice in ('1', '2', '3', '4'): # check if choice is one of the four options

try:

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

except ValueError:

print("Invalid input & try enter a number.")

continue

if choice == '1':

print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':

print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':

print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':

print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation

# break the while loop if answer is no

next_calculation = input("Are you interested to do next calculation? (yes/no): ")

if next_calculation == "no":

break

else:

print("Invalid Input")

Output:

Select operation.

1.Add

2.Subtract

3.Multiply

4.Divide

Enter choice(1/2/3/4): 2

Enter first number: 20

Enter second number: 15

20.0 - 15.0 = 5.0

Let's do next calculation? (yes/no): yes

Enter choice(1/2/3/4): 3

Enter first number: 40

Enter second number: 30

40.0 * 30.0 = 1200.0

Are you interested to do next calculation? (yes/no): no

3.i ) Write a program to calculate compound interest when principle, rate and number of periods are given.

Answer:-

Method -1:

P= 1200 # principle amount

T= 2 # time

R= 5.4 # rate

# calculates the compound interest

A=P*(1+(R/100))**T # formula for calculating amount

CI=A-P # compound interest = amount - principal amount

# printing compound interest value

print(CI)

Output:-

133.0992000000001

Method -2:

def compound_interest(principal, rate, time):

# compound interest Calculation

A = principal * (pow((1 + rate / 100), time))

CI= A - principal

print("Compound interest is", CI)

compound_interest(10000, 5, 2)

Output:-

Compound interest is 1025.0

ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points

Answer:-

Method -1: without using the inbuilt library

Input : x1, y1 = (3, 4)

x2, y2 = (4,3)

def distance(x1, y1, x2, y2):

# Calculating distance

return (((x2 - x1)**2 +(y2 - y1)**2)**0.5)

# Drivers Code

print( distance(3, 4, 4, 3))

Output: 1.4142135623730951

Method -2: with Using the inbuilt library i.e., math module.

import math

# Function to calculate distance

def distance(x1 , y1 , x2 , y2):

# Calculating distance

return math.sqrt(math.pow(x2 - x1, 2) +math.pow(y2 - y1, 2) * 1.0)

# Drivers Code

print("%.6f"%distance(3, 4, 7, 3))

Output: 4.123106

4. Read name, address, email and phone number of a person through keyboard and print the details.

Answer:-

name = input("Enter your name: ") # String Input

age = int(input("Enter your age: ")) # Integer Input

marks = float(input("Enter your marks: ")) # Float Input

print("The name is:", name)

print("The age is:", age)

print("The marks is:", marks)

Output:

Enter your name: sateesh

Enter your age: 38

Enter your marks: 786

The name is: sateesh

The age is: 38

The marks is: 786.0