Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python Basics/Python basics-1.ipynb
3074 views
Kernel: Python 3

Contents

  • Introduction

  • Set up & Configuration

  • Operators

  • Data Types

  • If else

  • loops

Python is one among the most popular dynamic programming languages that is being used today. Python is an open-source and object-oriented programming language developed by Dutchman Guido van Possum in 1980s. This language can be utilized for a wide range of applications like scripting, developing and testing. Due to its elegance and simplicity, top technology organizations like Dropbox, Google, Quora, Mozilla, Hewlett-Packard, Qualcomm, IBM, and Cisco have implemented Python.

image.png

Several websites state that Python is one among the most famous programming language of 2016. Because of its implementation and syntax, it pressures more on code readability. When compared to other programming languages like C++ and Java, it requires the programmer to develop lesser codes. It offers automatic memory management and several standard libraries for the programmer. Once a programmer completes Python certification training, he can gain knowledge and experience in a wide range of top IT organizations. It is a general-purpose and high-level coding language.

Because of its features, a large number of programmers across the world, showing interest in making use of this language to develop websites, GUI applications, and mobile applications. The main reason that brings Python one among the top coding languages is that it allows the developers to figure out the concepts by developing readable and less code. Several advantages of Python supports the programmers to alleviate the effort as well as the time required for developing complex and large applications.

1. Using the Interpreter

image.png

Interpreter : An interpreter is a program that reads and executes code. This includes source code, pre-compiled code, and scripts. So if we talk about python interpreter it will execute the code in python by taking single code line at a time.

Scripting : Any program written in python is called a script.The interpreter reads and executes each line of code one at a time, just like a SCRIPT for a play or an audition, hence the the term "scripting language". Python uses an interpreter to translate and run its code and that's why it's called a scripting language

Python Program Executing Model & Architecture

A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the -c option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.

A code block is executed in an execution frame. A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block’s execution has completed.

image.png

  • A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name.

Installation

The following link provides the complete installation guide for python basic IDLE

https://www.python.org/downloads/

Anaconda & Jupyter notebook

Anaconda is a free and open-source distribution of the Python and R programming languages for scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, etc.), that aims to simplify package management and deployment. Package versions are managed by the package management system conda.The Anaconda distribution is used by over 13 million users and includes more than 1400 popular data-science packages suitable for Windows, Linux, and MacOS.

image.png

The following link will guide you to anaconda interface and download details: https://www.anaconda.com/

2.Python Scripting

## int (1,2,344444,-556666) ## float(-1.2, 3.000000000, 344444.999) ## str("a","ash","hello python") print(8+9) print("hello")
print("Welcome all") print(2,"ram",2.3) print(2,"ram","2.3",sep=" \n")
##Placeholders\ Locators a= "Ashi" #strings=%s , Float= %f, int=%d, complex=%s b= 29 c = 5.5 print(a,"is", b, "years old her height is", c,"feet" ,(a,b,c))
w,x,y,z="sita",28,13.2,3+4j #print(x,y,z,sep="\n") print("%s is %d years old and her rating is %f and she is from %s"%(w,x,y,z))
import sys sys.version

Data Types

Type:To check data type of any variable

Python

  • Data types

type(3.4)
a=233333333333333 b=0.0008 type(a) round(float(a),2) str(a) int("123")
float(6) float("6.5")

INPUT VALUE

x=int(input("Enter Number"))
y=float(input("Enter Number ")) s=input(" ") c=complex(input())

Comparison Operators

2.5!=4+3j 3!=4
3>=1.4
13<18
2+5 == 7

Assignment Operator

_a=2 A =8 A+_a a,b=1,2 b
a,b=b,a #swapping
a

Bitwise Operators

a=20 b=10
a=111 b=101 a&b a and b
a|b ## OR gate : high even if one value is high
d = 101##010 : XOR gate e = 110 d ^ e print(not d)
a|b ## OR a^b ## XOR It copies the bit if it is set in one operand but not both. ~a#("one complement") a and b #(AND GATE) a or b #(OR GATE) not a
a =345 b =896 a != a

Built-in Types

Approximately two dozen types are built into the Python interpreter and grouped into a few major categories, as shown : image.png

Sequence type & Assignment

  • Sequences represent ordered sets of objects indexed by nonnegative integers and include strings, Unicode strings, lists, and tuples. -Strings are sequences of characters -

  • lists and tuples are sequences of arbitrary Python objects.

  • Strings and tuples are immutable; lists allow insertion, deletion, and substitution of elements.

  • All sequences support iteration.

1. Strings

s = "Python" s[:2]
len("abcd") a= "this is Python SESSION"
a.split("s")
e=a.lower() e.split("s")
c=a[:5:] c
len(name) #name.split(",") #name.count("S") name.split("l")
name.lower()
name.upper()
a.count("s")
a,x,y="1234","ASHA"," " print("returns true for digit members=",a.isdigit()) print("returns true if space=",y.isspace()) print("returns true if alphabets=",x.isalpha()) print("returns true if uppercase members=",x.isupper())

Immutable

s="Python for Data" w=" Science" x=s+w x
#name[3]="y" #del name[0] del name name
S = "Python" #string assignment print(" String =",S) print("Type=",type(S))
## operations for strings (+,*,/,) s+s ##(concadenation) "Data"*"Data" "6"*"Data" 6 * "Data"
String1 = "bit bought a bit of butter" #String1.index("b") #Find first index of this string. i = String1.find("t") print(i) #Find first index (of this string) after previous index. b = String1.find("t", i+1 ) print(b) c= String1.find("t",i+2) print(c)
## Membership "a" is "A" "e" in "AppleEye"
Z="This is " Z[:7:6]

Create a script to login to myspace web

  1. Create User Name

  2. If user Name is correct create password

  3. If not one more attempt

  4. Once pwd is correctr 1 attempt

  5. Welcome to page and enter details ( Age,Name, Gender)

# To check whether user id you have created is correct or not user=input("Please Create User Name") print("Welcome to interface and enter your user name") username=input("Enter User Name") if username==user: print("Create pass") pwd=input("Create Password") p=input("Input your Password") if p==pwd: elif username != user: print("Invalid user Name reenter") username=input("enter user name ") if username==user: print("welcome") pwd=input("Create Password") p=input("Input your Password") else: print("Relogin max attempt") else: print("Account locked")
Please Create User Namead1 Welcome to interface and enter your user name Enter User Namea2 Invalid user Name reenter enter user name ad1 welcome
##if else elif x=int(input("Enter a number ")) if x==0: print("Number is null") x=x+1 print(x) elif x>0: print("+nUM") elif x<0: print("-NUM") else: pass

List

#dec a=[1,23,24] b=["a","x",1] c=[2,3,4,4.5] a+a a[0] len(a) max(a) min(a) a[-1]
24
a.append(25) a del a[0]
a.insert(2,26)
a.sort(reverse=True) a
[26, 25, 25, 25, 24, 23]
L.append("a") L L.insert(1,"b") L.sort() L.sort() L.sort(reverse=True) del L[0]
x=[-9,12,6,1,3,45] x.sort() x
[-9, 1, 3, 6, 12, 45]
x.sort(reverse=True) x del x[4]
y=["a","e","B"] y.sort() y.sort()
None
y
['B', 'a', 'e']
M=[8,-9,6,34,0,78.66,-1]

Create a list of length 7 (int, floats) and then sort the members in descending order.

  • Fetch middle three members of the list

  • Add "a" ,"b and "c" at index 0,3, 5 Respecticvely

Tuples are immutable

a=() a=(2,3,"a") del a
a.append(1,"b")
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-21-0b99ad79b155> in <module> ----> 1 a.append(1,"b") AttributeError: 'tuple' object has no attribute 'append'
tuple([1,23,23])
(1, 23, 23)

Mutable vs Immutable Objects

Operation & Methods applicable to all sequences

image.png

Operations & Methods applicable to Mutable Sequence

  • List

image.png

## Type Casting String vs Tuples vs Lists tuple("Python") list("Python") list((1,2,3)) tuple([1,2,3]) a=str([1,45])
a[0]
'['

Mapping Types objects : Dictionary

  • A mapping object represents an arbitrary collection of objects that are indexed by another collection of nearly arbitrary key values. Unlike a sequence, a mapping object is unordered and can be indexed by numbers, strings, and other objects. Mappings are mutable.

  • You can use any immutable object as a dictionary key value (strings, numbers, tuples, and so on). Lists, dictionaries, and tuples containing mutable objects cannot be used as keys (the dictionary type requires key values to remain constant).

keys: values

(index: members)

SETS

a={1,1,2,2,55,66} tuple(a) set([1,2,3,3])
{1, 2, 3}

Dictionary

d={} d={1:"A",2:"B",3:"C"} d d.keys() d.values() #Is it possivle to have duplicate keys with diff values z={1:"A",1:"B",2:"C",3:"D"} z
{1: 'B', 2: 'C', 3: 'D'}
#Is it possivle to have duplicate keys with diff values z={1:"A",1:"B",2:"C",3:"D"} z ## Is it possible to have duplicate values with diff keys x={1:"a",2:"b",3:"a"} x
{1: 'a', 2: 'b', 3: 'a'}
#del z[1] z
{2: 'C', 3: 'D'}
x x[4]="g" x[5]="k" x[2]="r" x
{2: 'r', 3: 'a', 4: 'g', 5: 'k'}
c.items() del c[2] c d={} d[1]="P" d[2]="Q" d c={"a":2,"a":7,"b":5,"c":3,"d":7,"e":-1} c c["a"] del c["a"] c["F"]=9 c.values() c.keys() max(c.keys()) max(c.values()) max(c)
d={1:"Apple",2:"Mango"} d d.values() d.keys()
my_dict ={"java":100, "python":112, "c":11} # list out keys and values separately key_list = list(my_dict.keys()) val_list = list(my_dict.values()) # print key with val 100 position = val_list.index(100) print(key_list[position])
java
S={"one":1,"two":2,"one":3,"three":2} S S["four"]=8 S
{'one': 3, 'two': 2, 'three': 2, 'four': 8}

Dictionary Methods & Operations

image.png

#Map two list into dictionaries a = ['red', 'green', 'blue','green'] b = [0,1,2,4] d1 = dict(zip(b, a)) print(d1)
{0: 'red', 1: 'green', 2: 'blue', 4: 'green'}
##range(start,stop-1,interval) list(range(1,6,2)) list(range(10,1,-2))
[10, 8, 6, 4, 2]
list(range(10,20,2)) list(range(11,20,2))
[11, 13, 15, 17, 19]

Loops in Python

for i in range(0,5): print("Three")
Three Three Three Three Three
x=input() x=int(input())
1 3
L=[] n=int(input("Enter number of members")) for i in range(0,n): mem=input("Enter Member") L.append(mem) print(L)
Enter number of members4 Enter Membera Enter Memberb Enter Memberc Enter Memberd ['a', 'b', 'c', 'd']
for i in range(1,15,2): print(i,end="\t")
1 3 5 7 9 11 13
## create a for loop for follwing output: [12,10,8,6,4,2] for j in range(12,0,-2): print (j, end ="\t")
12 10 8 6 4 2

for loop for input lists, dict

d={} n=int(input("Enter num of mem")) for i in range(0,n): name=input("Name") age=int(input("Age")) d[name]=age print(d)
Enter num of mem3 NameA Age23 NameB Age24 NameC Age30 {'A': 23, 'B': 24, 'C': 30}
#Code to generate & print dictonary n=int(input("Input a number ")) d = {} for i in range(1,n+1): x=int(input("Emp ID ")) y=input("Emp NAME ") d[x]=y #value is square of number print(d) print("*"*20)
Input a number 3 Emp ID 102 Emp NAME RAM Emp ID 103 Emp NAME ASH Emp ID 104 Emp NAME SID {102: 'RAM', 103: 'ASH', 104: 'SID'} ********************
l=["red","blue","green"] l1=[1,2,3] d=dict(zip(l,l1)) d
help()
#sort (ascending and descending) a dictionary by value. import operator d = {"a": 334, "y": -489, "d": 893, "z": 111, "x": 506} print('Original ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(0)) print('Dictionary in ascending order by keys : ',sorted_d) sorted_d = sorted(d.items(), key=operator.itemgetter(1),reverse=True) print('Dictionary in descending order by value : ',sorted_d)
Original {'a': 334, 'y': -489, 'd': 893, 'z': 111, 'x': 506} Dictionary in ascending order by keys : [('a', 334), ('d', 893), ('x', 506), ('y', -489), ('z', 111)] Dictionary in descending order by value : [('d', 893), ('x', 506), ('a', 334), ('z', 111), ('y', -489)]
d1 = {'a': 1, 'b': 2} d2 = {'a': 3, 'd': 4} print("merge two dictionaries into d1:") d1.update(d2) print(d1)
#Map two list into dictionaries a = ['red', 'green', 'blue'] b = [0,1,2] d1 = dict(zip(b, a)) print(d1) print("*"*20)
#iterate dictinary over loop d = {'name' : 00, 'ash': 1, 'ashi': 2, 'sid': 3} for dict_key, dict_value in d.items(): print(dict_key,':',dict_value) print("*"*20)

Set Types Objects

A set is an unordered collection of unique items. Unlike sequences, sets provide no indexing or slicing operations. They are also unlike dictionaries in that there are no key values associated with the objects. In addition, the items placed into a set must be immutable.

  • Two different set types are available: set is a mutable set, and frozenset is an immutable set.

set1={11,12,13,14,14,14} set1
s1={1,22,22,3,4,9,5} s2={1,0,8,9,9,} print("s1-s2 will return all unique elements of s1" , s1-s2) print("s1&s2 will return intersection" , s1&s2) print("s1|s2 will return union" , s1|s2)
s={1,2,2,3,3,4,5,6,7} l=[2,3,4,4,5,6,7] l

Multi Target Assignment

a , b = 1,2 print("a=",a ) print("b=",b)
c , s = 26.2 ,"Ashi" print("%s age = %f"%(s,c))
a,b = b,a # swapping a
b

String Methods & Functions

image.png

## If else if cond: statements; elif cond: state; else:

Create an interface with user name and pwd:

x=user p=pwd

3-attempts , site is blocked

if user is correc, ask user to enter pwd, pwd is correct welcome to interface.

l=[1,2,4] 1 in l
True
x=input("YOUR NAME=") pwd=input("create password") user=input("enter user name") if user==x: pas=input("enter password") if pas==pwd: print("Welcome to Home page ") else: print("Wrong password") else: print("Wrong Input Page terminated")
userId="Amit96464" password="Test@01" attempts=0 pwd="" id="" while attempts < 3: id=input("Enter your user id : ") if id!=userId: print("Invalid userId, try again.") continue else: pwd=input("Enter your password : ") if pwd!=password: print("Invalid passwordy, try again.") continue else: print("Welcome to the interface : ",id) break attempts=attempts+1 if attempts==2: print("interface blocked")
File "<ipython-input-31-4034d4803e30>", line 10 id=input("Enter your user id : ") ^ IndentationError: expected an indented block
## Create script to to enter text and terminate it if a blank comes. name = " " name = "abc 123" list(name) x = input("Enter text") new_x=list(x) if new_x==" ":
## Nested a=int(input("First num =")) b=int(input("Second num =")) ch=input("Enter your choice\nA-ADD\nS-SUB\n D-Div\n M-MUL\n P-Power") if ch=="A": print("sum=",a+b) elif ch=="S": print("diff=",a-b) elif ch=="M": print("Prod=",a*b) elif ch=="D": print("DIV=",a/b) elif ch=="P": s=input("Enter\n1-a to b\n2-b to a\n3-a to a\n4-b to b") if s=="1": print(a**b) elif s=="2": print(b**a) elif s=="3": print(a**a) elif s=="4": print(b**b) else: print("invalid choice") else: print("Invalid choice")
## User input list(float numbers) of length six a=[] for i in range(0,5,1): mem=float(input("Enter mem")) a.append(mem) print(a)
### Loops x=0 while x<3: print("Loop") x=x+1 print("Out of Loop")
Loop Loop Loop Out of Loop
  • atleast one Upper case/Lower Case/digit/Spl/10-20/no Space

## 1. Script to check validity a password.(u,l,d,s,no, space,10-20) user=input('Enter Username\t') if len(user)<4: print("invalid user name") user=input("Reenter user name with aleast length greater than 5") else: pass pwd=input('Now Set your passowrd\t') d=a=u=s=l=sp=0 w="@#$%^&*_><?/" for c in pwd: if c.isdigit(): d=d+1 elif c.isalpha(): a=a+1 if c.isupper(): u=u+1 elif c.islower(): l=l+1 elif c in w: s=s+1 #127377057 elif c.isspace(): sp=sp+1 else: pass if d==0: print("invalid password atleast one digit needed") if sp>0: print("Invalid pasword space not allowed") elif a==0: print("Invalid pasword atleast one alpahabet needed") elif u==0: print("INVALID password atleast one in uppercase") elif l==0: print("INVALID password atleast one in lowercase") elif s==0: print("INVALID password atleast one special character") elif len(pwd)<10: print("INVALID MINIMUM LENGTH SHOULD BE 9") else: print("Valid password!!\n\n****WELCOME TO INTERFACE****")