Getting Started with Python
Python is a General Purpose high level Programming language used for developing application
softwares. Developed by Guido van Rossum in 1991.
Features of Python
• High Level
• Free and Open Source
• Case Sensitive
• Interpreted
• Platform Independent
• Rich library of functions
• Dynamic
• General Purpose
Working with Python
To write and run python programs we need Python Interpreter also called Python IDLE.
Execution Mode
We can use Python Interpreter in two ways:
• Interactive mode
• Script mode
Interactive Mode
• Instant execution of individual statement
• Convenient for testing single line of code
• We cannot save statements for future use
Script Mode
• Allows us to write and execute more than one Instruction together.
• We can save programs (python script) for future use
• Python scripts are saved as file with extension ".py"
Python Keywords
• These are predefined words which a specific meaning to Python Interpreter.
• These are reserve keywords
• Keywords in python are case sensitive
Example:- False, class, finally, is, return, None, continue, for, try, def, from, while, if, or etc…
Identifier
Identifiers are name used to identify a variable, function or any other entities in a programs.
Rules for naming Identifier
• The name should begin with an alphabet or and underscore sign and can be followed by any
combination of charaters a-z, A-Z, 0-9 or underscore.
• It can be of any length but we should keep it simple, short and meaningful.
• It should not be a python keyword or reserved word.
• We cannot use special symbols like !, @, #, $, % etc. in identifiers.
Variables
• It can be referred as an object or element that occupies memory space which can contain a value.
• Value of variable can be numeric, alphanumeric or combination of both.
• In python assignment statement is used to create variable and assign values to it.
Data types
These are keywords which determine the type of data stored in a variable. Following table show data
types used in python:
Comments
• These are statement ignored by python interpreter during execution.
• It is used add a remark or note in the source code.
• It starts with # (hash sign) in python.
Operators
These are special symbols used to perform specific operation on values. Different types of operator
supported in python are given below:
• Arithmetic operator ( +,-,*,/,%,//,**)
• Relational operator (= =,!=,>,<,<=,>=)
• Assignment operator
• Logical operator (and ,or ,not)
• Identity operator (is ,not is)
• Membership operator (in, not in)
Expressions
• An expression is combination of different variables, operators and constant which is always
evaluated to a value.
• A value or a standalone variable is also considered as an expression.
Example
56+ (23-13)+89%8 - 2*3
Sequence
**
* / // %
+ -
Evaluation:
= 56+ (23-13) + 89%8 - 2*3
#step1
= 56 + 10+ (89%8) - 2*3
#step2
= 56 + 10 + 1-(2*3)
#step3
= (56+10) +1-6
#step4
= (66 + 1) - 6
#step5
= 67-6
#step6
= 61
Statement
A statement is unit of code that the python interpreter can execute.
Example:
var1 = var2 #assignment statement
x = input ("enter a number") #input statement
print ("total = ", R) #output statement
How to input values in python?
In python we have input() function for taking user input.
Syntax:
Input([prompt])
How to display output in python?
In python we have print() function to display output.
Syntax:
print([message/value])
Example:
Python program to input and output your name
var = input("Enter your name")
print("Name you have entered is ", var)
Example:
Addition of two numbers
Var1 = int(input("enter no1"))
Var2 = int(input("enter no2"))
Total = Var1 + Var2
Print("Total = ", Total)
Control Statement
CHECKING CONDITIONS
if
a = 33
b = 200
if b > a:
print("b is greater than a")
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
if else
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
if ..... elif... elif .....else.....
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
nested if else
You can have if statements inside if statements, this is called nested if statements.
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).
This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.
for x in range(2, 30, 3):
print(x)
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Type Conversion
Type conversion refers to converting one type of data to another type.
Type conversion can happen in two ways:
• Explicit conversion
• Implicit conversion
Explicit Conversion
• Explicit conversion also refers to type casting.
• In explicit conversion, data type conversion is forced by programmer in program
Syntax:
(new_data_type) = (expression)
Explicit type conversion function
Example:
Program of explicit type conversion from float to int
x = 12
y=5
print(x/y) #output - 2.4
print(int(x/y)) #output - 2
Program of explicit type conversion from string to int
x = input("enter a number")
print(x+2) #output - produce error "can only concatenate str to str
x = int(input(Enter a number"))
print(x+2) #output - will display addition of value of x and 2
Implicit conversion
• Implicit conversion is also known as coercion.
• In implicit conversion data type conversion is done automatically.
• Implicit conversion allows conversion from smaller data type to wider size data type without any
loss of information
Example:
Program to show implicit conversion from int to float
var1 = 10 #var1 is integer
var2 = 3.4 #var2 is float
res = var1 var2 #res becomes float automatically after subtraction
print(res) #output - 6.6
print(type(res)) #output-class 'Float'
Strings
• String is basically a sequence which is made up of one or more UNICODE characters.
• Character in string can be any letter, digit, whitespace or any other symbol.
• String can be created by enclosing one or more characters in single, double or triple quotes.
Examples:
Accessing characters in a string (INDEX)
• Individual character in a string can be accessed using indexes.
• Indexes are unique numbers assigned to each character in a string to identify them
• Index always begins from 0 and written in square brackets "[]".
• Index must be an zero, positive or negative integer.
• We get IndexError when we give index value out of the range.
Negative Index
• Python allows negative indexing also.
• Negative indices are used when you want to access string in reverse order.
• Starting from the right side, the first character has the index as -1 and the last character (leftmost) has
the index -n where n is length of string.
Is string immutable?
• Yes, string is immutable data type. The content of string once assigned cannot be altered than.
• Trying to alter string content may lead an error.
String operations
String supports following operations:
• Concatenation
• Repetition
• Membership
• Slicing
Concatenation
• Concatenation refers to joining two strings.
• Plus ('+') is used as concatenation operator.
Repetition
• Repetition as it name implies repeat the given string.
• Asterisk (*) is used as repetition operator.
Membership
• Membership operation refers to checking a string or character is part or subpart of an existing string
or not.
• Python uses 'in' and 'not in' as membership operator.
• 'in' returns true if the first string or character appears as substring in the second string.
• 'not in' returns true if the first string or character does not appears as substring in the second string.
Slicing
• Extracting a specific part of string or substring is called slicing
• Subset occurred after slicing contains contiguous elements
• Slicing is done using index range like string[start_index: end_index: step_value
• End index is always excluded in resultant substring.
• Negative index can also be used for slicing.
Traversing a String
• Traversing a string refers to accessing each character of a given string sequentially.
• For or while loop is used for traversing a string
String Functions