0% found this document useful (0 votes)
86 views45 pages

Python: Vks-Learning Hub

The document provides an overview of the Python programming language. It describes Python as a simple, interpreted, object-oriented, high-level and open source programming language. It also lists some key features of Python like being free and open source, high-level, interpreted, object-oriented, extensible and having extensive libraries. The document then gives some examples of tasks that can be done with Python like system programming, GUI programming, scripting, database programming and more.

Uploaded by

Vinod Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
86 views45 pages

Python: Vks-Learning Hub

The document provides an overview of the Python programming language. It describes Python as a simple, interpreted, object-oriented, high-level and open source programming language. It also lists some key features of Python like being free and open source, high-level, interpreted, object-oriented, extensible and having extensive libraries. The document then gives some examples of tasks that can be done with Python like system programming, GUI programming, scripting, database programming and more.

Uploaded by

Vinod Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 45

VKS-LEARNING HUB

PYTHON
VKS-LEARNING HUB

What is Python…?
Python is a simple, interpreted, object-oriented, high-level , open source
programming language with dynamic semantics.
 Free & Open source
Freely distributed and Open source
Maintained by the Python community
 High Level Language
 Interpreted
You run the program straight from the source code.
Python program Bytecode a platforms native language
You can just copy over your code to another system and it will work! with
python platform
 Object-Oriented
Simple and additionally supports procedural programming
 Extensible – easily import other code
 Embeddable –easily place your code in non-python programs
 Extensive libraries
(i.e. reg. expressions, doc generation, CGI, ftp, web browsers, ZIP, WAV,
cryptography, etc...) (wxPython, Twisted, Python Imaging library)
VKS-LEARNING HUB

What can I do with Python…?


• System programming

• Graphical User Interface Programming


• Internet Scripting
• Component Integration
• Database Programming
• Gaming, Images, XML , Robot and more…..
VKS-LEARNING HUB

Programming basics
• code or source code: The sequence of instructions in a program.
• syntax: The set of legal structures and commands that can be used in a
particular programming language.
• output: The messages printed to the user by a program.
• console: The text box onto which output is printed.
– Some source code editors pop up the console as an external window,
and others contain their own console window.

4
VKS-LEARNING HUB

Compiling and interpreting


• Many languages require you to compile (translate) your program into a form
that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class

interpret

• Python issource code


instead output into machine instructions.
directly interpreted
Hello.py

5
VKS-LEARNING HUB

Python Interfaces
• IDLE – a cross-platform Python development
environment
• PythonWin – a Windows only interface to
Python
• Python Shell – running 'python' from the
Command Line opens this interactive shell
• For the exercises, we'll use IDLE, but you can
try them all.
VKS-LEARNING HUB

IDLE – Development Environment


• IDLE helps you
program in Python
by:
– color-coding your
program code
– debugging
– auto-indent
– interactive shell
Example Python

• Hello World
print(“Hello World”)
• prints Hello World
VKS-LEARNING HUB

Python programs must be written with a particular structure.


The syntax must be correct, or the interpreter will generate error messages and not
execute the program.
For example print(“VKS-Learning Hub“ )

We will consider two ways in which we can run this statement


1. enter the program directly into IDLE’s interactive shell
2. enter the program into IDLE’s editor, save it, and run it.

To start IDLE from the Microsoft Windows Start menu.


The IDLE interactive shell will open with >>> prompt.
You may type the above one line Python program directly
into IDLE and press enter to execute the program.
the result will be display using the IDLE interactive shell.
VKS-LEARNING HUB

Since it does not provide a way to save the code you enter, the interactive shell is not
the best tool for writing larger programs. The IDLE interactive shell is useful for
experimenting with small snippets of Python code
IDLE’s editor. IDLE has a built in editor.
From the IDLE menu, select New Window,
Editor will open a file . Type the text print(“VKS-Learning-Hub”) into the
editor.
We can run the program from within the IDLE editor by pressing
the F5 function key or from the editor’s Run menu: Run→Run
Module. The output appears in the IDLE interactive shell window.
If program is not saved it give message to save first before run
You can save your program using the Save option in the File menu as
shown in Figure. Save the code to a file named try1.py. The
extension .py is the extension used for Python source code.
VKS-LEARNING HUB

print(“VKS-Learning Hub")

This is a Python statement. A statement is a command that the interpreter


executes. This statement
prints the message VKS-Learning Hub on the screen. A statement is the
fundamental unit of
execution in a Python program. Statements may be grouped into larger chunks
called blocks, and blocks can make up more complex statements. Higher-order
constructs such as functions and methods are composed of blocks. The statement
print(“VKS-Learning Hub") makes use of a built in function named print
VKS-LEARNING HUB

If you try to enter each line one at a time into the IDLE interactive shell, the program’s
output will be intermingled with the statements you type. In this case the best approach
is to type the program into an editor, save the code you type to a file, and then execute
the program. Most of the time we use an editor to enter and run our Python programs.
The interactive interpreter is most useful for experimenting with small snippets of
Python code.
VKS-LEARNING HUB

It is important that no whitespace (spaces or tabs) come before the beginning of each
statement.
In Python the indentation of statements is significant and must be done properly. If
we try to put a single space before a statement in the interactive shell

The interpreter reports a


similar error when we attempt
to run a saved Python program
if the code contains such
extraneous indentation.
VKS-LEARNING HUB
VKS-LEARNING HUB

Python Character Set


Category Example
Letters A-Z, a-z
Digits 0-9
Special Space + - * / ** \ () [] {} // = != == < > . ‘ “ ‘’’ “””
Symbols , ; : % ! & # <= >= @ >>> << >> _(underscore)
White Blank space, tabs, carriage return, new line,
Spaces form-feed
Other All other ASCII and Unicode characters
Characters
VKS-LEARNING HUB

Token
Smallest Individual unit in a program is known as a Token or
a Lexical unit.
• Keyword
• Identifiers (Names)
• Literals
• Operators
• Punctuators
VKS-LEARNING HUB

Keywords
• A keyword is a word having special meaning reserved by the
programming language.

We cannot use a keyword as variable name, function name or any other identifier.


In Python, keywords are case sensitive.
All the keywords except True, False and None are in lowercase and they must be
written as it is. The list of all the keywords are given below.
VKS-LEARNING HUB

Python Identifiers

• Identifier is the name given to entities like class,


functions, variables etc. in Python. It helps differentiating
one entity from another.
Rules for writing identifiers
• Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_). Names
like myClass, var_1 and print_this_to_screen, all are valid example.
• An identifier cannot start with a digit. 1variable is invalid,
but variable1 is perfectly fine.
• Keywords cannot be used as identifiers.
• We cannot use special symbols like !, @, #, $, % etc. in our identifier.
• Identifier can be of any length.
VKS-LEARNING HUB

Valid Identifiers Invalid Identifiers


• Myfile • Data-rec
• School_46 • 48LIC
• _don_ • break
• _fall_down • My.file
• Up_and_down_22
VKS-LEARNING HUB

Literals
1. String Literals 3. Boolean Literals
– Single Line String 4.Special Literals
– Multi Line String 5. Literal Collection
– Raw String – List
– Unicode String – Tuple
2. Numeric Literals – Dictionary
– Integer – Set
– Float
– Complex
VKS-LEARNING HUB

Strings
A String Literal is a sequence of character surrounded by
quotes( Single or double or triple).

Single Line “hello world”


String
Multi Line “””Allahabad “hello\
String Uttar Pradesh””” World”
Raw String r"raw \n string"
Character "C"
Unicode u"\u00dcnic\u00f6de“,
string u"\u0930\u093E\u091C\u0940\u0935"
VKS-LEARNING HUB

Example
strings = "This is Python"
char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string“s
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
Demo1.py
• To calculate length of string use len() function
VKS-LEARNING HUB

Numeric Literals
• Integer
– Decimal Decimal 12, -25, 10035
– Binary Literal Binary 0b1010
– Octal Octal 0o12, 0O35
– Hexadecimal Hexadecimal 0x31A2, 0X4A
• Float Float 3.5, 2000.152,
135.75e25, -3.2e3
• Complex Complex (2 + 3.5j)
Number
VKS-LEARNING HUB

Numeric Literal Examples


a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
Demo2.py
VKS-LEARNING HUB

Boolean Literals
• There are two kinds of Boolean literal: True and False.
Example: demo3.py
x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
VKS-LEARNING HUB

Literal Collections
• fruits = [ "apple", "mango", "orange” ] #list
• numbers = (1, 2, 3) #tuple
• alphabets = { 'a':'apple', 'b':'ball', 'c':'cat’ } #dictionary
• vowels = { 'a', 'e', 'i' , 'o', 'u’ } #set
• print(fruits)
• print(numbers)
• print(alphabets)
• print(vowels)
• Demo5.py
VKS-LEARNING HUB

Operators
• Unary Operator (+, -, ~, not)
• Binary Operator
– Arithmetic Operator (+, -, *, /, %, **, //)
– Relational Operator (<, >, <=, >=, ==, !=)
– Logical Operator (and, or, not)
– Bitwise Operator (&, ^, |, <<, >>)
– Assignment Operator (=, +=, -=, *=, /=, %=,**=, //=)
– Identity Operator (is, not is)
– Membership Operator (in, not in)
VKS-LEARNING HUB

Punctuators
• Most common punctuators in python
are-
'"#\()[]{}@,:.=;
VKS-LEARNING HUB

expressions
• An expressions is any legal combination of
symbols(operators) that represent a value
• 15
• 2.9
• A=a+b
• A+4
• D>5
• F=(3+5)/2
VKS-LEARNING HUB

Python Statement
• Instructions that a Python interpreter can execute are called statements.
• For example, a = 2 is an assignment statement 
• if statement, for statement, while statement etc. are other kinds of statements.

Multi-line statement
In Python, end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\).

For example:
a=1+2+3+\
4+5+6+\
7+8+9
Multiple Statement in Single Line
We could also put multiple statements in a single line using semicolons, as
follows
a = 1; b = 2; c = 3
VKS-LEARNING HUB

Python Indentation
• Most of the programming languages like C, C++, Java use
braces { } to define a block of code. Python uses
indentation.
• A code block (body of a function, loop, class etc.) starts
with indentation and ends with the first unindented line.
• The amount of indentation is up to you, but it must be
consistent throughout that block.
• Generally four whitespaces are used for indentation and
is preferred over tabs.
VKS-LEARNING HUB

Python Comments

Single Line Comment:


• In Python, we use the hash (#) symbol to start writing a
comment.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
• Another way of doing this is to use triple quotes, either ''' or """.
"""This is also a
perfect example of
multi-line comments""“
print(“Hello”)
VKS-LEARNING HUB

Docstring in Python
• Docstring is short for documentation string.
• It is a string that occurs as the first statement in a module, function,
class, or method definition.
• Triple quotes are used while writing docstrings. For example:
def double(num):
"""Function to double the value"""
return 2*num
•  Docstring is available to us as the attribute __doc__ of the function.
Issue the following code in shell once you run the above program.
>>> print(double.__doc__)
Function to double the value : demo6.py
VKS-LEARNING HUB

print
• print : Produces text output on the console.

• Syntax:
print ("Message“)
print (Expression)
– prints the given text message or expression value on the
console, and moves the cursor down to the next line.
print( Item1, Item2, ..., ItemN)
– Prints several messages and/or expressions on the same
line.
34
VKS-LEARNING HUB

Python Input and output


• Printing in a single line with multiple print()
a=25
b=15
c=20
print(a, end=‘ ’)
print(b, end=‘ ‘)
print(c, end=‘ ‘)
print( ) #for line change

print(a, b, c, sep=“:”)
VKS-LEARNING HUB

By default print statement ends with new line

print statement with character given with end parameter

print statement with separator character not given default is space


print statement with separator character given with sep parameter
VKS-LEARNING HUB

Variables
• variable: A named piece of memory that can
store a value.
– Usage:
• Compute an expression's result,
• store that result into a variable,
• and use that variable later in the program.

• assignment statement: Stores a value into a


variable.
– Syntax: name = value
– Examples: x = 5
gpa = 3.14 37
VKS-LEARNING HUB

Declaring Variables in Python


VKS-LEARNING HUB

• Variable Definition
print(x) // will give error because x is not define
Dynamic Typing: A variable pointing to a value of a
certain type can be made to point a value/object of
different type. This is called Dynamic Typing.
X=10
X=“hello”
• Caution with Dynamic Typing
Y=10
X=“hello”
Y=X/2 /// ERROR
VKS-LEARNING HUB

To Know variable type


Type(variable)

All expressions in Python have a type.


The type of an expression indicates the kind of expression it is.
An expression’s type is sometimes denoted as its class.
The built in type function reveals the type of any Python expression:
VKS-LEARNING HUB

input
• input : Reads input data from user.
– You can assign (store) the result of input into a variable. By
default every thing is text /string as input
– Example:
name= input(“Enter your Name“))
age = int(input("How old are you? “))
print ("Your Name is”,name,”and age is",
age)
print("You have", 65 - age, "years left for
retirement“)
Output:
Enter your Name Vinod
How old are you? 53
Your Name is Vinod and age is 53
You have 12 years left for retirement
41
VKS-LEARNING HUB
VKS-LEARNING HUB

Python Input and output


• Printing formatted string
age=10
print(“Your age is {} years”.format(age))
• Printing formatted string (old style)
a=10
b=13.25
c=“Gwalior”
print(“a=%d, b=%f and c =%s“, a, b, c)
VKS-LEARNING HUB
VKS-LEARNING HUB

You might also like