0% found this document useful (0 votes)
4 views10 pages

Python Basics

Uploaded by

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

Python Basics

Uploaded by

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

Python Basics

History of Python
⮚ Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.

Introduction to Python
⮚ It is Open Source Scripting language.
⮚ It is Case-sensitive language (Difference between uppercase and lowercase letters).
⮚ Extension of python program is .py

Features of Python
1. Easy-to-learn
2. Easy-to-maintain
3. Interactive Mode
4. Portable

Advantages Of Python:
⮚ Platform independent
⮚ Higher productivity
⮚ Less learning time
⮚ GUI programming
⮚ Ample availability of libraries

Different ways to start Python:


1. Interactive Mode
You can use Python IDLE in Interactive mode.
⮚ Just start IDLE from start menu.
⮚ It will open Python IDLE and gives you the Python default prompt ">>>".
⮚ On this prompt you can simply write and execute your Python statements.

2. Script Mode:
Many of the homework assignments require you to create a Python script.
This is basically a text file, saved with the extension .py, with a collection of Python statements.
We will use Python IDLE for creating and running Python scripts

1 | Page
1. By entering Python statements in the python shell (prompt) window
>>> print(" Hello World ")
Hello World
>>> print(" Welcome to my first python program" )
Welcome to my first python program
>>> print(10*2)

2. By creating files and running these modules/files using the Run Module item in Run
Menu, or by pressing F5.
Using Python IDLE in Script Mode
The advantage of this approach is you are able to run your scripts very easily within IDLE.
First, go to "Start » All Programs » Python3.7.4 » IDLE Python IDE" to open IDLE.
Next, you need to open a new window for your script.
You can either use the Ctrl + N keyboard shortcut or go to "File » New Window" in the menu

Python Character Set


It is a set of valid characters that a language recognize.
Letters A-Z, a-z

Digits 0-9

Special Characters Space + -* / \ () [] {} = != <> ‘ “ , ;


: % ! & ? _ # <= >= @

Formatting /Escape Sequence characters backspace, horizontal tab, vertical tab, form
feed, and carriage return

TOKENS
✔ A token is a group of characters that logically belong together.
✔ The smallest individual unit of program.
✔ Python uses the following types of tokens.
❑ Keywords,
❑ Identifiers or variables,
❑ Literals,
❑ Punctuators/delimiters,
❑ Operators.

1. Keywords

2 | Page
These are some reserved words in python which have predefined meaning to interpreter called
keywords.
These keywords cannot be used as identifiers.
Some commonly used Keyword are given below:
and or not break for if else

2. Identifiers
A symbolic name is generally known as an identifier.
Rules for formation of an identifier
⮚ An identifier can consist of alphabets, digits and/or underscores.
⮚ It must not start with a digit, always with alphabet or underscore.
⮚ Python is case sensitive that is upper case and lower case letters are considered different
from each other.
⮚ It should not be a reserved word.
⮚ No special character, not even Space allowed.
⮚ Variables or identifiers can be of unlimited length (depends on user’s choice).

Some valid identifiers:


Mybook file123 z2td date_2 _no
Some invalid identifiers:
2rno break my.book data-cs

3. Literals
Literals (often referred to as constants) are data items that never change their value during the
execution of the program.

4. Operators
Operators are special symbols used for specific purposes. Python provides different types of
operators.
⮚ Arithmetical operators
⮚ Relational operators
⮚ Logical operators
⮚ Assignment operators

Arithmetic Operators : Arithmetic Operators are used to perform arithmetic operations like
addition, multiplication, division etc.
Operators Description Example

+ perform addition of two number a+b

- perform subtraction of two number a-b

/ perform division of two number a/b

* perform multiplication of two number a*b

% Modulus = returns remainder a%b

// Floor Division = remove digits after the decimal point a//b

** Exponent = perform raise to power a**b

3 | Page
Relational Operators : Relational Operators are used to compare the values.
Operator Description Example
s

== Equal to, return true if a equals to b a == b

!= Not equal, return true if a is not equals to b a != b

> Greater than, return true if a is greater than b a>b

>= Greater than or equal to , return true if a is greater a >= b


than b or a is equals to b

< Less than, return true if a is less than b a<b

<= Less than or equal to , return true if a is less than b a <= b


or a is equals to b

Assignment Operator : Used to assign values to the variables


Example : a = 5
Here = is the assignment operator and assigns the value of RHS to LHS

Logical Operators : Logical Operators are used to perform logical operations on the given
two variables or values.
Operators Description Example

and return true if both condition are true x and y

or return true if either or both condition are true x or y

not reverse the condition not(a>b)

5. Punctuators
The following characters are used as punctuators.
[] () , ;

Comments in python
● These are the non executable statements.
● Comments may be written anywhere in the program
● Python provides following types of comments :
1. Single line comment:
It starts with #.
The statement after this will not be executed.
int interest= (p * r* t)/100; # calculates simple interest
Starting from # upto end of statement will be commented
2. Multiline Comments
We can use triple quoted string for giving a multiline comment.
It is also called doc string.
for example:

4 | Page
""" this is a
multiline comment “””
which spans many lines

Input and Output


print() : Function In Python is used to print output on the screen.

Input From Keyboard


The main purpose of this function is to read input from the keyboard.
By default, you can input only the string values not numbers

Example 1 :
name= input(‘What is your name:’)
The input () function always returns a value of string type .
If you enter integer value it will be treated as string .
age= int(input(‘What is your age:’))
type(age) =>> int

CONDITIONAL AND ITERATIVE STATEMENTS

Control statements in Python


There are THREE types of control statements in python:
1. Sequential : The statement execute from top to bottom sequentially
2. Selection or conditional : Selection used for decisions, branching - choosing between 2 or
more alternative paths.
3. Repetition or loop or iterative: Repetition used for looping, i.e. repeating a piece of code
multiple times in a row.

Selection / Conditional Statements


Decision-making is the anticipation of conditions occurring during the execution of a program and
specified actions taken according to the conditions.

5 | Page
Conditional control statements are also called branching or selection statements that execute one
group of instructions depending on the outcome of a decision.

Suppose we want to write the scripts for: the following examples:


(i) To input the marks of a student, and if the marks are in the range 28 to 32, then the script
should increase the marks to 33, and otherwise the marks should not be changed. Here we
want to do some task (increase the marks to 33) depending upon a condition (the marks
are in the specified range).
(ii) To input the marks of a student and display the result. If the marks are 33 or more then
calculate result as “Pass”, otherwise calculate result as “Fail”. Here, the script has to
display one of the two messages (“Pass” or “Fail”) depending upon a condition.
(iii) To input marks of a student and display the grade. Grade should be calculated as per the
following criteria: Marks range Grade 90 – 100 A 75 – 89 B 60 – 74 C 50 – 59 D 49 or less
E Here we have to check multiple alternate conditions to calculate the grade.

In all these examples, the script has to check condition(s) and proceed accordingly.
Sometimes the program needs to be executed depending upon a particular condition. Python
provides the following statements for implementing the selection control structure.

Statement Description

if statements An if statement consists of a Boolean expression followed by one


or more statements.

if...else An if statement can be followed by an optional else statement,


which executes when the Boolean expression is false.
statements

nested if You can use one if or else if statement inside another if or else if

statements statement(s).

if...elif...else The if..elif..else statement is used when we need to check multiple


conditions.

1. if statement
syntax :
if condition:
statement(s)
----------------

6 | Page
Statement x
it is clear that if the condition is true, statements within the block are executed otherwise it is
skipped. The statement may either be a single or compound statement.

2. if – else statement
⮚ Like if block, the if…else block also tests the specified condition/expression.
⮚ If the condition is True, the commands in the if part of the block are executed.
⮚ If the condition is False, however, the commands under else part will execute instead.
⮚ The program will only execute one of the two groups of commands in the if…else block.
⮚ syntax of the if - else statement
if condition :
statement(s) # true block
else:
statement(s) # false block
Statement x
⮚ it is clear that the given condition is evaluated first. If the condition is true, true block is
executed. If the condition is false, false block is executed.

7 | Page
3. if – elif … else statement
Syntax :
if condition 1:
statement 1
elif condition 2:
statement 2
elif condition 3:
statement 3
else:
statement

Comparison or Relational Operators:


To form a condition we have to compare two values. Python provides Relational operators (also
called Comparison operators) to compare two values. These relational operators are:

Logical Operators:
● A simple condition can be formed using a relational operator. Sometimes a condition contains
more than one comparison.
● For example, to check if the marks are in the range 28 to 32. In this case we have to check that
marks are greater than or equal to (>=) 28 as well as marks are less than or equal to (<=) 32.

8 | Page
● Each relational operator forms a simple condition. If a condition contains more than one
relational operators then we can say that the condition is complex and the complex condition is
formed by joining simple conditions using Logical operators.
● A complex condition can also be formed by negating a simple condition.

For example, to check that a condition is not true. For forming complex conditions, we have to use
logical operators with simple conditions.

Different logical operators available in Python are:

PROGRAMS ON DECISION CONTROL STATEMENTS


WAP to convert temp from C to F and vice versa as per user’s
choice.

To check whether a person is eligible to vote or not

9 | Page
Write a program to check whether the given number is positive or
negative or zero

WAP to calculate your class grade and grade point for a subject’s
marks as per the table :
Marks Grade Grade Point
81-100 A 10.0
51-80 B 8.0
31-50 C 6.0
00-30 D 2.0

10 | Page

You might also like