Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views27 pages

Python U-I

Python complete things in one pdf

Uploaded by

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

Python U-I

Python complete things in one pdf

Uploaded by

layer86104
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Introduction to Python Programming

Unit-I

Python is a high-level, interpreted language that emphasizes code readability and simplicity. Created
by Guido van Rossum in 1991, Python supports multiple programming paradigms and is used for web
development, data science, automation, and more. Key reasons for its popularity include platform
independence, extensive libraries, and a beginner-friendly syntax.

Basic Python Syntax

• Indentation: Used to define code blocks; no curly braces.

• Comments: Start with # for single lines; triple quotes for multi-line.

• Statements: Each command ends with a newline.

• Print Example:

python

print("Hello, World!")

Output:

text

Hello, World!

What is Python?

Python is a popular programming language. It was created by Guido van

Rossum, and released in 1991.

OR

Python is an interpreted, object-oriented, high-level programming language

with dynamic semantics developed by Guido van Rossum.

It was originally released in 1991. Designed to be easy as well as fun, the

name "Python" is a nod to the British comedy group Monty Python.

Python has a reputation as a beginner-friendly language, replacing Java as

the most widely used introductory language because it handles much of the

complexity for the user, allowing beginners to focus on fully grasping


programming concepts rather than minute details.

Where It is used for?

web development (server-side),

software development,

mathematics,

system scripting.

Processing big data

Fast prototyping

Developing production-ready software

Why Python?

Python works on different platforms (Windows, Mac,

Linux, Raspberry Pi, etc).

Python has a simple syntax similar to the English

language.

Python has syntax that allows developers to write

programs with fewer lines than some other

programming languages.

Python runs on an interpreter system, meaning that

code can be executed as soon as it is written. This

means that prototyping can be very quick.

Python can be treated in a procedural way, an object-oriented

way or a functional way.

PYTHON HISTORY AND VERSIONS

Python laid its foundation in the late 1980s.

The implementation of Python was started in


December 1989 by Guido Van Rossum at CWI in Netherland.In February 1991, Guido Van Rossum
published the code (labeled version 0.9.0) In 1994, Python 1.0 was released with new features like
lambda, map, filter, and reduce.Python 2.0 added new features such as list comprehensions, garbage
collection systems.

PYTHON FEATURES

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is straightforward and
much the same as the English language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block. It is the recommended programming language for beginners.

2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type

print("Hello World"). It will take only one line to execute,while Java or C takes multiple lines.

3) Interpreted Language

Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc.
So, we can say that Python is a portable language. It enables programmers to develop the software for
several competing platforms by writing a program only once.

5) Free and Open Source

Python is freely available for everyone. It is freely available on its official website www.python.org. It
has a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source means,
"Anyone can download its sourcecode without paying any penny."

6) Object-Oriented Language

Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.

7) Dynamic Memory Allocation


In Python, we don't need to specify the data-type of the variable. When we assign some value to the
variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned
integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.

8) GUI Programming Support

Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the
libraries which are used for developing the web application.

9) Integrated

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line
like C,C++ Java. It makes easy to debug the code.

PYTHON APPLICATIONS

1) Web Applications

We can use Python to develop web applications. It provides libraries to handle internet protocols such
as HTML and XML, JSON, Email processing, request, beautiful Soup, Feedparser, etc. One of Python

web-framework named Django is used on Instagram.

2) Desktop GUI Applications

The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface.

3) Console-based Application

Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the old

generation of computers. Python can develop this kind of application very effectively. It is famous for
having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for

the command-line applications.

4) Software Development

Python is useful for the software development process. It works as a support language and can be used
to build control and management, testing, etc.

5) Scientific and Numeric

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.

6) Business Applications

Business Applications differ from standard applications. Ecommerce and ERP are an example of a
business application. This kind of application requires extensively, scalability and readability,

and Python provides all these features.

7) Audio or Video-based Applications

Python is flexible to perform multiple tasks and can be used to create multimedia applications. Some
multimedia applications which are made by using Python are TimPlayer, cplay, etc.

8) 3D CAD Applications

The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system. Python can create a 3D CAD application by

using Any CAD.

9) Enterprise Applications

Python can be used to create applications that can be used within an Enterprise or an Organization.

10) Image Processing Application

Python contains many libraries that are used to work with theimage. The image can be manipulated
according to our requirements.

Installation: There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software from
http://python.org/downloads/ Steps to be followed and remembered:

Step 1: Select Version of Python to Install.

Step 2: Download Python Executable Installer.

Step 3: Run Executable Installer.

Step 4: Verify Python Was Installed On Windows.

Step 5: Verify Pip Was Installed.

Step 6: Add Python Path to Environment Variables (Optional) Working with Python Python Code
Execution: Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted. Source Byte code Runtime Source code extension is .py Byte code
extension is .pyc (Compiled python code)

There are two modes for using the Python interpreter:

• Interactive Mode • Script Mode m.py m.pyc

Running Python in interactive mode: Without passing python script file to the interpreter, directly
execute code to Python prompt.

>>> print("hello world") hello world # Relevant output is displayed on subsequent lines without the >>>
symbol >>> x=[0,1,2] # Quantities stored in memory are not displayed by default. >>> x #If a quantity
is stored in memory, typing its name will display it. [0, 1, 2] >>> 2+3 5 The chevron at the beginning
of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to indicate that it is ready. If
the programmer types 2+6, the interpreter replies 8.

Running Python in script mode: Alternatively, programmers can store Python script source code in a
file with the .py extension, and use the interpreter to execute the contents of the file.

To execute the script by the interpreter, you have to tell the interpreter the name of the file.

For example, if you have a script name MyFile.py

C:\Users\Your Name>python –version

If you find that you do not have Python installed on your

computer, then you can download it for free from the following

website: https://www.python.org/

Verify installation

Once IDLE is launched, go to file menu

Click on new file to create new python file.

C:\Users\Your Name>python –

FIRST PYTHON PROGRAM

Python provides us the two ways to run a program:

1. Using Interactive interpreter prompt

2. Using a script file


Example Program

print("Hello, World!")

PYTHON BASICS

PYTHON CHARACTER SET

Character set is a set of valid characters that a language can recognize. A

character represents any letter, digit or any other symbol. Python

supports Unicode encoding standard. That means, Python has the

following character set :

Letters A-Z, a-z

Digits 0-9

Special symbols space +-/*\() [] {} // = != == <, > . '"'"",;:%!& # <= >=

@_(underscore)

Whitespaces Blank space, tabs (→), carriage return (), newline,

formfeed.

Other characters Python can process all ASCII and Unicode

characters as part of data or literals

IDENTIFIERS

IDENTIFIERS ARE FUNDAMENTAL BUILDING BLOCKS OF A PROGRAM

AND ARE USED AS THE GENERAL TERMINOLOGY FOR THE NAMES GIVEN

TO DIFFERENT PARTS OF THE PROGRAM VIZ. VARIABLES, OBJECTS,

CLASSES, FUNCTIONS, LISTS, DICTIONARIES ETC. IDENTIFIER FORMING

RULES OF PYTHON ARE BEING SPECIFIED BELOW:

An identifier is an arbitrarily long

sequence of letters and digits.

The first character must be a letter; the underscore (_) counts as a letter.
Upper and lower-case letters are different. All characters are significant.

The digits 0 through 9 can be part of the identifier except for the first character.

Identifiers are unlimited in length. Case is significant i.e., Python is case sensitive as

it treats upper and lower-case characters differently.

An identifier cannot contain any special

character except for underscore (_).

An identifier must not be a keyword of python.

KEYWORDS IN PYTHON

Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function
name or any

other identifier.

Here's a list of all keywords in Python Programming

Examples of Python Keywords:

• Control Flow: if, else, elif, for, while, break, continue, pass, return, yield

• Data Types and Values: True, False, None

• Module and Package Handling: import, from, as

• Class and Function Definition: def, class, lambda

• Exception Handling: try, except, finally, raise

• Other: and, or, not, in, is, del, global, nonlocal, assert, with, async, await

PYTHON VARIABLES

Variables are identifiers of a physical memory location, which is used to hold values temporarily

during program execution.

Python interpreter allocates memory based on the values(letter or a number) data type of variable,

different data types like integers, decimals, characters, etc. can be stored in these variables.
Python Variable Declaration

In Python, like many other programming languages, there is no need to define variables in advance.

As soon as a value is assigned to a variable, it is automatically declared. This is why Python is

called a dynamically typed language.

The syntax for creating variables in Python is

given below:

<variable-name> =<value>

ASSIGNING VALUE TO VARIABLES

Python interpreter can determine what type of data is stored, so before assigning a value, variables
do not need to be declared.

Usually, in all programming languages, equal sign = is used to assign values to a variable. It assigns
the values of the right side operand to the left side operand.

The left side operand of = operator is the name of a

variable, and the right side operand is value.

Example:

OUTPUT

Packing box

10

20.5

name = "Packing box" # A string

height = 10 # An integer assignment

width = 20.5 # A floating point

print (name)

print (height)

print (width)

Common Rules for Naming Variables in Python


Python has some variable related rules that must be

followed:

Variable names are case-sensitive.

Variable names must begin with a letter or underscore.

A variable name can only contain alphanumeric characters and underscore, such as (a-z, A-Z, 0-9,
and_ ).

A variable name can not contents space.

Reserved words cannot be used as a variable name.

Example

This will create two variables:

a=4

A = "Sally"

DATA TYPES

Python offers following built-in core data types :

1. Numbers - immutable(cannot be changed/modified)

2. String - immutable(cannot be changed/modified)

3. List - mutable(changed/modified)

4. Tuple - immutable(cannot be changed/modified)

5. Dictionary - mutable(changed/modified)

1. NUMBERS

N umeric values are stored in numbers. The whole number, float, and

complex qualities have a place with a Python Numbers data type.

Python offers the type() function to determine a variable's data type.

The instance () capability is utilized to check whether an item has a

place with a specific class.


Example

a=5

print("The type of a", type(a))

b = 40.5

print("The type of b", type(b))

c = 1+3j

print("The type of c", type(c))

print(" c is a complex number", isinstance(1+3j,complex))

Output

The type of a <class 'int'>

The type of b <class 'float'>

The type of c <class 'complex'>

c is complex number: True

PYTHON SUPPORTS THREE KINDS OF

NUMERICAL DATA.

Int: Whole number worth can be any length, like

numbers 10, 2, 29, - 20, - 150, and so on. An

integer can be any length you want in Python. Its

worth has a place with int.

Float: Float stores drifting point numbers like

1.9, 9.902, 15.2, etc. It can be accurate to within

15 decimal places.

Complex: An intricate number is in the form

A+Bi where i is the imaginary number, equal to

the sqare root of -1 i.e., √-1, that is 12 The complex


numbers like 2.14j, 2.0 + 2.3j, etc.

2. SEQUENCE TYPE OR STRING TYPE

The sequence of characters in the quotation marks can be used to

describe the string. A string can be defined in Python using single,

double, or triple quotes.

String dealing with Python is a direct undertaking since Python

gives worked-in capabilities and administrators to perform tasks in

the string.

When dealing with strings, the operation "hello"+" python" returns

"hello python," and the operator + is used to combine two strings.

Because the operation "Python" *2 returns "Python," the operator * is

referred to as a repetition operator.

Example

str1 = 'hello javatpoint' #string str1

str2 = ' how are you' #string str2

print (str1[0:2]) #printing first two character using slice operator

print (str1[4]) #printing 4th character of the string

print (str1*2) #printing the string twice

print (str1 + str2) #printing the concatenation of str1 and str2

3. LIST

Lists in Python are like arrays in C, but lists can contain data of

different types. The things put away in the rundown are isolated

with a comma (,) and encased inside square sections [].

To gain access to the list's data, we can use slice [:] operators. Like

how they worked with strings, the list is handled by the


concatenation operator (+) and the repetition operator (*).

Example

list1 = [1, "hi", "Python", 2]

#Checking type of given list

print(type(list1))

#Printing the list1

print (list1)

# List slicing

print (list1[3:])

# List slicing

print (list1[0:2])

# List Concatenation using + operator

print (list1 + list1)

# List repetation using * operator

print (list1 * 3)

Out put

[1, 'hi', 'Python', 2]

[2]

[1, 'hi']

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2,

1, 'hi', 'Python', 2]

4. TUPLE

In many ways, a tuple is like a list. Tuples, like lists, also contain a

collection of items from various data types. A parenthetical space ()


separates the tuple's components from one another.

Because we cannot alter the size or value of the items in a tuple, it is a

read-only data structure.

Example

up = ("hi", "Python", 2)

# Checking type of tup

print (type(tup))

#Printing the tuple

print (tup)

# Tuple slicing

print (tup[1:])

print (tup[0:1])

# Tuple concatenation using + operator

print (tup + tup)

# Tuple repatation using * operator

print (tup * 3)

# Adding value to tup. It will throw an error.

t[2] = "hi"

Out put

<class 'tuple'>

('hi', 'Python', 2)

('Python', 2)

('hi',)

('hi', 'Python', 2, 'hi', 'Python', 2)

('hi', 'Python', 2, 'hi', 'Python', 2,


'hi', 'Python', 2)

Traceback (most recent call

last):

File "main.py", line 14, in

<module> t[2] = "hi";

TypeError: 'tuple' object does

not support item assignment

5. DICTIONARY

A dictionary is a key-value pair set arranged in any order. It stores a

specific value for each key, like an associative array or a hash table.

Value is any Python object, while the key can hold any primitive data

type.

The comma (,) and the curly braces are used to separate the items in

the dictionary.

Example

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary

print (d)

# Accesing value using keys

print("1st name is "+d[1])

print("2nd name is "+ d[4])

print (d.keys())

print (d.values())

Out Put

1st name is Jimmy


2nd name is mike

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}

dict_keys([1, 2, 3, 4]) dict_values(['Jimmy',

'Alex', 'john', 'mike'])

6. SETS

The data type's unordered collection is Python

Set. It is iterable, mutable(can change after creation), and has remarkable components. The

elements of a set have no set order; It might return the element's altered sequence. Either a

sequence of elements is passed through the curly braces and separated by a comma to create the

set or the built-in function set() is used to create the set. It can contain different kinds of values.

EXAMPLE

# Creating Empty set

set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value

print(set2)

# Adding element to the set

set2.add(10)

print(set2)

#Removing element from the set

set2.remove(2)

print(set2)

Out Put

{3, 'Python', 'James', 2}

{'Python', 'James', 3, 2, 10}


{'Python', 'James', 3, 10}

PYTHON - OPERATORS

Python operators are the constructs which can manipulate

the value of operands. These are symbols used for the

purpose of logical, arithmetic and various other operations.

Consider the expression 4 + 5 = 9. Here, 4 and 5 are

called operands and + is called operator. In this tutorial,

Types of Python Operators

Python language supports the following types of operators.

Arithmetic Operators

Comparison (Relational) Operators

Assignment Operators

Logical Operators

Bitwise Operators

Membership Operators

PYTHON ARITHMETIC OPERATORS

Python arithmetic operators are used to perform mathematical operations on numerical values.
These operations are Addition, Subtraction, Multiplication, Division, Modulus, Exponents and Floor
Division. Operator Description

+ (Addition) It is used to add two operands.

For example, if a = 10, b = 10 => a+b = 20

- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is
less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b =15

/ (divide) It returns the quotient after dividing the first operand by the second operand. For example, if
a

= 20, b = 10 => a/b = 2.0


* (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a
* b = 80

% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if

a = 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent
operator.

// (Floor division) It provides the quotient's floor value, which is obtained by dividing the two
operands.

PYTHON COMPARISON OPERATORS

Python comparison operators compare the values on either sides of them and decide the relation
among

them. They are also called relational operators. These

operators are equal, not equal, greater than, less than,

greater than or equal to and less than or equal to.

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

PYTHON ASSIGNMENT OPERATORS

Python assignment operators are used to assign values to variables. These operators include simple

assignment operator, addition assign, subtraction assign, multiplication assign, division and assign

operators etc.

Operator
Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a %

5)

**= Exponent Assignment a **= 2 (Same as a = a **

2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

PYTHON BITWISE OPERATORS

Bitwise operator works on bits and performs bit by bit operation.

Assume if a = 60; and b = 13; Now in the binary format their

values will be 0011 1100 and 0000 1101 respectively. Following

table lists out the bitwise operators supported by Python

language with an example each in those, we use the above two

Name Example

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits is 1

^ Binary XOR Sets each bit to 1 if only one of two bits is 1

~ Binary Ones

Complement

Inverts all the bits

<< Binary Left Shift Shift left by pushing zeros in from the right
and let the leftmost bits fall off

>> Binary Right

Shift

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

PYTHON MEMBERSHIP OPERATORS

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are

• Variables:

python

x=5

name = "Alice"

4Basic Data Types in Python

Data Type Example Assignment

Int x = 20

Float y = 20.5

complex z = 1j

str s = "Hello World"

list list1 = ["apple", "banana"]

tuple t = ("apple", "banana")

range r = range(6)
Data Type Example Assignment

dict d = {"name": "John", "age": 36}

set set1 = {"apple", "banana"}

bool b = True

NoneType n = None

Use type() to check any variable's datatype:

python

x=5

print(type(x)) # Output: <class 'int'>

Simple Input-Output in Python

• Output: Use print() with optional sep, end parameters.

python

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

print("It is rainy today")

# Output: Good Morning! It is rainy today

• Input: Use input().

python

num = input("Enter a number: ")

print("You Entered:", num)

print("Type:", type(num))

# Output: Always a string

• Input Conversion:
python

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

Precedence of Operators

Order in which operations are performed:

• Highest precedence: Parentheses ()

• Exponentiation **

• Unary operators +x, -x, ~x

• Multiplication/Division/Modulus *, /, //, %

• Addition/Subtraction +, -

• Bitwise, Comparison, Logical, Identity, Membership

• Lowest precedence: or

Examples:

python

result = 10 - 5 + 3 * 2

print(result) # Output: 11

python

print((6 + 3) - (6 + 3)) # Output: 0

print(100 + 5 * 3) # Output: 115

Type Conversion in Python

• Implicit Conversion: Python converts types automatically.

python

a = 5 # int

b = 2.5 # float

result = a + b

print(result, type(result)) # Output: 7.5 <class 'float'>


• Explicit Conversion: Manual using built-in functions.

python

s = "100"

num = int(s)

print(num, type(num)) # Output: 100 <class 'int'>

Use functions: int(), float(), str(), list(), tuple(), bool(), dict()

Conditional Statements

• if: Checks condition.

• elif: Checks another condition if previous are False.

• else: Executes when previous are False.

Example:

python

age = 25

if age <= 12:

print("Child.")

elif age <= 19:

print("Teenager.")

elif age <= 35:

print("Young adult.")

else:

print("Adult.")

Nested if:

python

age = 70
is_member = True

if age >= 60:

if is_member:

print("30% senior discount!")

else:

print("20% senior discount.")

else:

print("Not eligible for a senior discount.")

Ternary Operator:

python

status = "Adult" if age >= 18 else "Minor"

match-case (Python 3.10+):

python

match number:

case 1:

print("One")

case 2 | 3:

print("Two or Three")

case _:

print("Other number")

Looping in Python: for, while, Nested Loops

for loop:

python

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:

print(fruit)

while loop:

python

i=1

while i < 5:

print(i)

i += 1

Nested loops:

python

for i in range(3):

for j in range(2):

print(i, j)

Complex Nested Loop Example (Prime Numbers):

python

i=2

while(i < 100):

j=2

while(j <= (i/j)):

if not(i%j): break

j += 1

if (j > i/j): print(i, "is prime")

i += 1

print("Good bye!")

Terminating Loops & Skipping Specific Conditions


• break: Terminates loop early.

python

for i in range(10):

if i == 5:

break

print(i)

# Output: 0 to 4

• continue: Skips current iteration.

python

for i in range(10):

if i % 2 == 0:

continue

print(i)

# Output: 1, 3, 5, 7, 9

• pass: Does nothing (null statement, placeholder).

python

for i in range(10):

pass # Placeholder for future code

Scope and Extent of Variables

• Variables defined inside a function have local scope.

• Variables outside functions have global scope.

• Use global keyword to modify global variables inside functions.

python

x = "global"

def foo():
global x

x = "modified"

foo()

print(x) # Output: "modified"

• Variables in loops, if blocks, etc., follow the same scope rules.

Testing and Debugging Principles

• Print Statements: Check values at different program stages.

• Exception Handling (try-except):

python

try:

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

print("The number is:", num)

except ValueError:

print("Invalid input. Please enter a valid number.")

• While-Else Statement:

python

i=0

while i < 5:

print(i)

i += 1

else:

print("Loop completed successfully.")

You might also like