Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python core/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 pytyhon 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=" ") z="abc" x=2.3 y=9 t=True f=3+9j type(z)
print(type(x)) print(type(z))
a= "Ashi" b= 29 c = 5.5 print("%s is %d years old and her height is %f" %(a,b,c)) print(a,b,c)
x,y,z="sita",28,13.2 #print(x,y,z,sep="\n") #print("%s is %d years old and his rating is %f "%(x,y,z))#%s = string ,%d=integer ,%f=Float print("This is age and year",(x,y,z))

Data Types

Type:To check data type of any variable

p=int(input("Enter your age ")) x= float(input("Enter your height")) print(x) c = complex(input("value"))
#iNPUT from users c = complex(input("value="))
p+x+c
p*x*c
p/c
print(x/p) print(x//p) 4//5
54%7
45+78/89*3-8999
34**4

Comparison Operators

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

Assignment Operator

a=1 a
4+21.4 #indentation "hello"

Bitwise Operators

a=111 b=101 a&b
101
a|b ## OR gate : high even if one value is high
111
d = 101##010 : XOR gate e = 110 d ^ e print(not d)
False
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
False
a =345 b =896 a != a
False

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

a = 234 b ="Python" s = "welcome all" s[0],s[-1] ## First, last s[3:7] #slice a string s[:2] #fetching before members s[2:] # Fetching after members s[::] s[:-1]
'welcome al'
name=input("Your Name = ")
Your Name = welcome You All
##Methods len(name) #name.split(",") #name.count("S") name.split("l")
['we', 'come You A', '', '']
name.lower()
'welcome you all'
name.upper()
'WELCOME YOU ALL'
name.index("e") name.count("l")
3
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())
returns true for digit members= True returns true if space= True returns true if alphabets= True returns true if uppercase members= True

Immutable

name
'welcome You All'
#name[3]="y" #del name[0] del name name
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-47-59123a2c4b11> in <module> 1 #name[3]="y" 2 #del name[0] ----> 3 del name 4 name NameError: name 'name' is not defined
S = "Python" #string assignment print(" String =",S) print("Type=",type(S))
String = Python Type= <class 'str'>
S*6
'PythonPythonPythonPythonPythonPython'

List

L=[1,2,3.8] M=["a",1,45,-9,8.9] len(L) L[0] type(L) L+M
del L[0] L
L[0]=5 L
L.append(9) L
L.insert(0,-10) L
print(max(L)) print(min(L))
Y=[[1,2],[3,2]] Y[1] S=Y[1] S S[0]

Tuples are immutable

T=(1,2,"a") len(T) T[0] #T.append("P") del T[0]

Mutable vs Immutable Objects

Operation & Methods applicable to all sequences

image.png

Operations & Methods applicable to Mutable Sequence

  • List

image.png

#mutable L=[1,2,3] L[2]=9 del L[2]
(1,2)*5
b=(1,2,3,5,6) del b[0]
#Lists L=[1,2,-3.2,0] A=["a",1,8.9] len(L) min(L) del L[2] L[0]=9 L.append(-12) L.insert(2,17) L
#type conversion a=9 b=float(a) c=str(a) #d=tuple(a) Not allowed s=(1,2,3) z=list(s) z
tuple([1,2,3]) a = (1,2,3) list(a)

Membership Statements

  • Membership operators are operators used to validate the membership of a value. It test for membership in a sequence, such as strings, lists, or tuples.

"data"+"Science" 2*"data"
a="learning is an art" b="art" b in a
a="apple is good for health" b="apple" #a in b #b in a # compares menbers #b==a #b is a # exact equal #b is not a "apple" is b

LIST

li=[1,2,3,4] l2=["v","c"] l3=[1,"a",4.5,3] l4=[[1,2],3,4,"abc"]
len(li) li[0] li[-1] l3[2:4]
l3
x=9 y=10 x,y=y,x y
l3
l3=[1,2,3] l3[2]=6 l3
#Mutable l3[0]="ab" del l3[1] l3
a=[1,2,3,4,5] max(a) min(a) a.append("ABC") a.insert(1,"a")

Tuples

T=(1,2,3) T1=("a",6,12)

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

d={1:"ASH",2:"RAM"} d d.keys() d.values() ## adding new members d[3]="SOnal" d del d[1] # keys d
S={"one":1,"two":2,"one":3,"three":2} S

Dictionary Methods & Operations

image.png

c={"a":2,"b":5,"c":3,"d":4,"e":-1} print("Class=",type(c)) print("Call members throgh keys",c["a"]) print("Keys in above dictionary=",c.keys()) print("Values in above dictionary=",c.values()) print("Max value =",max(c.values()))
c={1:"a",2:"b"} #c.pop("a") #removes a #c.update({"f": 20}) print(c)
#iteration for i in [c.values()]: print(i)
l=[] n=int(input(("Enter number of elements"))) for i in range(1,n+1): x=input("Enter Member") l.append(x) print(l)
#Code to generate & print dictonary n=int(input("Input a number ")) d = {} for i in range(1,n+1): x=int(input("Enter Keys")) y=input("Enter Values") d[x]=y #value is square of number print(d) print("*"*20)
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, "b": -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) print("*"*20)
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

Type Conversion

Converting one data type to other.

x=124 y=12.34 z=2+3j a="abcd12" b="128" c=[1,2,3] d=(1,2,3) e={"a":1,"b":2,"c":3} f={1,2,3,4,5,6,3,3}
list(f)
x=int(input("your age = "))

Type Casting

## Int to Float a=2.3 b=int(a) b str(123) str(123.02) #int("12a") int("45") tuple([1,2,3])
a={1:"one",2:"two"} a.values() tuple(a.values())

if else statements

#syntax if condition1: statements elif condition2: statements else: pass
if 5==5: print("a") print("b") elif 4>3:
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")
## 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")
## lOOPS for i in range(1,8): #print(i) print(i,end="\t")
for i in range(102,10,-2): #print(i) print(i,end="\t")
range(1,5,2) list(range(1,10,2))
##Iteration for i in [1,2,3]: print(i,end="\t")
### Loops x=0 while x<3: print("Loop") x=x+1 print("Out of Loop")
## 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") 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****")