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

Python Basics

Python is a high-level, general-purpose, and very popular programming language used in web development, machine learning, and other technologies. The document discusses Python variables, data types, expressions, operators, and other core concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Basics

Python is a high-level, general-purpose, and very popular programming language used in web development, machine learning, and other technologies. The document discusses Python variables, data types, expressions, operators, and other core concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

What is Python?

Python is a high-level, general-purpose, and very popular programming language. Python


programming language (latest Python 3) is being used in web development, Machine Learning
applications, along with all cutting-edge technology in Software Industry.

Variables and Data Structures

In other programming languages like C, C++, and Java, you will need to declare the type of
variables but in Python you don’t need to do that. Just type in the variable and when values
will be given to it, then it will automatically know whether the value given would be an int,
float, or char or even a String.

Rules for Naming Python variables


● It cannot be a reserved python keyword.
● It should not contain white space.
● It can be a combination of A-Z, a-z, 0-9, or underscore.
● It should start with an alphabet character or an underscore ( _ ).
● It should not contain any special character other than an underscore ( _ ).

Python Assign Values to Multiple Variables

Also, Python allows assigning a single value to several variables simultaneously with
“=” operators.
For example:
a = b = c = 10
print(a)
print(b)
print(c)

Python Data Types


Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data.
● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary
● Binary Types

Numeric Data Types in Python


The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number
Sequence Data Type in Python
The sequence Data Type in Python is the ordered collection of similar or different data
types.
● Python String
● Python List
● Python Tuple

String Data Type

Strings in Python are arrays of bytes representing Unicode characters. A string is a


collection of one or more characters put in a single quote, double-quote, or
triple-quote.

List Data Type

Lists are just like arrays, declared in other languages which is an ordered collection
of data. It is very flexible as the items in a list do not need to be of the same type.

Tuple Data Type

Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot
be modified after it is created. It is represented by a tuple class.

Boolean Data Type in Python


Data type with one of the two built-in values, True or False. Boolean objects that are equal
to True are truthy (true), and those equal to False are falsy (false).
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will
throw an error.

Set Data Type in Python


In Python, a Set is an unordered collection of data types that is iterable, mutable, and has
no duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.

Dictionary Data Type in Python


A dictionary in Python is an unordered collection of data values, used to store data values
like a map, unlike other Data Types that hold only a single value as an element, a
Dictionary holds a key: value pair.
What is Python type() Function?
To define the values ​of various data types and check their data types we use the type()
function. Consider the following examples.

Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce
some other value. In any programming language, an expression is evaluated as per the
precedence of its operators. So that if there is more than one operator in an expression,
their precedence decides which operation will be performed first. We have many different
types of expressions in Python.

1. Constant Expressions: These are the expressions that have constant values only.

Example:

x = 15 + 1.3 Output
print(x) 16.3

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values,


operators, and sometimes parenthesis.
x = 40 Output
y = 12 52
add = x + y 28
sub = x - y
print(add)
print(sub)

3. Integral Expressions: These are the kind of expressions that produce only integer
results after all computations and type conversions.
Example: Output
a = 13 25
b = 12.0
c = a + int(b)
print(c)
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.

Example: Output

a = 13 2.6
b = 5
c = a / b
print(c)

5. Relational Expressions: In these types of expressions, arithmetic expressions are


written on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions
are evaluated first, and then compared as per relational operator and produce a boolean
output in the end. These expressions are also called Boolean expressions.

Example: Output

a = 21 True
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)

Multiple operators in expression (Operator Precedence)

It’s a quite simple process to get the result of an expression if there is only one operator in
an expression. But if there is more than one operator in an expression, it may give different
results on basis of the order of operators executed. To sort out these confusions, the
operator precedence is defined. Operator Precedence simply defines the priority of
operators that which operator is to be executed first. Here we see the operator precedence
in Python, where the operator higher in the list has more precedence or priority:

Precedence Name Operator

1 Parenthesis ()[]{}

2 Exponentiation **

3 Unary plus or minus, complement -a , +a , ~a


4 Multiply, Divide, Modulo / * // %

5 Addition & Subtraction + –

6 Shift Operators >> <<

7 Bitwise AND &

8 Bitwise XOR ^

9 Bitwise OR |

10 Comparison Operators >= <= > <

11 Equality Operators == !=

12 Assignment Operators = += -= /= *=

13 Identity and membership operators is, is not, in, not in

14 Logical Operators and, or, not

Example: Output:

a = 10 + 3 * 4 22
print(a)

b = (10 + 3) * 4 52
print(b)

c = 10 + (3 * 4) 22
print(c)

Python Operators
In Python programming, Operators in general are used to perform operations on values
and variables. These are standard symbols used for the purpose of logical and arithmetic
operations. In this article, we will look into different types of Python operators.

● OPERATORS: These are the special symbols. Eg- + , * , /, etc.


● OPERAND: It is the value on which the operator is applied.

Types of Operators in Python


1. Arithmetic Operators

2. Comparison Operators

3. Logical Operators

4. Bitwise Operators

5. Assignment Operators

1) Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations like
addition, subtraction, multiplication, and division.

Operator Description Syntax

Addition: adds two


+ x+y
operands

Subtraction: subtracts
– x–y
two operands

Multiplication:
* x*y
multiplies two operands

Division (float): divides


/ the first operand by the x/y
second

Division (floor): divides


// the first operand by the x // y
second
Modulus: returns the
remainder when the
% x%y
first operand is divided
by the second

Power: Returns first


** x ** y
raised to power second

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

1. P – Parentheses

2. E – Exponentiation

3. M – Multiplication (Multiplication and division have the same precedence)

4. D – Division

5. A – Addition (Addition and subtraction have the same precedence)

6. S – Subtraction

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’. It
adds (‘+’), subtracts (‘-‘), multiplies (‘*’), computes the remainder (‘%’), and raises a to the
power of ‘b (**)’. The results of these operations are printed.
a=9
b=4
add = a + b

sub = a - b

mul = a * b

mod = a % b

p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
2) Comparison Operators in Python
In Python Comparison of Relational operators compares the values. It either returns True or
False according to the condition.

Operator Description Syntax

Greater than: True if the


> left operand is greater x>y
than the right

Less than: True if the left


< operand is less than the x<y
right

Equal to: True if both


== x == y
operands are equal

Not equal to – True if


!= x != y
operands are not equal

Greater than or equal to


True if the left operand is
>= x >= y
greater than or equal to
the right

Less than or equal to True


<= if the left operand is less x <= y
than or equal to the right

= is an assignment operator and == comparison operator.

Let’s see an example of Comparison Operators in Python.


Example: The code compares the values of ‘a’ and ‘b’ using various comparison operators
and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to,
greater than, or equal to, and less than or equal to ‘b’.

3) Logical Operators in Python


Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations.
It is used to combine conditional statements.

Operator Description Syntax

Logical AND: True if


and both the operands are x and y
true

Logical OR: True if


or either of the operands is x or y
true

Logical NOT: True if the


not not x
operand is false

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:


1. Logical not
2. logical and
3. logical or

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:


Example: The code performs logical operations with Boolean values. It checks if both ‘a’
and ‘b’ are true (‘and’), if at least one of them is true (‘or’), and negates the value of ‘a’
using ‘not’. The results are printed accordingly.

4) Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.

Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:


1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR

Here is an example showing how Bitwise Operators in Python work:


Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’.
It performs bitwise AND (&), OR (|), NOT (~), XOR (^), right shift (>>), and left shift (<<)
operations and prints the results. These operations manipulate the binary representations
of the numbers.

5) Assignment Operators in Python


Python Assignment operators are used to assign values to the variables.

Operator Description Syntax

Assign the value of the


right side of the
= x=y+z
expression to the left side
operand

Add AND: Add right-side


operand with left-side
+= a+=b a=a+b
operand and then assign
to left operand

Subtract AND: Subtract


right operand from left
-= a-=b a=a-b
operand and then assign
to left operand

Multiply AND: Multiply


right operand with left
*= a*=b a=a*b
operand and then assign
to left operand

Divide AND: Divide left


operand with right
/= a/=b a=a/b
operand and then assign
to left operand
Modulus AND: Takes
modulus using left and
%= a%=b a=a%b
right operands and assign
the result to left operand

Divide(floor) AND: Divide


left operand with right
//= operand and then assign a//=b a=a//b
the value(floor) to left
operand

Exponent AND: Calculate


exponent(raise power)
**= value using operands and a**=b a=a**b
assign value to left
operand

Performs Bitwise AND on


&= operands and assign a&=b a=a&b
value to left operand

Performs Bitwise OR on
|= operands and assign a|=b a=a|b
value to left operand

Performs Bitwise xOR on


^= operands and assign a^=b a=a^b
value to left operand

Performs Bitwise right


shift on operands and
>>= a>>=b a=a>>b
assign value to left
operand

Performs Bitwise left shift


<<= on operands and assign a <<= b a= a << b
value to left operand

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a
series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’.
The results of each operation are printed, showing the impact of these operations on the
value of ‘b’.
Input and Output in Python
Sometimes a developer might want to take user input at some point in the program. To do
this Python provides an input() function.

Syntax:
input('prompt')

where prompt is an optional string that is displayed on the string at the time of taking
input.

Example 1: Python get user input with a message

name = input("Enter your name: ")

print("Hello, " + name)

Note: Python takes all the input as a string input by default. To convert it to any other data
type we have to convert the input explicitly.

num = int(input("Enter a number: "))


add = num + 1
print(add)
How take inputs for the Sequence Data Types like List, Set, Tuple, etc.
In the case of List and Set the input can be taken from the user in two ways.

1. Taking List/Set elements one by one by using the append()/add() methods.

2. Using map() and list() / set() methods.

Taking List/Set elements one by one

Take the elements of the List/Set one by one and use the append() method in the case of
List, and add() method in the case of a Set, to add the elements to the List / Set.

List = list()
Set = set()
l = int(input("Enter the size of the List : "))
s = int(input("Enter the size of the Set : "))
print("Enter the List elements : ")
for i in range(0, l):
List.append(int(input()))
print("Enter the Set elements : ")
for i in range(0, s):
Set.add(int(input()))
print(List)
print(Set)
Using map() and list() / set() Methods

List = list(map(int, input("Enter List elements : ").split()))


Set = set(map(int, input("Enter the Set elements :").split()))
print(List)
print(Set)

Taking Input for Tuple

We know that tuples are immutable, there are no methods available to add elements to
tuples. To add a new element to a tuple, first type cast the tuple to the list, later append
the element to the list, and again type cast list back to a tuple.

T = (2, 3, 4, 5, 6)
print("Tuple before adding new element")
print(T)
L = list(T)
L.append(int(input("Enter the new element : ")))
T = tuple(L)
print("Tuple After adding the new element")
print(T)
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again.

Python Function Declaration


The syntax to declare a function is:

Types of Functions in Python

There are mainly two types of functions in Python.


● Built-in library function: These are Standard functions in Python that are
available to use.
● User-defined function: We can create our own functions based on our
requirements.

def fun():
print("Welcome to GFG")

Calling a Python Function

After creating a function in Python we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.

def fun():
print("Welcome to GFG")
fun()
Python Function with Parameters

def add(num1 , num2):


num3= num1 + num2

print(num3)

add(2,3)

You might also like