Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Introduction

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Introduction to Program

• A program is a sequence of instructions that specifies how to perform a


computation” .
• The computation might be mathematical ie Solving equations, Finding the roots
of polynomial, symbolic computation such as searching and replacing text in a
document.
Basic Instruction in Language
• Input: Get data from Keyboard.
• Output: Display data on the screen
• Math: Perform the mathematical operations.
• Conditional Execution: Check condition and execute certain code.
• Repetition: Perform some action repeatedly
Introduction to Python Programming

• Python is a high level programming language like C, C++ designed to be easy to


read, and less time to write.

• It is an open source and it is an interpreter which directly executes the program


without creating any executable file

• Python is portable which means python can run on different platform with less or
no modifications.
Introduction to Python Programming

Python Interpreter

• Python Interpreter translates high level instruction into an immediate form of


machine level language. It executes instructions directly without compiling.

• A language translator that converts a high-level language program into a machine


language program, one line at a time, is referred to as an interpreter.

Compiler

A language processor that converts a program written in high-level language into


machine language, entire program at once, is called a compiler.
Introduction to Python Programming

Modes of Python Interpreter


• It is a program that reads and executes python code. It uses of two modes of
execution (i) Interactive mode and (ii) Script mode
Interactive Mode
• Interactive mode is a command line which gives immediate feedback for each
statement.
• A prompt will appear and it usually have 3 greater than signs (>>>). Each Statements
can be enter after this (>>>) symbol.

Example: >>> 1+1


2
>>>5+10
15
Introduction to Python Programming
Script Mode
• In script mode, type python program in a file and store the file with .py extension
• Working in script mode is convenient for testing small piece of code because you can
type and execute them immediately, But for more than few line we can use script since
we can modify and execute in future

Syntax for input and output


Input(‘prompt’)
where prompt is an optional string that is displayed on the string at the time of
taking input.
<class 'str'>

Introduction to Python Programming


Example 1:
# Taking input from the user comments
name = input("Enter your name: ")
Output
print("Hello, " + name)
print(type(name))

Output:
Enter your name: GFG
Hello, GFG
<class 'str'>
Introduction to Python Programming

Debugging
Programming is error –prone, programming errors are called bugs and process of tracking
them is called debugging.
Three kinds of error can occur in a program: a. Syntax Error b. Runtime Error
c. Semantic error.
Syntax error:
• Syntax refers to the structure of a program and rules about the structure.
• Python can only execute a program if the syntax is correct otherwise the interpreter
display an error message.
Introduction to Python Programming

Runtime Error:
The error that occurs during the program execution is called run time error.

Semantic Error:
The computer will not generate any error message but it will not do the right thing since
the meaning of the program is wrong.

Values and data types


• A value is one of the fundamental things a program works with like a word or number.
Example values are 5, 83.0, and 'Hello, World!’.
• These values belong to different types: 5 is an integer, 83.0 is a floating-point number,
and 'Hello, World!' is a string.
Introduction to Python Programming

Example:
>>>type(5) # data type : integer
<class 'int'>
>>>type(83.0) ) # data type : float
<class 'float’>
>>>type('Hello, World!’) # data type : string
<class 'str’>

Python Keywords:
• Keywords are reserved words that cannot be used as ordinary identifiers.
• All the keywords except True, False and None are in lowercase
Introduction to Python Programming

Keywords in Python programming language


False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield


Introduction to Python Programming

Python Identifier
Identifiers are names for entities in a program such as class, variables and functions
etc.
Rules for defining Identifiers:
• Identifiers can be composed of uppercase, lowercase letters, underscore and digits
should start only with an alphabet or an underscore.
• Identifiers can be a combination of lowercase letters (a to z) or uppercase letters (A to Z)
or digits or an underscore.
• Identifiers cannot start with digit
• Keywords cannot be used as identifiers.
• Only ( _ ) underscore special symbol can be used.
Introduction to Python Programming

Example for Identifier


Valid Identifiers: sum total _ab_ add_1
Invalid Identifies: 1x x+y if

Variables
A variable is nothing but a reserved memory location to store values. A variable in a
program gives data to the computer.
Example
>>>b=20
>>>print(b)
Introduction to Python Programming

Example for Identifier


Valid Identifiers: sum total _ab_ add_1
Invalid Identifies: 1x x+y if

Variables
A variable is nothing but a reserved memory location to store values. A variable in a
program gives data to the computer.
Example
>>>b=20
>>>print(b)
Introduction to Python Programming

Python Indentation
Indentation refers to the spaces at the beginning of a code line.
The indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example: Correct Indentation
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Output
Five is greater than two!"
Five is greater than two!"
Introduction to Python Programming

Example: Incorrect Indentation


if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

Output
File "demo_indentation2_error.py", line 3
print("Five is greater than two!")
^
IndentationError: unexpected indent
Introduction to Python Programming

Expressions
An Expression is a combination of values, variables and operators
Example
>>>10+20
12
Statements
• A Statement is an instruction that a python interpreter can execute.
Example
c=a+b
• Multiline statement can be used in single line using semicolon(;)
Example
>>a=1;b=10;c=a +b
Introduction to Python Programming

Comments
Comments are non-executable statements which explain what program does.
There are two ways to represent a comment.
Single Line Comment
Begins with # hash symbol
Example
#This is a comment
print("Hello, World!")
Multiline Comments
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Introduction to Python Programming

Types of Operator:

1. Arithmetic Operator 2. Comparison Operator (or) Relational Operator 3. Assignment


Operator 4. Logical Operator etc..

Arithmetic Operator

It perform some arithmetic operations. Consider the values of a=10, b=20 for the
following table.
Introduction to Python Programming

Operator Meaning Syntax Description

+ Addition a+b It adds and gives the value 30

- Subtraction a-b It subtracts and gives the value -10

* Multiplication a*b It multiplies and gives the value 200

/ Division a/b It divides and gives the value 0.5

a%b
% Modulo It divides and return the remainder 0

** Exponent a**b It performs the power and return 1020


Introduction to Python Programming
Example Program
>>num1=int(input(“enter the number1:”)
>>num2=int(input(“enter the number2:”)
>>>dif = num1 - num2
>>>mul = num1 * num2
>>>div = num1 / num2
>>>modulus = num1 % num2
>>>power = num1 ** num2
>>>floor_div = num1 // num2
>>>print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
>>>print('Difference of ',num1 ,'and' ,num2 ,'is :’, dif)
>>>print('Product of' ,num1 ,'and' ,num2 ,'is :’, mul)
>>>print('Division of ',num1 ,'and' ,num2 ,'is :',div)
>>>print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)
>>>print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
Introduction to Python Programming
Example Program
Output: >>>
Enter First number: 10
Enter Second number 20
Sum of 10 and 20 is : 30
Difference of 10 and 20 is : -10
Product of 10 and 20 is : 200
Division of 10 and 20 is : 0.5
Modulus of 10 and 20 is : 10
Exponent of 10 and 20 is : 100000000000000000000
Floor Division of 10 and 20 is : 0
>>>
Introduction to Python Programming

Logical Operator
Logical Operators are used to combine two or more condition and perform logical
operations using Logical AND, Logical OR, Logical Not.
Description
Operator Example

Both Conditions are


AND If(a<b and a!=b)
true

Anyone of the
If(a<b or a!=b)
OR condition should be
true

The condition returns


NOT Not(a<b) true but not operator
returns false
Introduction to Python Programming

Standard Datatypes
A datatype is a category for values and each value can be of different types. There are
7 data types mainly used in python interpreter.

a) Integer
b) Float
c) Boolean
d) String
e) List
f) Tuple
g) Dictionary
Introduction to Python Programming

Integer
Let Integer be positive values, negative values and zero.
Example:
>>>2+2
4
>>>a=-20
>>> type(a)
output
<type ‘int’>
Float
A floating point value indicates number with decimal point.
>>> a=20.14
>>>type(a) <type ‘float’>
Introduction to Python Programming

Write a Python program to swap two numbers using a temporary variable.

x = input('Enter value of x: ') # To take input from the user


y = input('Enter value of y: ')
temp = x # create a temporary variable
x=y
y = temp
print('The value of x after swapping: {}'.x)
print('The value of y after swapping: {}'.y))
Output:
>>> Enter value of x: 10
Enter value of y: 20
The value of x after swapping: 20
The value of y after swapping: 10
Introduction to Python Programming

Write a python Program to find the quadratic equation


import cmath # import complex math module
a = float(input('Enter a: ')) # To take coefficient from the users
b = float(input('Enter b: '))
c = float(input('Enter c: ')) # calculate the discriminant
d = (b**2) - (4*a*c)
sol1 = (-b-cmath.sqrt(d))/(2*a) # find two solutions
sol2 = (-b+cmath.sqrt(d))/(2*a)
print(“The solution are {0} and {1}”.format(sol1,sol2)) # displays the quadratic equation
Output:
>>> Enter a: 1
Enter b: 5
Enter c: 6
The solution are (-3+0j) and (-2+0j)

You might also like