Unit 3 Python Fundamentals

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Getting started with Python

Python is a popular programming language due to its liveliness and pleasant


productivity. It offers programming fun while coding. It was developed by
Guido Van Rossum in February 1991 and further developed by the Python
software foundation. It is a general-purpose programming language. Its
syntax is easy and designed to give importance to the readability of code. It
saves a few lines of codes with easy syntax rules. It is a powerful
programming middle-level language but not so high-level language like C,
C++, Java, etc.

Strengths
1. Easy to use: The syntax of python is very simple to use
compared to other programming languages.
2. Fewer Lines code: It offers few lines of code, a programmer can
write multiple lines of in a single line.
3. Use of interpreter: Python is using an interpreter, not a compiler
that executes code line by line. So it is easy for a beginner.
4. No additional library required: When python is installed, all
basic libraries installed with it. So no need to install any standard
library.
5. Platform Independent: Python can run on any platform such as
Windows, Linux/UNIX, Macintosh etc. Moreover, it can run on
many devices like supercomputers, smartphones. It is a portable
language.
6. Free & Open Source: It’s free of cost and can be downloaded
from www.python.org. It is open-source, so source code may be
available for redistribution.
7. Offers a variety of applications: Nowadays Python is used in
many devices or applications such as Scripting, Web
Development, Gaming, AI, Database Development etc.
Limitations – Getting started with Python
1. Slow execution: Python uses an interpreter that executes code
line by line which is slower in execution compared to a compiler-
based programming language.
2. Less no. of libraries: Python offers limited libraries compared to
other programming languages like C, C++, etc.
3. Not strong for mobile development: It is good for desktop or
server-based applications but not efficient for mobile apps.
4. Memory Consumption: Python offers flexible data types so
there is high memory consumption.
5. Weak in database connectivity: It is not that much strong like
JDBC or ODBC, its database access layer has some barriers.
Now we will discuss how to install python into your computer or laptop
which is first step of Getting started with Python.
Python Installation
Before starting programming with python, it needs to be installed. There are
few distributions of python available like CPython (set of applications such
as python interpreter, Python IDLE and Pip), Anaconda Python distribution
(Comes with preloaded packages and libraries with IDEs like Spider, Jupyter,
PyCharm etc.)
Download python from www.python.org for windows suitable executable
installer. The latest version of python is 3.8.3.
Please refer to this documentation for installation steps: Documentation
After installation, you need to understand python interpreter which is mostly
used to interpret your code in Getting started with Python.
Python interpreter
Python interpreter offers two modes for coding:
1. in Interactive mode
2. in Script mode
Working in Interactive Mode
Interactive mode allows one to type one statement and executes the same line
when the enter key is pressed. To start working in interactive mode follow
these steps:
Step1. Click on Start → All Programs → Python 3.7 →IDLE (Python 3.7 64-

bit). A python Shell window will appear


as shown in the below-given screen:

After typing a line or statement press enter, the interpreter will execute the
line and gives the result:

Working in Script Mode


Working in script mode is an essential part when you are Getting started with
Python.
To work in script mode follow these steps:
Step 1. Click on Start → All Programs → Python 3.7 →IDLE (Python 3.7
64-bit). A python shell will appear.
Step 2. Click File New. A new window will appear with the title “untitled”.
Step 3. Type the statement(s).

Step 4. Click on Run → Run Module or press F5 key.


Step 5. It prompts to save the module. Save the file with .py extension.

Step 6. The python shell display output like this:

After the understanding of print() function let’s move ahead with Getting
started with Python tokens.
Tokens – Getting started with python
Tokens are the least units of programs. These tokens are as following:
1. Identifiers
2. Keywords
3. Literals
4. Operators
5. Puncutators
Identifiers
Identifiers are names used in programs to identify small units of programs
such as variables, objects, classes, functions etc.
Identifiers defined by the following few rules as follows:
1. It must start alphabets
2. It can be a combination of numbers and letters
3. Special characters are not allowed in identifiers name
4. Spaces are not allowed in identifier names, underscore can be
used to separate two words
5. The meaning of Upper Case and Lower Case different should not
use as identifier names
6. Few Examples:
7. MyData, roll_no, year1 etc.
Keywords
Keywords are python reserved words used in a program. Each and every
keyword conveys special meaning to the python interpreter.
Ex.: def, False, if, elif, else, for etc.
Literals(Constants)
Literals or Constants means that an item(s) have a fixed value. There are
several types of constants or literals as follows:
1. String Literals: Ex.: ‘a’, ‘abc’, ‘my_name’, ‘t’, ‘n’ etc.
2. Numeric Literals: int, float, complex etc.
3. Boolean Literals: True or False
4. Special Literals: None
Operators – getting started with python
Operators are symbols or words used to perform the simple calculation or
logical comparison in statement or expression. Python supports these
operators:
1. Unary Operators: It requires one operand Ex.: + (Positive), –
(Negative), ~ (Bit wise complement), not (Logical Negation)
2. Binary Operators: It requires more than one operators. They are
as follows:
3. Arithmetic Operators: + (Addition), – (Subtraction), *
(Multiplication), / (Division), % (Modulus/Remainder), **
(Power), // (Floor division)
4. Bitwise operator: & (AND), ^ (XOR), I (OR)
5. Shift Operator: << (Shift left), >> (Shift Right)
6. Identity Operators: is, is not (compare similar identity )
7. Relational Operators: < (less than), > (greater than), <= (less
than or equal to), >= (greater than or equal to), == (equal to), !=
(not equal to)
8. Logical Operators: and (Logical AND), or (Logical OR)
9. Assignment Operators: =, /=, +=, -=, *=, /=, %=, **=, //=
10. Membership Operators: in, not in (use to check the
variable is in sequence or not)
These tokens are very important for each program of python. So when yo

Introduction to Python fundamentals


A program has important parts such as variables, statements, expressions,
data types, input and output related functions, etc. In this post, you will learn
about python programming fundamentals.
Expressions
A small set of variables, operators, and value is known as expression. It seems like
every line of a program can be an expression.

input() function
This function is used accept value from user. Let’s look in the following:

After understanding how to take input from the user for Python fundamentals
class 11 notes understand how you can print the output.
print() function
As I have used print() function in the above codes. It allows generating output on the
screen. The syntax of the print() function is as follows:
print(“text”,[sep=’ ‘ or end=’character’])
Basically python print() a new line when the print function is used in the program.

Sometimes users want to end a line with some specific characters. In this case, the ‘end’ option is
used, have a look:
Now you are familiar with how to accept input and print the output. The next
section of Python fundamentals class 11 notes talk about variables.
Variables
Variables are storage names with specific data types, used to store a value for
use in the future. It holds a value of any type such as numeric values, letters,
or any other value. The value of the variable can be changed at execution
time by the user and it keeps changing as per the need of the program.
A variable needs to declare first then it will assign a value or use in input
statement and finally hold output or final result. The value of a variable
manipulates any time in a program.
When you are going to declare any variable you need to learn about the rules
to define them. The next section talk of Python fundamentals class 11 notes
talks about the same.
Rules for variable naming
Variables are similar to identifiers. Follow the identifiers naming rules while
declaring variables.
Their rules are as following:
• It must start with an alphabet
• It doesn’t contain any space or special character or symbols
• A keyword should not be used as variables
• It should be short and simple
Read about print() function
Now let’s look at this code:

In the first code variable, a is assigned value 5. In python, when the value is
assigned to the variable, the data type of a variable is determined by python
itself. So here 5 is an integer. In the second code variable, a is declared with
value 5, then value 10 is added in a and then displayed using print() function.
In the last code, two different values assigned to two different variables a and
b, 5 and 10 respectively, then added both of them along with print()
functions.
There are three main properties associated with a variable:

1. Address: Memory location address in the memory cell. To know the


address of memory location python offers id() function, that accepts a
variable name as parameter.
Displaying memory address through id() function

2. Value: Assigned by the programmer or changed by the statements in a


program.
3. Datatype: The type of data such as number, letters or string, etc. To print
datatype of a variable, python offers type() function.

Displaying data type of variable


The next section of Python fundamentals class 11 notes talks about data types
in python.
Datatypes in python
Python DataTypes

Numbers: It holds numeric values in a program. Python allows following


built-in data types for numbers:
Integer: A Numeric value without decimal places is considered as an integer.
The inbuilt class ‘int’ represent these type of numbers. Integers can be of any
length in python. Ex. : 12345, -45465, 234, -456, 10, 0
Float: Real numbers having decimal or floating points are considered are
float. Ex.: 567.90, 234.90, 3456.898989 etc. Python prints a large value post
decimal places by default. Have a look on the following code:

Using float in program


To print desired digits in decimal value post point/dot, use str.format()
function. Suppose I want to print 2 decimal place value post point/dot in the
above result, I have done in the following manner:

Result in two decimal places value after a point

Complex Number: It has two parts: i) Real Number and ii) Imaginary Part.
It is available in the form of ‘x + yJ’ or ‘x + yj’, where x is a float number
(real number), yJ is the imaginary part, small letter j indicates the square root
of an imaginary number -1. Example:

Use of complex number in python


None: None is a special data type of python. When no other data type is
required to accepted then None is given as a value. It displays nothing when a
variable is assigned to None.
After this in python fundamentals class 11 notes, the following data types can
be used.
Sequence: It accepts values as in a sequence or specific patters. Python offers
the following sequence data types:
str (String): It is a sequence of characters that is a combination of letters,
numbers, and special symbols. A string is enclosed with a quotation. It can be
enclosed with single, double, or triple quotes. Single line text is enclosed
either with single or double quotes whereas multi-line text is enclosed with
triple quotes.
For python fundamentals class 11 notes you must aware of the character
sequence.
Python also offers a special escape character sequence to print some non-
graphic character as following:

Escape character sequence in Python


Boolean: Boolean holds either True or False value. Any statement that has
either True or False result, has a boolean data type.
What is Python Sequence?
So, what is a Python sequence, and how does it differ from a Python
collection?

A sequence is a group of items with a deterministic ordering. The order in


which we put them in is the order in which we get an item out from them.

Python offers six types of sequences. Let’s discuss them.

1. Python Strings
A string is a group of characters. Since Python has no provision for arrays, we
simply use strings. This is how we declare a string:

Python Sequence or Collection

We can use a pair of single or double quotes. And like we’ve always said,
Python is dynamically-typed. Every string object is of the type ‘str’.

>>> type(name)

Output
<class ‘str’>

To declare an empty string, we may use the function str():

>>> name=str()

>>> name

Output

>>> name=str('Ayushi')

>>> name
Output
‘Ayushi’

>>> name[3]

Output
‘s’

2. Python Lists
Since Python does not have arrays, it has lists. A list is an ordered group of
items. To declare it, we use square brackets.

>>> groceries=['milk','bread','eggs']

>>> groceries[1]

Output
‘bread’

>>> groceries[:2]

Output
[‘milk’, ‘bread’]

A Python list can hold all kinds of items; this is what makes it heterogenous.

>>> mylist=[1,'2',3.0,False]

Also, a list is mutable. This means we can change a value.

>>> groceries[0]='cheese'

>>> groceries

Output
[‘cheese’, ‘bread’, ‘eggs’]

A list may also contain functions.


>>> groceries[0]='cheese'

>>> groceries

Output
print(“Hi”)

>>> newlist=[sayhi,sayhi]

>>> newlist[0]

Output
<function sayhi at 0x05907300>

>>> newlist[0]()

Output
Hi

3. Python Tuples
A tuple, in effect, is an immutable group of items. When we say immutable, we
mean we cannot change a single value once we declare it.

>>> name=('Ayushi','Sharma')

>>> type(name)

Output
<class ‘tuple’>

We can also use the function tuple().

>>> name=tuple(['Ayushi','Sharma'])

>>> name

Output
(‘Ayushi’, ‘Sharma’)
Like we said, a tuple is immutable. Let’s try changing a value.

>>> name[0]='Avery'

Output
Traceback (most recent call last):File “<pyshell#594>”, line 1, in <module>

name[0]=’Avery’

TypeError: ‘tuple’ object does not supp

Dictionaries
Dictionaries are also like lists, and they are mutable -- you can add, change, and remove elements
from a dictionary. However, the elements in a dictionary are not bound to numbers, the way a list is.
Every element in a dictionary has two parts: a key, and a value. Calling a key of a dictionary returns
the value linked to that key. You could consider a list to be a special kind of dictionary, in which the
key of every element is a number, in numerical order.
Dictionaries are declared using curly braces, and each element is declared first by its key, then a
colon, and then its value. For example:

>>> definitions = {"guava": "a tropical fruit", "python": "a programming


language", "the answer": 42}
>>> definitions
{'python': 'a programming language', 'the answer': 42, 'guava': 'a tropical
fruit'}
>>> definitions["the answer"]
42
>>> definitions["guava"]
'a tropical fruit'
>>> len(definitions)
3

Also, adding an element to a dictionary is much simpler: simply declare it as you would a variable.

>>> definitions["new key"] = "new value"


>>> definitions
{'python': 'a programming language', 'the answer': 42, 'guava': 'a tropical
fruit', 'new key': 'new value'}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy