0% found this document useful (0 votes)
5 views53 pages

Python Unit 1

This document provides an introduction to Python, covering its history, application areas, and fundamental programming concepts such as data types, operators, and program structure. It highlights Python's versatility in fields like web development, game development, machine learning, and data science, along with its syntax rules, including indentation and comments. Additionally, it explains tokens, operators, and various types of literals used in Python programming.

Uploaded by

rmeshak2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views53 pages

Python Unit 1

This document provides an introduction to Python, covering its history, application areas, and fundamental programming concepts such as data types, operators, and program structure. It highlights Python's versatility in fields like web development, game development, machine learning, and data science, along with its syntax rules, including indentation and comments. Additionally, it explains tokens, operators, and various types of literals used in Python programming.

Uploaded by

rmeshak2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-I

Introduction: History and Application areas of Python; Structure of Python Program;


Identifiers and Keywords; Operators and Precedence; Basic Data Types and type
conversion; Statements and expressions; Input/Output statements. Strings: Creating and
Storing Strings, Built-in functions for strings; string operators, String slicing and joining;
Formatting Strings.

History of python:
Python is a widely used general-purpose, high-level programming language.
It was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation.
It was mainly developed to emphasize code readability, and its syntax allows programmers to
express concepts in fewer lines of code.

In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to [Link].

Python can be used on a server to create web applications.

Application Of Python:

Python Applications Python is known for its general-purpose nature that makes it applicable in
almost every domain of software development. Python makes its presence in every emerging
field. It is the fastest-growing programming language and can develop any application. Some of
the globally known applications such as YouTube, BitTorrent, DropBox, etc. use Python to
achieve their functionality. Let us see some of the areas where Python excels in application
development.

Web Development
We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, etc. Some of the most well-known
frameworks that Python use to create these applications are Django, Flask, Pyramid, etc

Game Development

Python is also used in the development of interactive games. There are libraries such as PySoy
which is a 3D game engine supporting Python 3, PyGame which provides functionality and a
library for game development. Games such as Civilization-IV, Disney’s Toontown Online, Vega
Strike etc. have been built using Python.

Web Scraping Applications

Python can be used to pull a large amount of data from websites which can then be helpful in
various real-world processes such as price comparison, job listings, research and development

1
and much more. Python has libraries such as BeautifulSoup, LXML, MechanicalSoup, Python
Requests, Scrapy, etc which can be used to pull such data and be used accordingly.

Machine Learning and Artificial Intelligence

This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations. Some of popularly used libraries are Numpy, Pandas, Scipy, Scikit-learn,
etc.

Data Science and Data Visualization

Data is money if you know how to extract relevant information which can help you take
calculated risks and increase profits. You study the data you have, perform operations and extract
the information required. Libraries such as Pandas, NumPy help you in extracting information.
You can even visualize the data using libraries such as Matplotlib, Seaborn, which are helpful in
plotting graphs and much more.

Audio and Video Applications

Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Video and audio applications such as TimPlayer, Cplay have been developed using Python
libraries and they provide better stability and performance compared to other media players. Few
multimedia libraries are Gstreamer, Pyglet, QT Phonon, etc.

Business Applications

Business Applications are different from normal applications covering domains such as e-
commerce, ERP and many more. They require applications which are scalable, extensible and
easily readable and Python provides us with all these features. Some real-time applications are
Odoo (formerly OpenERP), Tryton, Picalo, etc.

3D CAD and CAM Applications:

CAD (Computer aided design) and CAM (computer aided manufacturing) is a term that refers to
computer systems that are used to both design and manufacture products. CAD is used to
develop the 3D representation of a part of a system. Python supports a wide range of
functionalities for 3D CAD & CAM application such as FreeCAD, Fandango, CAMVOX,
HeeksCNC, AnyCAD, HeeksPython, PythonOCC, PythonCAD, Blender, Vintech RCAM, etc.

Embedded Applications

2
Python is based on C which means that it can be used to create Embedded C software for
embedded applications. This helps us to perform higher-level applications on smaller devices
which can compute Python. The most wellknown embedded application could be the Raspberry
Pi which uses Python for its computing. It can be used as a computer or like a simple embedded
board to perform high-level computations.

Structuring Python Programs

Python Statements In general, the interpreter reads and executes the statements line by line i.e
sequentially. Though, there are some statements that can alter this behavior like conditional
statements.
Mostly, python statements are written in such a format that one statement is only written
in a single line. The interpreter considers the ‘new line character’ as the terminator of one
instruction. But, writing multiple statements per line is also possible that you can find below.
Examples:

print('Welcome to Geeks for Geeks')

Output:
Welcome to Geeks for Geeks

Multiple Statements per Line We can also write multiple statements per line, but it is not a
good practice as it reduces the readability of the code. Try to avoid writing multiple statements in
a single line. But, still you can write multiple lines by terminating one statement with the help of
‘;’. ‘;’ is used as the terminator of one statement in this case.
For Example, consider the following code.

# Example

a = 10; b = 20; c = b + a

print(a); print(b); print(c)

Output:
10
20
30

3
Python Indentation:

Most of the programming languages like C, C++, and Java use braces { } to define a block of
code. Python, however, uses indentation.

A code block (body of a function, loop, etc.) starts with indentation and ends with the first un
indented line. The amount of indentation is up to you, but it must be consistent throughout that
block. Generally, four whitespaces are used for indentation and are preferred over tabs.

Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results in
Python programs that look similar and consistent. Incorrect indentation will result in
IndentationError.

Comments in Python
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing code.
Single Line Comment

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the end of the line are part of the comment and the Python interpreter ignores them.

# First comment

print "Hello, Python!"

Multi-line Comment

Python does not really have syntax for multi line comments. To add a multiline comment you
could insert a

# for each line:

# This is a comment.

# This is a comment, too.

4
# This is a comment, too.

# I said that already.

Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are generally
used for multi-line strings. But they can be used as a multi-line comment as well. Following
triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comments ''' This is a multiline comment. ''

Character set
A character set is a set of valid characters acceptable by a programming language in scripting.
In this case, we are talking about the Python programming language.
the Python character set is a valid set of characters recognized by the Python language. These
are the characters we can use during writing a script in Python.
Alphabets: All capital (A-Z) and small (a-z) alphabets.
 Digits: All digits 0-9.
 Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ `
&*()_+–={}[]\.
 White Spaces: White spaces like tab space, blank space, newline, and carriage return.
 Other: All ASCII and UNICODE characters are supported by Python that constitutes the
Python character set.

Tokens
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens. The various tokens in python are :
1. Keywords: Keywords are words that have some special meaning or significance in a
programming language. They can’t be used as variable names, function names, or any
other random purpose. They are used for their special features.
In Python we have 33 keywords some of them are: try, False, True, class, break,
continue, and, as, assert, while, for, in, raise, except, or, not, if, elif, print, import, etc.

2. Identifiers: Identifiers are the names given to any variable, function, class, list,
methods, etc. for their identification. Python is a case-sensitive language and it has
some rules and regulations to name an identifier.

Here are some rules to name an identifier:-


 As stated above, Python is case-sensitive. So case matters in naming identifiers. And
hence geeks and Geeks are two different identifiers.
 Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It can’t
start with any other character.
 Except for letters and underscore, digits can also be a part of identifier but can’t be the first
character of it.
 Any other special characters or whitespaces are strictly prohibited in an identifier.

5
 An identifier can’t be a keyword.

For Example: Some valid identifiers are gfg, GeeksforGeeks, _geek, mega12, etc.

While 91road, #tweet, i am, etc. are not valid identifiers.

3. Literals or Values: Literals are the fixed values or data items used in a source code. Python
supports different types of literals such as:

(i) String Literals: The text written in single, double, or triple quotes represents the string
literals in Python. For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes
to write multi-line strings.

# String Literals
a ='Hello'
b ="Geeks"
c ='''Geeks for Geeks is a
learning platform'''

# Driver code
print(a)
print(b)
print(c)
Output
Hello
Geeks
Geeks for Geeks is a
learning platform
(ii) Character Literals: Character literal is also a string literal type in which the character is
enclosed in single or double-quotes.
 Python3
# Character Literals
a ='G'
b ="W"

# Driver code
print(a)
print(b)
Output:
G
W

6
(iii) Numeric Literals: These are the literals written in form of numbers. Python supports the
following numerical literals:
 Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t
include fractional parts. It can also include binary, decimal, octal, hexadecimal literal.
 Float Literal: It includes both positive and negative real numbers. It also includes
fractional parts.
 Complex Literal: It includes a+bi numeral, here a represents the real part and b represents
the complex part.
 Python3
# Numeric Literals
a =5
b =10.3
c =-17

# Driver code
print(a)
print(b)
print(c)
Output
5
10.3
-17
(iv) Boolean Literals: Boolean literals have only two values in Python. These are True and
False.
 Python3
# Boolean Literals
a =3
b =(a ==3)
c =True+10

# Driver code
print(a, b, c)
Output
3 True 11
(v) Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no
values, or the absence of value.
 Python3

# Special Literals

7
var =None

print(var)
Output
None
(vi) Literals Collections: Literals collections in python includes list, tuple, dictionary, and
sets.
1. List: It is a list of elements represented in square brackets with commas in between. These
variables can be of any data type and can be changed as well.
2. Tuple: It is also a list of comma-separated elements or values in round brackets. The values
can be of any data type but can’t be changed.
3. Dictionary: It is the unordered set of key-value pairs.
4. Set: It is the unordered collection of elements in curly braces ‘{}’.
 Python3
# Literals collections
# List
my_list =[23, "geek", 1.2, 'data']

# Tuple
my_tuple =(1, 2, 3, 'hello')

# Dictionary
my_dict ={1:'one', 2:'two', 3:'three'}

# Set
my_set ={1, 2, 3, 4}

# Driver code
print(my_list)
print(my_tuple)
print(my_dict)
print(my_set)
Output
[23, 'geek', 1.2, 'data']
(1, 2, 3, 'hello')
{1: 'one', 2: 'two', 3: 'three'}
{1, 2, 3, 4}
4. Operators: These are the tokens responsible to perform an operation in an expression. The
variables on which operation is applied are called operands. Operators can be unary or binary.
Unary operators are the ones acting on a single operand like complement operator, etc. While
binary operators need two operands to operate.

8
 Python3
# Operators
a =12
# Unary operator
b =~ a
# Binary operator
c =a+b

# Driver code
print(b)
print(c)
Output
-13
-1
5. Punctuators:

These are the symbols that used in Python to organize the structures, statements, and
expressions. Some of the Punctuators are: [ ] { } ( ) @ -= += *= //= **== = , etc.

OPERATORS:

In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for 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
6. Identity Operators and Membership Operators

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers
was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

9
Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

Multiplication: multiplies two


* x*y
operands

Division (float): divides the first


/ x/y
operand by the second

Division (floor): divides the first


// x // y
operand by the second

Modulus: returns the remainder when


% the first operand is divided by the x%y
second

Power: Returns first raised to power


** x ** y
second

Example of Arithmetic Operators in Python


Division Operators
In Python programming language Division Operators allow you to divide two numbers and
return a quotient, i.e., the first number or number at the left is divided by the second number or
number at the right and returns the quotient.
There are two types of division operators:
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers. For example:
Example: The code performs division operations and prints the results. It demonstrates that both
integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’,
and ‘-10/2’ results in ‘-5.0’.
[GFGTABS] Python
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
[/GFGTABS]
Output:
10
1.0
5.0
-5.0
10.0

Integer division( Floor division)


The quotient returned by this operator is dependent on the argument being passed. If any of the
numbers is float, it returns output in float. It is also known as Floor division because, if any
number is negative, then the output will be floored. For example:
Example: The code demonstrates integer (floor) division operations using the // in Python
operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-5//2’ equals ‘-3’,
‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division returns the largest integer less
than or equal to the division result.
[GFGTABS] Pythons
print(10//3)
print(-5//2)
print(5.0//2)
print(-5.0//2)
[/GFGTABS]
Output:
3
-3
2.0
-3.0

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
The modulus of Python operators helps us extract the last digit/s of a number. For example:
 x % 10 -> yields the last digit
 x % 100 -> yield last two digits
Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power
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.
[GFGTABS] Python
a=9
b=4
add=a+b

sub=a-b

11
mul=a*b

mod=a%b

p=a**b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
[/GFGTABS]
Output:
13
5
36
1
6561

Note: Refer to Differences between / and // for some interesting facts about these two Python
operators.
Comparison of Python Operators
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 than the x>y
right

Less than: True if the left


< x<y
operand is less than the 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 greater x >= y
than or equal to the right

12
Operator Description Syntax

Less than or equal to True if


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

= is an assignment operator and == comparison operator.


Precedence of Comparison Operators in Python
In Python, the comparison operators have lower precedence than the arithmetic operators. All the
operators within comparison operators have the same precedence order.
Example of Comparison Operators in Python
Let’s see an example of Comparison Operators in Python.
Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python
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’.
[GFGTABS] Python
a=13
b=33

print(a>b)
print(a<b)
print(a==b)
print(a!=b)
print(a>=b)
print(a<=b)
[/GFGTABS]
Output
False
True
False
True
False
True

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 both


and x and y
the operands are true

13
Operator Description Syntax

Logical OR: True if either of


or x or y
the operands is 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.
[GFGTABS] Python
a=True
b=False
print(aandb)
print(aorb)
print(nota)
[/GFGTABS]
Output
False
True
False

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

14
Operator Description Syntax

^ 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
Bitwise Operators in Python
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.
[GFGTABS] Python
a=10
b=4
print(a&b)
print(a|b)
print(~a)
print(a^b)
print(a>>2)
print(a<<2)
[/GFGTABS]
Output
0
14
-11
14
2
40

Assignment Operators in Python


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

15
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


%= right operands and assign the result to left a%=b a=a%b
operand

Divide(floor) AND: Divide left operand with


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

Exponent AND: Calculate exponent(raise power)


**= value using operands and assign value to left a**=b a=a**b
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

16
Operator Description Syntax

assign value to left operand

Performs Bitwise left shift on operands and


<<= a <<= b a= a << b
assign value to left operand

Assignment Operators in Python


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’.
[GFGTABS] Python
a=10
b=a
print(b)
b+=a
print(b)
b-=a
print(b)
b*=a
print(b)
b<<=a
print(b)
[/GFGTABS]
Output
10
20
10
100
102400

Identity Operators in Python


In Python, is and is not are the identity operators both are used to check if two values are located
on the same part of the memory. Two variables that are equal do not imply that they are
identical.
is True if the operands are identical
is not True if the operands are not identical

Example Identity Operators in Python


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

17
Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not
the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same
object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’).
[GFGTABS] Python
a=10
b=20
c=a

print(aisnotb)
print(aisc)
[/GFGTABS]
Output
True
True

Membership Operators in Python


In Python, in and not in are the membership operators that are used to test whether a value or
variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

Examples of Membership Operators in Python


The following code shows how to implement Membership Operators in Python:
Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or
not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the
printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.
[GFGTABS] Python
x=24
y=20
list=[10,20,30,40,50]

if(xnotinlist):
print("x is NOT present in given list")
else:
print("x is present in given list")

if(yinlist):
print("y is present in given list")
else:
print("y is NOT present in given list")
[/GFGTABS]
Output
x is NOT present in given list
y is present in given list

18
Ternary Operator in Python
in Python, Ternary operators also known as conditional expressions are operators that evaluate
something based on a condition being true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the
code compact.

Syntax : [on_true] if [expression] else [on_false]


Examples of Ternary Operator in Python
The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a
conditional assignment to determine the smaller of the two values and assigns it to the
variable ‘min’. Finally, it prints the value of ‘min’, which is 10 in this case.
[GFGTABS] Python
a,b=10,20
min=a if (a<b) else b

print(min)
[/GFGTABS]
Output:
10

Precedence and Associativity of Operators in Python


In Python, Operator precedence and associativity determine the priorities of the operator.
Operator Precedence in Python
This is used in an expression with more than one operator with different precedence to determine
which operation to perform first.
Let’s see an example of how Operator Precedence in Python works:
Example: The code first calculates and prints the value of the expression 10 + 20 * 30, which is
610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the
name is “Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”
[GFGTABS] Python
expr=10+20*30
print(expr)
name="Alex"
age=0

ifname=="Alex"orname=="John"andage>=2:
print("Hello! Welcome.")
else:
print("Good Bye!!")
[/GFGTABS]
Output
610
Hello! Welcome.

19
Precedence and Associativity of Operators in Python
Precedence of Python Operators
The combination of values, variables, operators, and function calls is termed as an expression.
The Python interpreter can evaluate a valid expression.
For example:

>>>5 - 7
-2

Here 5 - 7 is an expression. There can be more than one operator in an expression.


To evaluate these types of expressions there is a rule of precedence in Python. It guides the order
in which these operations are carried out.
For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence


# than subtraction
>>>10 - 4 * 2
2

But we can change this order using parentheses () as it has higher precedence than
multiplication.

# Parentheses () has higher precedence


>>>(10 - 4) * 2
12

The operator precedence in Python is listed in the following table. It is in descending order
(upper group has higher precedence than the lower ones).
Operators Meaning

() Parentheses

** Exponent

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

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

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <,


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

not Logical NOT

and Logical AND

or Logical OR

Type Conversion in Python


Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming. This article is
aimed at providing information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Python Implicit Type Conversion
2. Python Explicit Type Conversion
Type Conversion in Python
The act of changing an object’s data type is known as type conversion. The Python
interpreter automatically performs Implicit Type Conversion. Python prevents
Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit

21
type conversion, sometimes referred to as type casting. When type casting, data
loss could happen if the object is forced to conform to a particular data type.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement. To
get a more clear view of the topic see the below examples.
Example
As we can see the data type of ‘z’ got automatically changed to the “float” type
while one variable x is of integer type while the other variable y is of float type.
The reason for the float value not being converted into an integer instead is due to
type promotion that allows performing operations by converting data into a wider-
sized data type without any loss of information. This is a simple case of Implicit
type conversion in Python.
 Python3
x =10

y =10.6
z =x +y
print(z)

Output
20.6
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of data
loss since we are forcing an expression to be changed in some specific data type.
Various forms of explicit type conversion are explained below:
Converting integer to float
int(a, base)

This function converts any data type to an integer. ‘Base’ specifies the base in
which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-
point number.
 Python3

22
# printing string converting to float
a=5
b=10
c=a+b
print( c )
e =float(c)
print(e)
Output:
15
15.0

Expressions in Python:
An expression is a combination of values, variables, operators, and calls to functions.
Expressions need to be evaluated. If you ask Python to print an expression, the
interpreter evaluates the expression and displays the result.

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. Let’s discuss all types along with
some exemplar codes :
1. Constant Expressions: These are the expressions that have constant values only.
Example:
 Python3

# Constant Expressions

x =15+1.3

print(x)

Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis. The result of this type of expression is also a numeric

23
value. The operators used in these expressions are arithmetic operators like addition,
subtraction, etc. Here are some arithmetic operators in Python:

Operators Syntax Functioning

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation

Example:
Let’s see an exemplar code of arithmetic expressions in Python :
 Python3

# Arithmetic Expressions

x =40

y =12

add =x +y

sub =x -y

pro =x *y

div =x /y

24
print(add)

print(sub)

print(pro)

print(div)

Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.
Example:
 Python3

# Integral Expressions

a =13

b =12.0

c =a +int(b)

print(c)

Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
 Python3

25
# Floating Expressions

a =13

b =5

c =a /b

print(c)

Output
2.6
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:
 Python3

# Relational Expressions

a =21

b =13

c =40

d =37

p =(a +b) >=(c -d)

print(p)

Output
True

26
6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal
to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also
come across some logical operators which can be seen in logical expressions most often. Here
are some logical operators in Python:

Operator Syntax Functioning

P and
and It returns true if both P and Q are true otherwise returns false
Q

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false

Example:
Let’s have a look at an exemplar code :
 Python3

P =(10==9)

Q =(7> 5)

# Logical Expressions

R =P andQ

S =P orQ

T =notP

print(R)

print(S)

27
print(T)

Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
 Python3

# Bitwise Expressions

a =12

x =a >> 2

y =a << 1

0010

print(x, y)

Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single
expression, and that will be termed as combinational expressions.
Example:
 Python3

# Combinational Expressions
a =16
b =12

c =a +(b >> 1)
print(c)

Output
22

28
But when we combine different types of expressions or use multiple operators in
a single expression, operator precedence comes into play.

Statement:

A statement is an instruction that the Python interpreter can execute. We have


only seen the assignment statement so far. Some other kinds of statements that
we’ll see shortly are while statements, for statements, if statements,
and import statements. (There are other kinds too!)
Example:
y = 3.14
x = len("hello")
print(x)
print(y)

Python Basic Input and Output

Python Output

In Python, we can simply use the print() function to print output. For example,
print('Python is powerful')

# Output: Python is powerful


Run Code

Here, the print() function displays the string enclosed inside the single quotation.
Syntax of print()
In the above code, the print() function is taking a single parameter.
However, the actual syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)

Here,

29
 object - value(s) to be printed
 sep (optional) - allows us to separate multiple objects inside print().
 end (optional) - allows us to add add specific values like new line "\n", tab "\t"
 file (optional) - where the values are printed. It's default value is [Link] (screen)
 flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

Example 1: Python Print Statement

print('Good Morning!')
print('It is rainy today')
Run Code

Output

Good Morning!
It is rainy today

In the above example, the print() statement only includes the object to be printed. Here, the
value for end is not used. Hence, it takes the default value '\n'.
So we get the output in two different lines.

Example 2: Python print() with end Parameter

# print with end whitespace


print('Good Morning!', end= ' ')

print('It is rainy today')

30
Run Code

Output

Good Morning! It is rainy today

Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.

Example 3: Python print() with sep parameter

print('New Year', 2023, 'See you soon!', sep= '. ')


Run Code

Output

New Year. 2023. See you soon!

In the above example, the print() statement includes multiple items separated by a comma.
Notice that we have used the optional parameter sep= ". " inside the print() statement.
Hence, the output includes items separated by . not comma.

Example: Print Python Variables and Literals

We can also use the print() function to print Python variables. For example,
number = -10.6

31
name = "Programiz"

# print literals
print(5)

# print variables
print(number)
print(name)
Run Code

Output

5
-10.6
Programiz

Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by
using the [Link]() method. For example,
x=5
y = 10

print('The value of x is {} and y is {}'.format(x,y))


Run Code

Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
To learn more about formatting the output, visit Python String format().

32
Python Input

While programming, we might want to take the input from the user. In Python, we can use
the input() function.
Syntax of input()

input(prompt)

Here, prompt is the string we wish to display on the screen. It is optional.

Example: Python User Input

# using input() to take user input


num = input('Enter a number: ')

print('You Entered:', num)

print('Data type of num:', type(num))


Run Code

Output

Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>

In the above example, we have used the input() function to take input from the user and stored
the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'>.
To convert user input into a number we can use int() or float() functions as:

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

Here, the data type of the user input is converted from string to integer .

33
Data Types in Python:
A data type in Python is a classification of specific types of data by a certain value or certain
types of mathematical or logical operations.
The way that data items are categorized or classified is known as their data type. It stands for the
type of value that indicates the types of operations that can be carried out on a specific set of
data. In this programming,
Types of Data Types in Python
Python has various built-in data types which will be discussed in this article:

1. Numeric - int, float, complex


2. String - str
3. Sequence - list, tuple, range
4. Binary - bytes, bytearray, memoryview
5. Mapping - dict
6. Boolean - bool
7. Set - set, frozenset
8. None - NoneType

1. Numeric data types in Python

 In Python, data with a numeric value is represented by the numeric data type.
 Python programming language supports four different numerical types −
1. int (signed integers) (eg 10)
2. long (long integers, they can also be represented by octal and hexadecimal)
(eg0122L)
3. float (floating point real values) (eg15.20)
4. complex (complex numbers) (eg3.14j)

Example meric Data Type in Python Compiler

# integer variable.
a=150
print("The type of variable having value", a, " is ", type(a))
# float variable.
b=20.846
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=18+3j
print("The type of variable having value", c, " is ", type(c))
Run Code >>

34
In this code, three variables (a, b, and c) are defined with three different data types (integer, float,
and complex), and each variable's type and value are printed.

Output

The type of variable having value 150 is <class 'int'>


The type of variable having value 20.846 is <class 'float'>
The type of variable having value(18+3j) is <class 'complex'>

2. Python String Data Type

 A group of one or more characters enclosed in a single, double, or triple quote is called
a string in python.
 A character in Python is just a string with a length of one; there is no character data type.
 The str class is used to represent it.

Example of String Data Type in Python

str = 'Hello World!'


print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string stating from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
Run Code >>

With the help of this code, you can see how to do many string operations in Python, such as
printing the complete string, accessing particular characters, slicing the string to get a substring,
repeating the text, and concatenating it with another string.

Output

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

3. Python List Data Type

 Python list is an arranged grouping of the same or dissimilar elements that are enclosed
by brackets [] and separated by commas.
 Use the index number to retrieve the list entries.

35
 To access a particular item in a list, use the index operator [].

Example of List Data Type in Python

list = [ 'abcd', 786 , 2.23, 'Scholar-Hat', 70.2 ]


tinylist = [123, 'Scholar-Hat']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Run Code >>

Working with Python lists is shown by this code in the Python Editor. It introduces two lists,
"list" and "tiny list," and it illustrates several list actions, such as printing the complete list,
accessing specific components, slicing to extract a sublist, repeating a list, and concatenating two
lists.

Output

['abcd', 786, 2.23, 'Scholar-Hat', 70.2]


abcd
[786, 2.23]
[2.23, ‘Scholar-Hat', 70.2]
[123, 'Scholar-Hat', 123, 'john']
['abcd', 786, 2.23, 'Scholar-Hat', 70.2, 123, 'Scholar-Hat']

4. Python Tuple Data Type

 A tuple in Python is an ordered list of elements, just like a list.


 Tuples are not changeable, which is the only difference.
 Once created, tuples cannot be changed.
 In Python, items of a tuple are stored using parentheses ().
 In Python, we utilize the index number to retrieve tuple items, just like with lists.

Example of Tuple Data Type in Python

tuple = ( 'abcd', 786 , 2.23, 'Scholar-Hat', 70.2 )


tinytuple = (123, 'Scholar-Hat')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice

36
print (tuple + tinytuple) # Prints concatenated tuples
Run Code >>

Python tuples are used in this code to show how they work. It introduces two tuples, "tuple" and
"tinytuple," defines them, and illustrates a number of tuple operations, such as publishing the
complete tuple, accessing each member, slicing to extract a sub-tuple, repeating a tuple, and
concatenating two tuples.

Output

('abcd', 786, 2.23, 'Scholar-Hat', 70.2)


abcd
(786, 2.23)
(2.23, 'Scholar-Hat', 70.2)
(123, ‘Scholar-Hat', 123, 'Scholar-Hat')
('abcd', 786, 2.23, 'Scholar-Hat', 70.2, 123, 'Scholar-Hat')

5. Python Range Data Type

 Range() in Python is a built-in function that returns a series of numbers that begin at 0
and increase by 1 until they reach a predetermined number.
 Utilizing a for and while loop in python, we use the range() method to produce a series of
numbers.

Example of Range Data type in Python

for i in range(1, 5):


print(i)
Run Code >>

This program iterates over numbers from 1 to 4 (inclusive) and writes each one on a separate line
using a for loop in python.

Output

1
2
3
4

6. Python Dictionary Data Type

 Python's dictionary is an unordered collection of data values that is used to store data
values in a map-like fashion.
 Unlike other data types, which only include a single value per element, dictionaries
contain a key-value pair.

37
 The dictionary contains key-value pairs to make it more effective.
 In a dictionary, a colon (:) separates each key-value pair, while a comma separates each
key.
 A dictionary in Python can be made by enclosing a list of elements in curly {} braces and
separating them with commas.

Example of Dictionary Data Type in Python

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'Scholar-Hat','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values
Run Code >>

The use of dictionaries in Python is shown by the following code. It performs several activities,
such as accessing values by keys, printing the complete dictionary, and showing keys and values
individually for 'tinydict', and defines three dictionaries: 'dict', and 'tinydict'.

Output

This is one
This is two
{'name': 'Scholar-Hat', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['Scholar-Hat', 6734, 'sales'])

7. Python Boolean Data Type

 One of the built-in data types in Python is the boolean type, which can represent either
True or False.
 Any expression can be evaluated for value using the Python bool() method, which returns
True or False depending on the expression.

Example of Boolean Data Type in Python

a = True
# display the value of a
print(a)

# display the data type of a


print(type(a))

38
Run Code >>

The variable 'a' is given the Boolean value "True" by the following code, which then prints both
the value ("True") and the data type ("bool") of the variable.

Output

true
<class'bool'>

8. Python Set Data Type

 A set is an unsorted collection of distinct components. This means that set elements
cannot be repeated, and the order in which they are kept is irrelevant.
 Sets are changeable, which means that after they are constructed, their elements can be
added or withdrawn. A set's elements, on the other hand, cannot be modified in place.
 Curly brackets {}are used to define sets.

Example of Set Data Type in Python

my_set = {1, 2, 3, 4, 5}
print(my_set)
Run Code >>

This code generates the set my_set and assigns the numbers 1, 2, 3, 4, and 5 to it. The contents of
the set are then printed to the console. Output
{1, 2, 3, 4, 5}
What is the data type conversion function?

 In Python, the process of converting an object's data type from one type to another is
referred to as data type conversion.
 In Python, there are two primary methods for converting data types:
1. Implicit Type Conversion
2. Explicit Type Conversion

Example of Data Type Conversion Function in Python Online Compiler

a = str(1) # a will be "1"


b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"
print (a)
print (b)
print (c)
Run Code >>

39
In this code, the numbers 1 and 2.2 are converted to string representations and assigned to
variables 'a' and 'b', respectively. The string "3.3" is already present in variable "c". Following
that, it prints the values of "a," "b," and "c," producing the output.

Python Strings

In Python, a string is a sequence of characters. For example, "hello" is a string containing a


sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use single quotes or double quotes to represent a string in Python. For example,

# create a string using double quotes


string1 = "Python programming"

# create a string using single quotes


string1 = 'Python programming'

Here, we have created a string variable named string1. The variable is initialized with the
string "Python Programming".

Example: Python String

# create string type variables

name = "Python"
print(name)

message = "I love Python."


print(message)
Run Code

Output

40
Python
I love Python.

In the above example, we have created string-type variables: name and message with
values "Python" and "I love Python" respectively.
Here, we have used double quotes to represent strings, but we can use single quotes too.

Access String Characters in Python

We can access the characters in a string in three ways.

 Indexing: One way is to treat strings as a list and use index values. For example,
greet = 'hello'

# access 1st index element


print(greet[1]) # "e"
Run Code

 Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For
example,
greet = 'hello'

# access 4th last element


print(greet[-4]) # "e"
Run Code

 Slicing: Access a range of characters in a string by using the slicing operator colon :. For
example,
greet = 'Hello'

# access character from 1st index to 3rd index


print(greet[1:4]) # "ell"

41
Run Code

Note: If we try to access an index out of the range or use numbers other than an integer, we will
get errors.

Python Strings are Immutable


In Python, strings are immutable. That means the characters of a string cannot be
changed. For example,

message = 'Hola Amigos'


message[0] = 'H'
print(message)
Run Code

Output

TypeError: 'str' object does not support item assignment

However, we can assign the variable name to a new string. For example,

message = 'Hola Amigos'

# assign new string to message variable


message = 'Hello Friends'

print(message); # prints "Hello Friends"


Run Code

Python Multiline String


We can also create a multiline string in Python. For this, we use triple double
quotes """ or triple single quotes ''' . For example,

42
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""

print(message)
Run Code

Output

Never gonna give you up


Never gonna let you down

In the above example, anything inside the enclosing triple quotes is one multiline
string.

Python String Operations


Many operations can be performed with strings, which makes it one of the most
used data types in Python.
1. Compare Two Strings
We use the == operator to compare two strings. If two strings are equal, the operator
returns True . Otherwise, it returns False . For example,
str1 = "Hello, world!"
str2 = "I love Swift."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)

43
Run Code

Output

False
True

In the above example,

1. str1 and str2 are not equal. Hence, the result is False .

2. str1 and str3 are equal. Hence, the result is True .

2. Join Two or More Strings


In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack


Run Code

In the above example, we have used the + operator to join two strings: greet and name .

44
Iterate Through a Python String
We can iterate through a string using a for loop. For example,
greet = 'Hello'

# iterating through greet string


for letter in greet:
print(letter)
Run Code

Output

H
e
l
l
o

Python String Length


In Python, we use the len() method to find the length of a string. For example,
greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5
Run Code

45
String Membership Test
We can test if a substring exists within a string or not, using the keyword in .
print('a'in'program') # True
print('at'notin'battle') # False
Run Code

String methods:

[Link] String upper()

The upper() method converts all lowercase characters in a string into uppercase
characters and returns it.
Example

message = 'python is fun'

# convert message to uppercase


print([Link]())

# Output: PYTHON IS FUN


The capitalize() method converts the first character of a string to an uppercase
letter and all other alphabets to lowercase.
Example

sentence = "i love PYTHON"

# converts first character to uppercase and others to lowercase


capitalized_string = [Link]()

print(capitalized_string)

# Output: I love python

46
[Link] String count()

The count() method returns the number of occurrences of a substring in the


given string.
Example

message = 'python is popular programming language'

# number of occurrence of 'p'


print('Number of occurrence of p:', [Link]('p'))

# Output: Number of occurrence of p: 4

[Link] String lower()

The lower() method converts all uppercase characters in a string into lowercase
characters and returns it.
Example
message = 'PYTHON IS FUN'

# convert message to lowercase


print([Link]())

# Output: python is fun

[Link] String split()

The split() method breaks down a string into a list of substrings using a chosen
separator.
Example

text = 'Python is fun'

# split the text from space


print([Link]())

# Output: ['Python', 'is', 'fun']

47
[Link] String find()

The find() method returns the index of first occurrence of the substring (if found). If
not found, it returns -1.
Example
message = 'Python is a fun programming language'

# check the index of 'fun'


print([Link]('fun'))

# Output: 12

[Link] String index()

The index() method returns the index of a substring inside the string (if found). If the
substring is not found, it raises an exception.
Example
text = 'Python is fun'

# find the index of is


result = [Link]('is')

print(result)

# Output: 7

[Link] replace() method


 [Link] translate() method
To learn some different ways to remove spaces from a string in Python, refer to Remove Spaces
from a String in Python.

A Python String object is immutable, so you can’t change its value. Any method that
manipulates a string value returns a new String object.

The examples in this tutorial use the Python interactive console in the command line to
demonstrate different methods that remove characters.
Remove Characters From a String Using the replace() Method
The String replace() method replaces a character with a new character. You can remove a
character from a string by providing the character(s) to replace as the first argument and an
empty string as the second argument.

48
Declare the string variable:

1. s = 'abc12321cba'
2.
Copy

Replace the character with an empty string:

1. print([Link]('a', ' '))


2.
Copy

The output is:

Output
bc12321cb
The output shows that both occurrences of the character a were removed from the string.
Remove a Substring from a String Using the replace() Method
The replace() method takes strings as arguments, so you can also replace a
word in string.
Declare the string variable:

1. s = 'Helloabc'
2.
Copy

Replace a word with an empty string:

1. print([Link]('Hello', ''))
2.
Copy

The output is:

Output
abc
The output shows that the string Hello was removed from the input string.
Remove Characters From a String Using the translate() Method
The Python string translate() method replaces each character in the string using the given
mapping table or dictionary.

Declare a string variable:

1. s = 'abc12321cba'
2.
Copy

49
Get the Unicode code point value of a character and replace it with None:
1. print([Link]({ord('b'): None}))
2.
Copy

The output is:

Output
ac12321ca
The output shows that both occurrences of the b character were removed from the string as
defined in the custom dictionary.

Python String islower()


The syntax of islower() is:

[Link]()

islower() parameters
The islower() method doesn't take any parameters.

Return Value from islower()


The islower() method returns:
 True if all alphabets that exist in the string are lowercase alphabets.
 False if the string contains at least one uppercase alphabet.

50
Example 1: Return Value from islower()
s = 'this is good'
print([Link]())

s = 'th!s is a1so g00d'


print([Link]())

s = 'this is Not good'


print([Link]())
Run Code

Output

True
True
False

Python String isupper()


The syntax of isupper() method is:

[Link]()

String isupper() Parameters


The isupper() method doesn't take any parameters.

51
Return value from String isupper()
The isupper() method returns:
 True if all characters in a string are uppercase characters
 False if any characters in a string are lowercase characters

Example 1: Return value of isupper()


# example string
string = "THIS IS GOOD!"
print([Link]());

# numbers in place of alphabets


string = "THIS IS ALSO G00D!"
print([Link]());

# lowercase string
string = "THIS IS not GOOD!"
print([Link]());
Run Code

Output

True
True
False

Python String Formatting (f-Strings)


Python f-Strings makes it easy to print values and variables. For example,
name = 'Cathy'
country = 'UK'

52
print(f'{name} is from {country}')
Run Code

Output

Cathy is from UK

Here, f'{name} is from {country}' is an f-string.


This new formatting syntax is powerful and easy to use. From now on, we will use f-
Strings to print strings and variables.

53

You might also like