0% found this document useful (0 votes)
33 views

Python Intro

Here are the key points about operator associativity in Python: - Operator associativity refers to which order operators of the same precedence are evaluated. - Most operators in Python are left-associative, meaning they are evaluated from left to right. - For example, in the expression a + b + c, a + b is evaluated first, then the result is added to c. - A few operators like exponentiation (**) are right-associative, meaning they are evaluated from right to left. - So in the expression a ** b ** c, c is exponentiated first, then the result is exponentiated by b. - Knowing the associativity helps determine the order of evaluation when

Uploaded by

nitindibai3
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Python Intro

Here are the key points about operator associativity in Python: - Operator associativity refers to which order operators of the same precedence are evaluated. - Most operators in Python are left-associative, meaning they are evaluated from left to right. - For example, in the expression a + b + c, a + b is evaluated first, then the result is added to c. - A few operators like exponentiation (**) are right-associative, meaning they are evaluated from right to left. - So in the expression a ** b ** c, c is exponentiated first, then the result is exponentiated by b. - Knowing the associativity helps determine the order of evaluation when

Uploaded by

nitindibai3
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Computer Organization

All types of computers follow the same basic logical structure and perform the
following five basic operations for converting raw input data into information
useful to their users.

S.No. Operation Description


The process of entering data and instructions
1 Take Input into the computer system.
Saving data and instructions so that they are
2 Store Data available for processing as and when required.

Performing arithmetic, and logical operations


3 Processing Data on data in order to convert them into useful
information.

The process of producing useful information or


4 Output Information results for the user, such as a printed report or
visual display.

Directs the manner and sequence in which all


5 Control the workflow of the above operations are performed.
 Input Unit
This unit contains devices with the help of which we enter data into the
computer. This unit creates a link between the user and the computer. The input
devices translate the information into a form understandable by the computer.
 CPU (Central Processing Unit)
CPU is considered as the brain of the computer. CPU performs all types of data
processing operations. It stores data, intermediate results, and instructions
(program). It controls the operation of all parts of the computer.

CPU itself has the following three components −

ALU (Arithmetic Logic Unit)


Memory Unit
Control Unit
Operating System
 What is an Operating System?
An Operating system (OS) is a software which acts as an interface between
the end user and computer hardware.
Every computer must have at least one OS to run other programs.
An application like Chrome, MS Word, Games, etc. needs some environment
in which it will run and perform its task.
The OS helps you to communicate with the computer without knowing how to
speak the computer's language. It is not possible for the user to use any
computer or mobile device without having an operating system.
Programming Languages
 A programming language is a formal language comprising a set of
instructions that produce various kinds of output. Programming languages
are used in computer programming to implement algorithms.

 The description of a programming language is usually split into the two


components of syntax(form) and semantics(meaning).

 Programming languages differ from natural languages in that natural


languages are only used for interaction between people, while programming
languages also allow humans to communicate instructions to machines.

 Example: C, C++, C#, Basic, Fortran, Java, Jscript, PHP, Python, Perl etc..

Write an algorithm to add two numbers entered by the user.


Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2
Step 5: Display sum
Step 6: Stop
Difference between Compiler and Interpreter

 We generally write a computer program using a high-level language. A high-


level language is one that is understandable by us, humans. This is
called source code.
 However, a computer does not understand high-level language. It only
understands the program written in 0's and 1's in binary, called the machine
code.
 To convert source code into machine code, we use either a compiler or
an interpreter.
 Both compilers and interpreters are used to convert a program written in a high-
level language into machine code understood by computers. However, there are
differences between how an interpreter and a compiler works.
Interpreter Compiler

Scans the entire program and


Translates program one statement at a
translates it as a whole into machine
time.
code.

Interpreters usually take less amount Compilers usually take a large


of time to analyze the source code. amount of time to analyze the source
However, the overall execution time code. However, the overall execution
is comparatively slower than time is comparatively faster than
compilers. interpreters.

No intermediate object code is Generates intermediate object code


generated, hence are memory which further requires linking, hence
efficient. requires more memory.

Programming languages like


Programming languages like C, C++,
JavaScript, Python, Ruby use
Java use compilers.
interpreters.
What is Python….. ?
 Python was conceived in the late 1980s by Guido van
Rossum at Centrum Wiskunde & Informatica (CWI) in
the Netherlands.
 Python is a general purpose programming language
that is often applied in scripting roles.
 So, Python is programming language as well as
scripting language.
 Python is also called as Interpreted language(executes
the code line by line at a time.)
 Python is also an Integrated language because we can
easily integrated python with other languages like C,
C++, etc.
 Python is case sensitive as it treats upper and lower
case characters differently.
What can I do with Python….. ?

 System Programming
 Graphical User Interface Programming
 Database Programming
 Game development
Why do people use Python….. ?
The following primary factors cited by Python users seem
to be these:
 Python is object-oriented with very simple
syntax rules.
 It’s free (open source)
 It’s powerful
 It’s portable(works on variety of platforms –
Windows,linux,Mac).
 Its completeness(need not to install additional
libraries).
Installing Python

https://www.python.org/downloads/
- Download the latest version of python IDLE and install,
recent version is 3.8.1 , 3.7.1
Running Python

Once you’re inside the Python interpreter, type in


commands .
 Examples:
>>> print ‘Hello World’
Hello World
Math (Operator ) In Python
Try this :

>>> print (3 + 12)


15
>>> print (12 – 3)
9
>>> print 9 + 5 – 15 + 12
11
Arithmetic Operators:
Add: +
Subtract: -
More Operators:
Multiply: *
Divide: /, Integer Division: //

>>> print 3 * 12 36
>>> print 12 / 3 4
>>> print 12.0 / 3.0 4.0
>>> print 11.0 / 3.0 3.66
Relational operators:
>>> print 2 < 3 True
>>> print 2 != 3 True
>>> print False < True True
>>> print ‘Apple’==‘Apple’ True
 Unary operators
The operators that act on one operand are referred to as Unary operators.
Example: +,-.
If a = 5 then +a means 5, -a means -5
If a = 0 then +a means 0, -a means 0
If a = -4 then +a means -4, -a means 4

 Binary operators
The operators that act upon two operands are referred to as Binary operators.
Example: +,-,*,/,//, %(modulus), **(Exponentiation)
4+20 results in 24
a+5(where a=2) results in 7
19 % 6 results in 1
4**3 results in 64
5*6 results in 30
a=15.9, b=3, a/b = 5.3
Augmented Assignment operators
 Example1: if you want to add value of b to value of a and assign the result to a,
then instead of writing
a=0, b=5 a = a + b = 0+5 =5
you may write
a+=b
 Example2: to add value of a to value of b and assign the result to b, you may write
b+=a # instead of b= b + a

x+=y x= x+y
x - =y x=x-y
x *=y x=x*y
x/=y x=x/y
x//=y x=x//y
x**=y x=x**y
Operator Precedence
 Order of execution through Operator Precedence.
Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR
 Examples:
f=‘god’, g=‘God’,h=‘god’,j=‘God’, k=“Godhouse”
f==h will return True
“God”==“Godhouse” will return True
g== j will return True
“god” < “Godhouse” will return False

 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 not(x<5 and x<10)
the result is true
Operator Associativity
 Python will evaluate the operator with higher precedence first. BUT what if
the expression contains two operators that have the same precedence ?
 In this case, associativity helps determine the order of operations.
Associativity is the order in which an expression is evaluated.
>>> print(7*8/5//2)
5.0
 Multiple operators with the same precedence, other than **, in the same
expression is left evaluated first and then the operator on its right and so on.
 An expression having multiple ** operators is evaluated from right to left.
Example: 3**3**2
19683
Type Conversion
 In a mixed-mode expression , different types of variables/constants are
converted to one same type. This process is called type conversion (also
known as coercion).
 Type conversion can take place in two forms: implicit( that is performed by
compiler without programmer’s intervention) and explicit (also known as
type casting) (that is defined by the user).
 Implicit type conversion(Coercion):
ch=5 #integer
i=2 #integer
fl = 4 #integer
db = 5.0 #floating point number
fd = 36.0 #floating point number
A= (ch + i)/db # expression1
B = fd/db* ch/2 #expression2
print(A)
print(B)
 Explicit type conversion(Type Casting):
example: if we have (a=3 and b= 5.0), then
int(b) – will give 5
will cast the data type of the expression as int.
Similarly,
d = float(a)
will assign value 3.0 to d because float(a) cast the expression’s
value to float and then assigned it to d.

str(a) – will give ‘3’


str(5.78) – will give ‘5.78’
str(True) – will give ‘True’
float(‘34’) – will give 34.0
 What would be the output of the following code:
a = 3+5/8
b = int(3+5/8)
c = 3+ float(5/8)
d = 3+ float(5)/8
e = 3+ 5.0/8
f = int(3+5/8.0)
print(a, b, c, d, e, f)
Variable In Python
Variable
Create a Variable:
>>> x = 10
>>> x
10
Assigning a new value:
>>> x = 20
>>> x
20
Multiple assignments
Variable Definition
 In Python, a variable is created when you first assign a value to it. It
also means that a variable is not created until some value is assigned
to it.
 Example:
print(x)
x=20
print(x)
When you run the above code, it will produce an error for the first
statement only – name ‘x’ is not defined.

So, to correct it-


x=0
Print(x)
x=20
Print(x)
 Python Identifiers
1. An identifier is a name given to entities like class, functions, variables, etc.
It helps to differentiate one entity from another.
2. An identifier cannot start with a digit.
3. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9).
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. An identifier can be of any length.
6. Always give the identifiers a name that makes sense. While c=10 is a valid
name, writing count=10 would make more sense, and it would be easier to
figure out what it represents when you look at your code after a long gap.
 Expressions
An expression is any legal combination of symbols that represents a
value. An expression represents something, which Python evaluates
and which then produces a value.
Example: 15, 2.9, a+5, (3+5)/4
Data Types In Python
Data Type:
Python has many data types. Here are the important ones:

• Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions,
or even complex numbers.

• Strings are sequences of characters

• Booleans are either true or false

• Lists are ordered sequence of values.

• Tuples are ordered, immutable sequence of values.


 Numbers
Number data types are used to store numeric values in Python. The numbers in
Python have following core data types:
a) Integers - are whole numbers such as 5,39,1917,0 etc. They have no
fractional parts. Integers can be positive or negative.
b) Booleans – represent the truth values False and True. False and True behave
like the values 0 and 1, respectively. To get the Boolean equivalent of 0 or 1,
you can type bool(0) and bool(1), Python will return False or True
respectively.
String: Data Type
Strings:

Examples:
Try typing without quotes: >>>”It’s a beautiful day !”
What’s the result ? >>> a= “Good Morning”
>>> a
‘Good Morning’
>>> a= ‘Good Morning’
>>>a
‘Good Morning’
Strings Operations:

Concatenation , Replication :
Strings Operations:
Slicing : refers to a part of the string.
Specify the start index and the end index, separated by a colon.
Syntax: string[start:end:step]
Example:
Membership operators
 ‘in’ and ‘not in’ are membership operators.
 ‘in’ – returns true if a character/substring exists in a given string.
 ‘not in’ – returns true if a character/substring does not exist in the
given string.
 Syntax: <substring> in <string>
<substring> not in <string>
Built in String Methods:
 Len() – returns the length of the string.
Syntax: Len(str)
 Capitalize() – first letter is in uppercase
Syntax: str.capitalize()
 Split() – breaks up a string at the specified separator and returns a list of
substrings.
Syntax : str.split( [ separator [, maxsplit ] ] )
** Note : a) If separator is not specified, any white space string is a separator.
b) Default value of maxsplit is 0.
 Lower() – converts all the uppercase letters into lowercase
Syntax: str.lower()
 Upper() - converts all the lowercase letters into uppercase
Syntax: str.upper()
 Replace() – replaces all the occurrences of the old string with the new
string.
Syntax : str.replace(old,new)
Empty String

** if we wish to display the output on the next line, then the use of escape
sequence ‘\n’ becomes mandatory.
 We can also use escape sequence (\t) to tabulate the output.

 Multiline Strings
Traversing a String
 Means accessing all the elements of the string one after the other by
using the subscript or index value.
List: Data Type
Lists:

 Comma – separated values(items) between square brackets.


 Important thing about a list is that items in a list need not be of the same
type.

Example:
List1= [‘physics’,’chemistry’,1997,2000]
List2= [1,2,3,4,5]
Creating lists
 A)

 B) An empty list with function list() :

 C) Creating a list through user input using list() method:


Traversing a List
 Using ‘in’ operator inside for loop:

 Using range() function:


List Operations:

Concatenation , Replication :
List Operations:

Slicing :
Can we have 2 lists working
together ????
List In-Built Functions:
 append() – append a value at the end.
 clear() – clear entire list.
 insert(index value, value) - insert the value at the mentioned index value.
 remove(value) – remove the particular value.
 pop(index no.) – remove the value which is at the mentioned index
number. Without any index value , pop() will remove the last element
which is added.
 del list_name[start: end]
 extend() – add multiple values.
 min(list) – finds minimum value
 max(list) – finds maximum value
 sum(list) – sum of all the numbers of the list.
 sort() – sorts the list ascending by default.
** list.sort(reverse=True|False), reverse=True will sort the
list descending. Default is reverse=False
Tuples: Data Type
Tuples:
Example:
Fruits=(‘Mango’, ’apple’, ’Grapes’)
Tuple named ‘Fruits’ with three elements.
 Main difference between lists and tuples are: Lists are enclosed within
brackets [ ] and their elements and size can be changed, while tuples are
enclosed within parenthesis ( ) and cannot be updated. Tuples can be thought
of as read-only lists.
 When we should be using Tuples ?
When you know that you have a list and you don’t want to change the values
of it and yes, in certain projects we have this requirement. Since, we don’t change
values in a tuple, so, iteration in tuples is faster than a list. So, it enhances the
speed of execution.
Tuple Operations:

Concatenation , Replication :
Tuple Operations:

Slicing :
Change Tuple Values
 Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
 But ,you can convert the tuple into a list, change the list, and convert the
list back into a tuple.
 Example:
Tuple In-Built Functions:
 len() – how many items a tuple has.
 del keyword can delete the tuple completely.
Syntax : del tup
 index() - Search for the first occurrence of the value 8, and
return its position
 count() - Returns the number of times a specified value occurs
in a tuple
Dictionary: Data Type
Dictionary:

Example:
>>> data = {1:’Navin’,2:’kiran’,4:’Harsh’}
1) Dictionaries have a “Key” and a “value of that key”.
2) Dictionaries store huge amount of data.
3) Fetch value in an efficient way.
4) Every value is assigned with a key.
5) Key should be immutable & unique.( can be string or numbers)
 Note: Internally, dictionaries are arranged on the basis of keys.
 Traversing a Dictionary:
Change Values
You can change the value of a specific item by referring to
its key name:
Ways of creating Dictionaries
 To create an empty dictionary, there are two ways:
i) employee = { }
ii) employee = dict{ }
 Specify Key:Value pairs as keyword arguments to dict() function.
employee = dict(name=‘John’, salary = 10000,age=24)
>>>employee
{‘salary’:10000,’age’:24,’name’: ‘John’}
** Python automatically converted argument names to string type
keys.
 Specify comma-separated key:value pairs.
employee = dict({‘name’:‘John’, ‘salary’ : 10000,’age’:24})
>>>employee
{‘salary’:10000,’age’:24,’name’: ‘John’}
• Clear () – empties the dictionary

thisdict.clear()

• Make a copy of a dictionary with the copy() method:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964 }
mydict = thisdict.copy()
print(mydict)

• Values() – return only the values of keys of the


dictionary items.
>>>Emp={‘Name’:’Raman’,’Dept’:’HR’,’Sal’:25000}
>>>print(Emp.values())
Output:
dict_values([‘Raman’,’HR’,25000])
Format() Method
 We can combine strings & numbers by using the format() method.
 It takes the passed arguments then, and places them in the string where the
placeholders { } are.
 It takes unlimited number of arguments.
 You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders.
For loop
 Used for iterating over a sequence (either a list, a tuple, a dictionary , a
set or a string).
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
 Continue statement
we can stop the current iteration of the loop, and continue with the next:
fruits = ["apple", "banana", "cherry"]
for x in fruits:

print(x)

if x== "banana":
continue
Break statement
 We can stop the loop before it has looped through all the items.
fruits = ["apple","banana","cherry"]
for x in fruits:

if x== "banana":
break
** you can write print(x) before break also.
Range() function
 To loop through a set of code a specified number of times we can use the range()
function.
 Range() function a sequence of numbers, starting from 0 by default and increments
by 1, and ends at a specified number.
for x in range(6):
print(x)
 However, it is possible to specify the starting value by adding a parameter: range(2,6)
, which means values from 2 to 0 (but not including 6):
for x in range(2, 6):
print(x)

 Else keyword in a for loop specifies a block of code to be executed when the loop has
ended:
for x in range(2, 6):
print(x)
else:
print(“Finally finished !”)
Nested Loops
adj = ["red", "big", "tasty"]
fruits = ["apple","banana", "cherry"]
for x in adj:
for y in fruits:
print(x,y)

While Loops:
We can execute a set of statements as long as a condition is true.
i=1
while i<6:
print(i)
i+=1
else:
print("i is no larger than 6")
Break & continue statement

i=1 i=0
While i<6: While i<6:
Print(i) i+=1
If i== 3: If i== 3:
Break continue
i+=1 Print(i)
If statement
a=331
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")
Short Hand If
if a>b : print(“a is greater than b”)
Nested If
x= 13
if x>10:
print("above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20")

You might also like