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

Getting Started With Python

Uploaded by

unknown22.7one
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views45 pages

Getting Started With Python

Uploaded by

unknown22.7one
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Introduction to Python

Prepared by : Mr. Raja Rawal (PGT CS)


Introduction to Python
• Python programming language was developed by Guido Van Rossum in Feb
1991.
• Python is an easy to learn yet powerful object oriented programming
language.
• It is high level programming language.
• In short
• Easy to use
• Interpreted Language
• Cross platform or Platform independent : languages do not require extensive
recompilation or modification in order to run on a wide range of hardware architectures and
operating systems
• Free and open source: Open-source programming languages are not owned by anyone. They
are easily available, they are usually maintained by a community, and on many occasions, they are
also freely distributed under different open-source licenses.
• Case sensitive :two words that appear or sound identical, but are using different letter cases,
are not considered equal.
Example: Ram, ram, rAm all are different with respect to case sensitive.
Difference between Compiled and Interpreted
Language
Sno Compiled Language Interpreted Language
.
1 Compiled language follows at least two Interpreted language follows one
levels to get from source code to step to get from source code to
execution. execution.
2 A compiled language is converted into An interpreted language is a
machine code so that the processor can language in which the
execute it. implementations execute
instructions directly without earlier
compiling a program into machine
language.
3 The compiled programs run faster than The interpreted programs run
interpreted programs. slower than the compiled program.
4 This language delivers better This language delivers slower
performance. performance.
Python Interpreter Installation and First Program
• You can download Python interpreter from following and install on
your system to run Python code.
• https://www.python.org/
Mode to run python Program File Extension:
.py
Script
Interactive Mode:
Mode:
Output

In script mode, we type Python


Interactive Mode, as the name program in a file and then
suggests, allows us to use interpreter to execute the
interact with OS. Hear, when we content of the file.
type Python statement, interpreter
displays the result(s) immediately.

Python, in interactive mode, is good enough to learn, experiment or


explore, but its only drawback is that we cannot save the statements and
have to retype all the statements once again to re-run them
Practice Questions
print() function in Python
• The print() function in Python is used to output text or other data to
the console.

• object(s): One or more objects (strings, numbers, etc.) that you want
to print. Multiple objects can be separated by commas.
• sep (separator): A string inserted between each object if multiple
objects are provided. The default is a space (‘ ‘).
• end: A string appended after the last object. The default is a newline
character ('\n'), which means each print() call ends on a new line.
Code

Output

Code

Printing Multiple Objects


Output

Code
Using a Custom Separator
Output

Changing the End Character:


input() function in python
• The input() function in Python is used to take input from the user.
• When this function is called, the program pauses and waits for the user to
type something and press the Enter key.
• The input is then returned as a string.

Syntax:
input(prompt)
prompt: A string that is displayed to the user as a prompt before the user inputs something. This
parameter is optional. If provided, it helps the user understand what kind of input is expected.
How It Works:
When input() is executed, it waits for the user to enter data.
The user types something and presses Enter.
The input() function returns the entered data as a string.
Practice Questions
Answers
Python Character Set

Letters A-Z , a-z

Digits 0-9

Special Symbols Space + - * / ** \ ( ) [ ] { } // = !=


== < , > . ‘’ “” ; : % ! @ # >= <=
_(underscore)
Whitespace Blank space, tab() , newline

Other Python can process all ASCII and Unicode


Characters characters as part of data or literals
Token
• Individual words and punctuation marks are called tokens or lexical
unit or lexical elements.
Python has following tokens
1. Keywords
2. Identifiers(names)
3. Literals
4. Operators
5. Punctuations
Keywords: are used to give some special meaning to the interpreter and are used by Python interpreter to
recognize the structure of program.
Total 35 keywords in python as of now.
Program to get keywords in Python

Output
Comment in Python:
comments are used to add explanatory notes or annotations within the code.
They are not executed by the Python interpreter and are purely for the
benefit of the programmer. Comments are helpful for explaining the purpose of the code, making it easier
to understand and maintain.
Types of Comments in Python:
1.Single-Line Comments: Single-line comments begin with the # symbol and continue until the end of the
line.

2. Multi-Line Comments:Python doesn't have a specific syntax for multi-line comments like some other
languages. However, you can use consecutive # symbols on each line to create multi-line comments, or use
a multi-line string (triple quotes ''' or """) as a comment.

Usage of Comments:
Documentation: Comments are used to explain the code, making it more understandable to others (or to
yourself when you come back to the code later).
Clarification : Comments can clarify complex logic or highlight important details in the code.
Identifiers (Names)
• In Python, identifiers are names used to identify a variable, function, class,
module, or other objects.
• Character Set: Identifiers can include letters (both uppercase and
lowercase), digits, and underscores (_).An identifier cannot start with a
digit.
• Case Sensitivity: Identifiers are case-sensitive. For example, myVar, MyVar,
and myvar are all different identifiers.
• Reserved Words: Keywords (reserved words in Python) cannot be used as
identifiers. Examples of keywords include if, else, for, while, class, def, etc.
• Special Characters: Identifiers cannot include special characters such as !,
@, #, $, etc.
• No Spaces: Spaces are not allowed in identifiers. Use underscores (_) to
separate words if necessary, e.g., my_variable.
Literals/ Values
• Literals( Often referred to as constant – value) are data items that
have a fixed value. Python allow several kind of literals:
1. String literal : “Hi”, ‘Hello’
2. Numeric Literals : 1,2 ,3, 7.5 , complex number
3. Boolean : True , False
4. Special Literal None : None is a special constant representing the
absence of a value or a null value.
5. Literal Collections : list, tuple etc
Identifiers are crucial for naming elements in your Python code to make
it readable and maintainable. They are used to reference variables,
functions, classes, etc., throughout your code.
• Examples of Valid Identifiers:
myVariable
_my_variable
Var123
MAX_COUNT
A , a , b , hello
• Examples of Invalid Identifiers:
123variable (starts with a digit)
my-variable (contains a special character -)
if (keyword)
My name (Space between two token)
Variables in python
• In Python, a variable is a name or label that refers to a memory location
where a value is stored. Variables are used to store and manipulate data
throughout a program.
• They act as containers for values, which can be of various types like
integers, strings, lists, dictionaries, etc.
• We use objects (variables) to capture data, which then can be manipulated
by computer to provide information. By now, we know that object/variable
is a name which refers to a value.
• Every object has:
Here a and b are variable and id(a) &
 An Identity, id(b) uses to get address of variable

 A type, and a and b

 A value.
Type (i.e data type) is a set of values, and the allowable
operations on those values. It can be one of the following:
• We use objects (variables) to capture data, which then can be
manipulated by computer to provide information. By now, we know
that object/variable is a name which refers to a value.
• Every object has:
• An Identity,
• A type, and
• value.

Identity of the object is its address in memory and does not get change
once it is created. We may know it by typing id (variable)
1. Number: Number data type stores Numerical Values. This data type is immutable
i.e. value of its object cannot be changed.
• Numbers are of three different types:
a. Integer & Long (to store whole numbers i.e. decimal digits without fraction part)
b. Float/floating point (to store numbers with fraction part)
c. Complex (to store real and imaginary part)
2. None: This is special data type with a single value. It is used to signify
the absence of value/false in a situation. It is represented by None.

3. Sequence: A sequence is an ordered collection of items, indexed


by positive integers. It is a combination of mutable (a mutable
variable is one, whose value may change) and immutable (an
immutable variable is one, whose value may not change) data
types. There are three types of sequence data type available in
Python, they are Strings, Lists & Tuples.
String
• String- It is an ordered sequence of letters/characters. They are
enclosed in single quotes (' ') or double quotes ('' ").
• The quotes are not part of string. They only tell the computer about
where the string constant begins and ends. They can have any
character or sign, including space in them.
• These are immutable. A string with length 1 represents a character in
Python.
Boolean data type
• Python boolean type is one of the built-in data types provided by
Python, which represents one of the two values
• i.e. True or False.
Operators in pythons
• Operators are used to perform operations on variables
and values.
Python divides the operators in the following
groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
Python Arithmetic Operators
• Arithmetic operators are used with numeric values to
perform common mathematical operations:
Operator Name Example Examples:
+ Addition X+Y X = 18
Y=4
- Subtraction X–Y
1. Z=X+Y,Z=?
* Multiplication X*Y 2. Z = X – Y ,Z = ?
/ Division X/Y 3. Z = X * Y , Z =?
4. Z=X/Y,Z?
// Floor division X // Y 5. Z = X // Y , Z = ?
% Modulus X%Y 6. Z = X ** Y , Z = ?
7. Z=X%Y,Z=?
** Exponentiation X ** Y
Example Questions
Python Assignment Operators
• Assignment operators are used to assign values to
variables:
Examples:
X = 15
Y=7
1. X += Y ,X = ?
2. X -= 3 , X = ?
3. X *= 3 , X = ?
4. X /= Y , X = ?
5. X //= Y , X =?
6. X %= Y , X = ?
7. X **= Y , X = ?
Python Comparison Operators
• Comparison operators are used to compare two values:

Example:
5 == 6  ?
5 != 6  ?
5>6 ?
5<6 ?
5 >= 6  ?
6 >= 6  ?
6<= 6  ?
Python Logical Operators
• Logical operators are used to combine conditional
statements:
Casting
• Type Conversion(Casting): Python defines type conversion functions
to directly convert one data type to another.
There are two types of Type Conversion in Python:
• Python Implicit Type Conversion
• Python Explicit Type Conversion
Implicit Type Conversion in Python
• In Implicit type conversion of data types in Python, the Python
interpreter automatically converts one data type to another without
any user involvement. To get a more clear view of the topic see the
below examples.
Program

Output
Explicit Type Conversion in Python
• In Explicit Type Conversion in Python, the data type is manually
changed by the user as per their requirement.
• With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type
int(a, base): This function converts any data type to an integer.
‘Base’ specifies the base in which the string is if the data type is
a string.
float(): This function is used to convert any data type to
a floating-point number.
Output
Exercise
1
3

2
• Convert ASCII value to characters
chr(number): This function converts a number to its corresponding
ASCII character.
Convert character to ASCII
• ord(char): This function converts a charater to its
corresponding ASCII.
Output
Programs
Q1. Write program to obtain tree number and print their sum.
Q2. Program to obtain length and breath of rectangle and print area of
it.
Q3. Write program to input a number and print cube of that number.
Q4. Write a program to input a value in kilo metres and convert to into
miles. (1 km = 0.621371 miles)
Q5. Write a program to input two numbers and swap them.
Q6. Write a program to obtain temperature in Celsius and convert it
into Fahrenheit using formula ( C * 9 / 5 = F)

You might also like