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

Python Notes For Beginners (Autosaved)

Uploaded by

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

Python Notes For Beginners (Autosaved)

Uploaded by

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

Python for Beginners

• 1.Features of python
• 2. Difference between python and pycharm
• 3.Execution Modes(Interactive and Script Mode)
• 4. Python Keywords
• 5. Python Variables(Good variable names and Good variable names
• 6. Four primitive data types in python (Int, float, strings and bool)
• 7.Identifiers
• 8.Data types
• 9.Mathematical operators, Assignment operators and Boolean operators
• 10.Basic programmes
• 11. Lists and operations with lists
• 12. Basic oprations with Matrices.
5.1.1 Features of Python
• Python is a high level language. It is a free and open source language.

• It is an interpreted language, as Python programs are executed by an interpreter.

• Python programs are easy to understand as they have a clearly defined syntax and relatively
simple structure.

• Python is case-sensitive. For example, NUMBER and number are not same in Python.

• Python is portable and platform independent, means it can run on various operating systems
and hardware platforms.

• Python has a rich library of predefined functions.

• Python is also helpful in web development. Many popular web services and applications are
built using Python.

• Python uses indentation for blocks and nested blocks .


1.The difference between Python and PyCharm is as follows123:Python is a
programming language used by developers to create applications.
2.PyCharm is an Integrated Development Environment (IDE) specifically built for the Python
programming language.
3.Python is the language you write in, while PyCharm is the platform where you create
projects.
Difference between pycharm and python
1 、 First of all, their download addresses and installation methods are different;

2 、 Python is a basic compilation environment, just like java and jar. Pycharm is an
integrated development environment, in order to allow you to write code quickly and
facilitate debugging.

3 、 Simply put: Python is an interpreter, and pycharm is an IDE (Integrated Development


Environment) specially built for the Python programming language.
To write Python programs in pycharm, you must eventually have the support of a Python
interpreter, and the two work together.
4 、 It is not possible to download a pycharm separately, but also download a python
interpreter.
5.1.3 Execution Modes
There are two ways to use the Python interpreter:
a) Interactive mode
b) Script mode
Interactive mode allows execution of individual statement instantaneously. Whereas,
Script mode allows us to write more than one instruction in a file
called Python source code file that can be executed.
(A) Interactive Mode
To work in the interactive mode, we can simply type a Python statement on the >>>
prompt directly. As soon as we press enter, the interpreter executes the statement and
displays the result(s), as shown in Figure 5.2.

Figure 5.2: Python interpreter in interactive mode Working in the interactive mode is
convenient for
testing a single line code for instant execution. But in the interactive mode, we cannot
save the statements for future use and we have to retype the statements to run
(B) Script Mode
In the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute it.

Python scripts are saved as files where file name has extension “.py”.
By default, the Python scripts are saved in the Python installation folder.

To execute a script, we can either:


a) Type the file name along with the path at the prompt. For example, if the name of
the file is prog5-1.py, we type prog5-1.py. We can otherwise open the program
directly from IDLE as shown in Figure 5.3.

b) While working in the script mode, after saving the file, click [Run]->[Run Module]
from the menu as shown in Figure 5.4.
5.2 Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter,
and we can use a keyword in our program only for the purpose for which it has been defined. As
Python is case sensitive, keywords must be written exactly as given in Table 5.1.
Python Variable is a container that stores values.
Python is not “statically typed”.
We do not need to declare variables before using them or declare their type. A variable is
created the moment we first assign a value to it.

A Python variable is a name given to a memory location. It is the basic unit of


storage in a program. In this article, we will see how to define a variable in Python.

Example of Variable in Python


An Example of a Variable in Python is a representational name that serves as a pointer to
an object. Once an object is assigned to a variable, it can be referred to by that name. In
layman’s terms, we can say that Variable in Python is containers that store values.
Eg1 x=9 Eg2 y=“Hello” Eg 3 Print(z)

Print(x)=9 Print(y) # Hello # Name Error: Name z is not defined

Note :A variable is associated with a value that cloud be things like a number, a word or even more complex
things.
Note :A variable is associated with a value that colud be things like a number, a word
or even more complex
things.
Here are how we can create variables and assign them a value.

Good variable names


Bad variable names

X=6 min # Reserved key word

Account_id=“3247197307654” 1_variable # can not start with a number

Student_name=“Jack” var_1 # not descriptive

Tax_rate=0.32 student name Incorrect casing

Temp_Fahrenheit =70 proc_ctr # Too abbreiviated

Is_valid=True distance # should have a unit


Eg, Food ordering App
In an online food ordering app, you might want to store information about a specific item like
Its name , price and whether it is vegetarian or not
Item_burger
price_Rs
Is_vegetarian =False
There are four primitive data types in python . These are building blocks to more complex data strucures.
Note: Strings are case sensitive
Int #Integer(whole numbers)
Flaot # numbers with decimals
Str # string(literals, words and texts)
Bool # Boolean values(either True or False)
Boolean values (True and False ) need to be capitalized.
X=5 #int
Y=2.32 #flaot
Name =“Rama” # string(strings are case sensitive)
Likes_coffee=True # bool(Boolean values (True and False need to be capitalized).
For eg, we can add two integers
# Adding integers
Print(2+2)
# Add int with flaot
Print(2+3.5)
We can add two strings , but , it behaves differently
Print(“2”+”2”) #”22”
Strings are characters and have no numerical values. When we add them , it just treats them as
though we have cut letters out of news papers and pasted them together.
5.3 Identifiers
In programming languages, identifiers are names used
to identify a variable, function, or other entities in a
program. The rules for naming an identifier in Python
are as follows:
• The name should begin with an uppercase or a
lowercase alphabet or an underscore sign (_). This
may be followed by any combination of characters
Note: LUN
a–z, A–Z, 0–9 or underscore (_). Thus, an identifier Can contain Letters, Underscores, Numbers
cannot start with a digit.
• It can be of any length. (However, it is preferred to
keep it short and meaningful).
• It should not be a keyword or reserved word given
in Table 5.1.
• We cannot use special symbols like !, @, #, $, %,
etc., in identifiers.
For example, to find the average of marks obtained
by a student in three subjects, we can choose the
identifiers as marks1, marks2, marks3 and avg rather
than a, b, c, or A, B, C.
avg = (marks1 + marks2 + marks3)/3
Similarly, to calculate the area of a rectangle, we can
use identifier names, such as area, length, breadth
Example 5.1
#Variable amount is the total spending on
#grocery
amount = 3400
#totalMarks is sum of marks in all the tests
#of Mathematics
totalMarks = test1 + test2 + finalTest
Program 5-4 Write a Python program to find the sum of

two numbers.

#Program 5-4
#To find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)
Output:
30
5.6 Everything is an Object
Python treats every value or data item whether numeric,
string, or other type (discussed in the next section) as
an object in the sense that it can be assigned to some
variable or can be passed to a function as an argument.
Every object in Python is assigned a unique identity
(ID) which remains the same for the lifetime of that object.
This ID is akin to the memory address of the object. The
function id() returns the identity of an object.
Variables of simple data types like integers, float,
boolean, etc., hold single values. But such variables are
not useful to hold a long list of information, for example,
names of the months in a year, names of students in a
class, names and numbers in a phone book or the list of
artefacts in a museum. For this, Python provides data
types like tuples, lists, dictionaries and sets.
5.7.2 Sequence
A Python sequence is an ordered collection of items,
where each item is indexed by an integer. The three
types of sequence data types available in Python are
Strings, Lists and Tuples. We will learn about each of
them in detail in later chapters. A brief introduction to
these data types is as follows:
(A) String
String is a group of characters. These characters may be
alphabets, digits or special characters including spaces.
String values are enclosed either in single quotation
5.8 Operators
An operator is used to perform specific mathematical
or logical operation on values. The values that the
operators work on are called operands. For example,
in the expression 10 + num, the value 10, and the
variable num are operands and the + (plus) sign is an
operator. Python supports several kinds of operators
whose categorisation is briefly explained in this section.

Python
compares strings
lexicographically, using
ASCII value of the
characters. If the first
character of both the
strings are same, the
second character is
compared, and so on.
Figure 5.10: Variables with different values have different identifiers

Ch 5.indd 99
x=5 x=5
y=7 y=7x=5
print(x==y) print(x==y)
y=7
print(x==y)

X=5…………………………………………….. X=5
y=5
print (x==y) True
Y=7
Print(x==y) OUTPUT….False
s3=x<3
s4=x<1
print(s1 or s2)
print(s3 or s4)
print(s2 or s3)
C:\Users\DELL\PycharmProjects\pythonProject1\.venv\Scripts\python.exe C:\Users\DELL\PycharmProjects\
print(s2 or s4)
pythonProject1\progarm.py True
False
True
x=7
True
y=8
s1 =x>4
s2 =y>3
s3=x<3
s4=x<1
C:\Users\DELL\PycharmProjects\pythonProject1\.venv\Scripts\python.exe C:\Users\DELL\PycharmProjects\pythonProject1\
print(s1 and s2)
progarm.py
True
print(s3 and s4)
False
print(s2 and s3)
False
print(s2 and s4)
False
Program of explicit type conversion
from
um1=10
int to float
C:\Users\DELL\PycharmProjects\pythonProject1\.venv\Scripts\
python.exe C:\Users\DELL\PycharmProjects\pythonProject1\
num2=20 progarm.py
num3=num1+num2 30
print(num3) <class 'int'>
30.0
print(type(num3)) <class 'float'>
num4=float(num1+nu
m2) Process finished with exit code 0

print(num4)
print((type(num4)))
Program of explicit type conversion
from float to int
num1=10.2 C:\Users\DELL\PycharmProjects\pythonProject1\.venv\Scripts\
num2=20.6 python.exe C:\Users\DELL\PycharmProjects\pythonProject1\
num3=num1+num2 progarm.py
print(num3) 30.8
<class 'float'>
print(type(num3))
30
num4=int(num1+num <class 'int'>
2)
print(num4) Process finished with exit code 0
print((type(num4)))
Simple programmes
• Consider the following program
• num1 = input("Enter a number and I'll num1 = input("Enter a number
double
and I'll double it: ")
• it: ")
• num1 = num1 * 2 num1 = num1 * 2
• print(num1) print(num1)
• The program was expected to display double
the value This is because the value returned by the input
function is a string ("2") by default. As a result, in
• of the number received and store in variable statement num1 = num1 * 2, num1 has string value and
num1. So if
* acts as repetition operator which results in output as
• a user enters 2 and expects the program to "22". To get 4 as output, we need to convert the data
display 4 as type of the value entered by the user to integer. Thus,
• the output, the program displays the we modify the program as follows:
following result:
• Enter a number and I'll double it: 2
• 22
• num1 = input("Enter a number and num1 = input("Enter a number and I'll double it:
I'll double it: ") ")
num1 = int(num1)
• num1 = int(num1) #convert string #convert string input to
input to #integer
#integer

• num1 = num1 * 2 num1 = num1 * 2


• print(num1) print(num1)
• Now, the program will display the :\Users\DELL\PycharmProjects\pythonProject1\.venv\Scripts\
python.exe C:\Users\DELL\PycharmProjects\pythonProject1\
expected output balu.py
• as follows: Enter a number and I'll doubleit: 3
6
• Enter a number and I'll double it: 2
•4
How will Python evaluate the following

expression?
5.11 Input and Output
Sometimes, a program needs to interact with the user’s to get some input data or information from the
end user
and process it to give the desired output. In Python, we have the input() function for taking the user
input.
The input() function prompts the user to enter data. It accepts all user input as string. The user may
enter
a number or a string but the input() function treats them as strings only. The syntax for input() is:
input ([Prompt])
Prompt is the string we may like to display on the screen prior to taking the input, and it is optional.
When
a prompt is specified, first it is displayed on the screen after which the user can enter data. The input()
takes
exactly what is typed from the keyboard, converts it into a string and assigns it to the variable on left-
hand side
of the assignment operator (=). Entering data for the input function is terminated by pressing the enter
key.
To find simple intereset using
python
# To calculate simple interest

principal=200
years=5
rate=0.04
new_value=principal*years* rate
print(new_value)
:\Users\DELL\PycharmProjects\pythonProject1\.venv\Scripts\python.exe C:\Users\DELL\PycharmProjects\pythonProject1\
progarm.py
40.0
Compound Interest-Python program

To calculate compound interest


principal=240000
years=2
C:\Users\DELL\PycharmProjects\
annual_rate=2 pythonProject1\.venv\Scripts\
new_value=principal*(1+annual_rate) python.exe C:\Users\DELL\
*years PycharmProjects\pythonProject1\
progarm.py
print(new_value) 1440000
The If statement and the If -
Else statement
• The If statement and the If - Else statement
•  Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular block of
code for a particular decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of decision making. The if
statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of the if statement can be any valid
logical expression which can be either evaluated to true or false.

•  The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition. If the condition is true, then the if-block is
executed. Otherwise, the else-block is executed.
2. Python program to check whether the given
number is even or odd. (can be run)
• n = int(input())
• if(n%2 = = 0):
• print(“Number is an even number‟) n= int(input())
if(n%2==0):
• else: print("Number is an even number")
• print(" Number is an odd number ") else:
• Output: print("Number is an odd number")
• 20 •Note:A colon is used to represent an indented block.
•It is also used to fetch data and index ranges or arrays
• Number is an even number •Another major use of the colon is slicing. In slicing, the
programmer specifies the starting index and the ending
index and separates them using a colon which is the
general syntax of slicing.
•A colon is used to identify the keys in dictionaries.
Python program to check whether the year is leap
year or not
• n = int(input("Enter a umber"))
if(n%4==0):
• print("Leap year") n = int(input("Enter a number"))
if(n%4==0):
• else: print("Leap year")
• print("Not Leap year") else:
76print("Not Leap year")
Lists in python
• The data type list is an ordered sequence which is mutable and made
up of one or more elements.
• Unlike a string which consists of only characters, a list can have
elements of different data types, such as integer, float, string, tuple or
even another list.
• A list is very useful to group together elements of mixed data types.
• Elements of a list are enclosed in square brackets and are separated
by comma.
• Like string indices, list indices also start from 0.
Lists in python
• #list1 is the list of six even numbers
list1 = [2,4,6,8,10,12]
print(list1)
• [2, 4, 6, 8, 10, 12]
• #list2 is the list of vowels
list2 = ['a','e','i','o','u']
print(list2)
• ['a', 'e', 'i', 'o', 'u']
Lists in python
• #list3 is the list of mixed data types
list3 = [100,23.5,'Hello']
• print(list3)
• [100, 23.5, 'Hello']
• #list4 is the list of lists called nested
• #list
• list4 =[['Physics',101],['Chemistry',202],
• ['Maths',303]]
• >>> print(list4)
• [['Physics', 101], ['Chemistry', 202],
• ['Maths', 303]]
Accessing Elements in a List
Operations with lists.
• The elements of a list are accessed in the same way as
• characters are accessed in a string.
# Define a list of lists (2D matrix)
• #initializes a list list1
List1=[1,2,3,4,5,6,7]
• >>> list1 = [2,4,6,8,10,12] List1[0]
• >>> list1[0] #return first element of list1 print(List1[0])
• 2 print(List1[4])
• >>> list1[3] #return fourth element of list1 List2=[]
• 8
• #return error as index is out of range List2.append("Apple")
• >>> list1[15] print(List2)
• IndexError: list index out of range List2.append('Onion')
• #an expression resulting in an integer index print(List2)
• >>> list1[1+4]
• 12
Write python program to read a particular student mark and print the
grade
n=int(input("Enter a
number"))
if(n<25):
print("Fail")
elif (n>=25 and n<=45):
print("Second class")
elif(n>=50 and n<80):
print(("First calss"))
else:
print("distinction")
Python program for basic matrix entries.

A=[[1,4,5,12],[5,7,8,9],
[10,3,0.5]]
print("A",A)
print("A[0]",A[0])
print("A[1][3]",A[1][3])
column=[]
for row in A:
column.append((row[1]))
print("second
column",column)
Python program for basic matrix entries.
A = [ [10, 20, 30],
[40, 50, 60],
[70, 80, 90] ]

# Define an empty list to store the column values


column = []

# Extract the second element from each row and append it to the
column list
for row in A:
column.append(row[1])

# Print the result


print(column)
• print("Hello\nWorld")
• print("Hello\nWorld")
• multiline_string = "This is the first line.\nThis is the second line.\nAnd
this is the third line."
• print(multiline_string)
Examining \n in Python
"What does \n mean in Python" is a common question among beginners. The answer is simple: \n is the newline character. It's used to create a new line within a string literal,
initiating a line break.
Using \n in Python: Examples
Here are examples demonstrating the use of \n for line breaks:
multi_line_string = "This is a line.\nThis is another line."

multiline_str="Hello\nRama\nHow areyou"
print(multiline_str)

Hello
Rama
How areyou
Cramer’s Rule
Solutions of Linear Equations by
Matrix Method
Row Reduced Echelon form

You might also like