Sunteți pe pagina 1din 23

Python

Python is a popular programming language. It was created in 1991 by Guido van Rossum.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-orientated way or a functional way.

Good to know

 The most recent major version of Python is Python 3.7


 Python will be written in a text editor. It is possible to write Python in an Integrated
Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are
particularly useful when managing larger collections of Python files.
 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
Python Syntax compared to other programming languages

 Python was designed to for readability, and has some similarities to the English language with
influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.
How to download Python and set up it:
1.Open the website https://www.python.org/downloads/
2.DownloadWindows

3. Click on Download Python3.7.2


4.Follow the instructions.

IDE:-Integrated Development Environment:- An integrated development


environment (IDE) is a software application that provides comprehensive facilities to computer
programmers for software development.An IDE normally consists of a source code editor, build
automation tools, and a debugger.
Ex:-Pycharm

How to download Pycharm and set up it:


1. Open the following link
2. https://www.jetbrains.com/pycharm/

3. Click on Download Now


4. Then it will show you two options out of which select Lightweight IDE for Python & Scientific
development.
Click to download

5. Open downloads and execute the setup.

Note: The extension of python file is .py

Print() Method:
To write anything on output screen we required this function it can print the string values.
Ex:-
print(“Hello”) Hello
print(“5”) 5
print(8+9) 17
print(“8+9”) 8+9
print(“8”+”9”) 89
Now draw a triangle using print:
print(" *")
print(" * *")
print(" * *")
print(" *******")

Variables:- Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory. Based on the data type of a
variable, the interpreter allocates memory and decides what can be stored in the reserved memory.
It is useful in case we have to make changes on multiple places in a document. If we have stored in
variable then we have to make changes in one place and it will reflect on all places.
counter = 100 # An integer assignment(int)
miles = 1000.0 # A floating point(float)
name = "John" # A string(str)
Input From User
If you want to receive the value from the user at runtime than we can use Input () method this
bydefault returns the string value if we are using this for numeric value than we have to convert the
received value from string to expected numeric data type(int, float).

First_Name=input(‘enter the First name’)


Last_Name=input(‘enter the Last name’)
Full_Name=First_Name+’ ‘ +Last_Name
print(Full_Name)
Output
enter First Name Pawan
enter the Last name Mishra
Pawan Mishra

First_No=input(‘enter the First name’)


Second_No=input(‘enter the Last name’)
result=First_No+Second_No
print(result)
Output
enter First No 5
enter Second No 2

52
In above example entered value is 5 and 2 the result is 52 because input() method returns string value
and using the + operator will concatenate the given values so in final output result is 52.

//EXAMPLE 1 :- Write a programme to calculate sum of given 2 numbers.


First_No=int(input(‘enter the First name’))
Second_No=int(input(‘enter the Last name’))
result=First_No+Second_No
print(result)
Output
enter First No 5
enter Second No 2

7
//EXAMPLE2:- Write a programme to calculate the percentage of given 5 subject marks.
English=int(input(‘enter marks of English’))
Maths= int(input(‘enter marks of Math’))
Sst= int(input(‘enter marks of SST’))
Science=int(input(‘enter marks of Science’))
Hindi= int(input(‘enter marks of Hindi’))
result=English+Sst+Science+Hindi+Maths
per=result*100/500
print(per)

Python Comments:-

Comments are very important while writing a program. It describes what's going on inside
a program so that a person looking at the source code does not have a hard time figuring it
out. You might forget the key details of the program you just wrote in a month's time.

There are 3 ways of creating comments in Python.

# This is a comment

"""This is a
multiline
comment."""

'''This is also a
multiline
comment.'''

Operators:

Operators are used to perform operations on variables and values. These are special symbols which is
used to specific operation on the operands.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Arithmetic Operators:- Arithmetic operators are used with numeric values to perform common
mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

Shift left by pushing zeros in from the right and let the
<< Zero fill left shift
leftmost bits fall off

Shift right by pushing copies of the leftmost bit in from the


>> Signed right shift
left, and let the rightmost bits fall off

Python Conditions and If statements:

Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You
need to determine which action to take and which statements to execute if outcome is TRUE or
FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the
programming languages −
Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

Indentation

Python relies on indentation, using whitespace, to define scope in the code. Other programming
languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example

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")

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

(and )Operator
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
if a > b and c > a:
print("Both conditions are True")
(or) Operator
The or keyword is a logical operator, and is used to combine conditional statements:
Example

Test if a is greater than b, OR if a is greater than c:

if a > b or a > c:
print("At least one of the conditions is True")

Python Loops:-
In general, statements are executed sequentially: The first statement in a function is executed first, followed
by the second, and so on. There may be a situation when you need to execute a block of code several
number of times.

A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement −
Python has two primitive loop commands:

 while loops
 for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true. while loop

Repeats a statement or group of statements while a given condition is TRUE. It tests the condition
before executing the loop body.

Print i as long as i is less than 6:

Example:1

i=1
while i < 6:
print(i)
i += 1;

Example:2

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"

Output:-
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when
using while loops because of the possibility that this condition never resolves to a FALSE value. This
results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run
continuously so that client programs can communicate with it as and when required.

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

Python 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 language, 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.
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

for i in range(10,16):
print(i)

Output

10

11

12

13

14

15

Using the step value in FOR loop: Step value

for i in range(16,10,-2):
print(i)

String Literals

String literals in python are surrounded by either single quotation marks, or double quotation marks.
It set of alphanumeric values.

'hello' is the same as "hello".

Strings can be output to screen using the print function. For example: print("hello").

Like many other popular programming languages, strings in Python are arrays of bytes representing
Unicode characters. However, Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access elements of the string.

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Output:-e

Substring. Get the characters from position 2 to position 5 (not included):


b = "Hello, World!"
print(b[2:5])

Command-line String Input

Python allows for command line input.

That means we are able to ask the user for input.

The following example asks for the user's name, then, by using the input() method, the program prints
the name to the screen:

print("Enter your name:")


x = input()
print("Hello, " + x)

String Functions:

1.strip()
The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

2 len()
The len() method returns the length of a string, i.e. number of characters in the string.

a = "Hello, World!"
print(len(a)) # return 13

3.lower()
The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower()) # return "hello, world!"

4.upper()
The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper()) # return "HELLO, WORLD!"
5.replace()
The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J")) # return "Jello, World!"

6.split()
The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Python Collections (Arrays)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the
right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.

A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

Output:- ["apple", "banana", "cherry"]

Access Items

You access the list items by referring to the index number:

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])
Output:- “banana”

Change Item Value


To change the value of a specific item, refer to the index number:

Change the second item:


thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
[“apple”,”blackcurrant”,”cherry”]

Loop Through a List


You can loop through the list items by using a for loop:
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

apple
banana
cherry
Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

Output:- yes

List Length

To determine how many items a list have, use the len() method:

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))
Output:-3
The list() Constructor
It is also possible to use the list() constructor to make a list.
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

List Methods

Python has a set of built-in methods that you can use on lists.

srno Method Description


1 append() Adds an element at the end of the list
2 clear() Removes all the elements from the list
3 copy() Returns a copy of the list
4 count() Returns the number of elements with the specified value
5 extend() Add the elements of a list (or any iterable), to the end of the current list
6 index() Returns the index of the first element with the specified value
7 insert() Adds an element at the specified position
8 pop() Removes the element at the specified position
9 remove() Removes the item with the specified value
10 reverse() Reverses the order of the list
11 sort() Sorts the list

1.append():-
The append() method appends an element to the end of the list.
list.append(elmnt)
a = ["apple", "banana", "cherry"]
a.append(“mango”)
Add a list to a list:
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)

2.clear()

Remove all elements from the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']

fruits.clear()

3.copy()
The copy() method returns a copy of the specified list.
fruits = ['apple', 'banana', 'cherry', 'orange']

x = fruits.copy()

4.count():

Return the number of itmes the value "cherry" appears int the fruits list:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

//Write a programme to cound the number of worlds in a string.

msg=”Welcome to the world of Python”;


x=msg.count(“ “);
print(x+1);

5. The extend() method adds the specified list elements (or any iterable) to the end of the current list.
fruits = ['apple', 'banana', 'cherry']

points = (1, 4, 5, 9)

fruits.extend(points)

print(fruits)

['apple', 'banana', 'cherry', 1, 4,5,9]


6. The index() method returns the position at the first occurrence of the specified value.
What is the position of the value 32:
fruits = [4, 55, 64, 32, 16, 32]

x = fruits.index(32)
Output:-3

7. The insert() method inserts the specified value at the specified position.

Syntax
list.insert(pos, elmnt)

Insert the value "orange" as the second elemnent of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")
8. The pop() method removes the element at the specified position.

Syntax
list.pop(pos)

Parameter Values
Parameter Description

Required. A number specifying the position of the element you want to remove
pos
If not specified it returns last value and remove it from list.

Return the removed element:

fruits = ['apple', 'banana', 'cherry']

x = fruits.pop(1)
Output:-banana

9. The remove() method removes the first occurrence of the element with the specified value.

Syntax
list.remove(elmnt)

Parameter Values
Parameter Description

elmnt Required. Any type (string, number, list etc.) The element you want to remove

Remove the "banana" element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")
10. The reverse() method reverses the sorting order of the elements.
Syntax
list.reverse()
The sort() method sorts the list in ascending order by default.
You can also make a function to decide the sorting criteria(s).

Syntax
list.sort(reverse=True|False, key=myFunc)

Parameter Values
Parameter Description

reverse Optional. reverse=True will sort the list descending. Default is reverse=False

key Optional. A function to specify the sorting criteria(s)

Sort the list descending:

cars = ['Ford', 'BMW', 'Volvo']

cars.sort(reverse=True)
print(cars)

Sort the list ascending:

cars = ['Ford', 'BMW', 'Volvo']

cars.sort()
print(cars)
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

You can access tuple items by referring to the index number, inside square brackets:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

Output:- banana

NOTE:-Once a tuple is created, you cannot change its values. Tuples


are unchangeable.
Add Items

Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange" # This will raise an error
print(thistuple)

Print an element from specified position :-

print(thistuple[1])

Output :- banana

Tuple Methods

Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was found
Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Access Items

You cannot access items in a set by referring to an index, since sets are unordered the items has no
index.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set,
by using the in keyword

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Add Items

To add one item to a set use the add() method.

To add more than one item to a set use the update() method.

Example

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add multiple items to a set, using the update() method:

thisset = {"apple", "banana", "cherry"}

thisset.update(["orange", "mango", "grapes"])

print(thisset)
Remove Item

To remove an item in a set, use the remove(), or the discard() method.

Example

Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

S-ar putea să vă placă și