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

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

Shuvajyoti Python

The document provides an overview of Python programming concepts, including conditional expressions, for loops, recursion, file operations, and exception handling. It explains the syntax and usage of conditional expressions, the mechanics of for loops, and how to open, read, and close files in Python. Additionally, it emphasizes the importance of proper file handling and exception management in programming.
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 views11 pages

Shuvajyoti Python

The document provides an overview of Python programming concepts, including conditional expressions, for loops, recursion, file operations, and exception handling. It explains the syntax and usage of conditional expressions, the mechanics of for loops, and how to open, read, and close files in Python. Additionally, it emphasizes the importance of proper file handling and exception management in programming.
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
You are on page 1/ 11

Swami Vivekananda Institute of Modern Studies

Name :Shuvajyoti Sarkar


Stream :BCA
Roll No: 35101221017
Year:2nd
Subject: Python
Subject Code: BCAC 403
What is a conditional expression?
A conditional expression in Python is an expression (in other words, a piece of code
that evaluates to a result) whose value depends on a condition.

Expressions and statements


To make it clearer, here is an example of a Python expression:

>>> 3 + 4 * 5
23

The code 3 + 4 * 5 is an expression, and that expression evaluates to 23.

Some pieces of code are not expressions. For example, pass is not an expression
because it does not evaluate to a result. pass is just a statement, it does not “have”
or “evaluate to” any result.

This might be odd (or not!) but to help you figure out if something is an expression or
not, try sticking it inside a print function. Expressions can be used inside other
expressions, and function calls are expressions. Therefore, if it can go inside
a print call, it is an expression:

>>> print(3 + 4 * 5)
23
>>> print(pass)
File "<stdin>", line 1
print(pass)
^
SyntaxError: invalid syntax

The syntactic error here is that the statement pass cannot go inside the print function,
because the print function wants to print something, and pass gives nothing.

Conditions
We are very used to using if statements to run pieces of code when
certain conditions are met. Rewording that, a condition can dictate what piece(s) of
code run.

In conditional expressions, we will use a condition to change the value to which the
expression evaluates. Wait, isn't this the same as an if statement? No! Statements
and expressions are not the same thing.

Syntax
Instead of beating around the bush, let me just show you the anatomy of a
conditional expression:

s
1
expr_if_true if condition else expr_if_false

A conditional expression is composed of three sub-expressions and the


keywords if and else. None of these components are optional. All of them have to be
present.

How does this work?

First, condition is evaluated. Then, depending on whether condition evaluates


to Truthy or Falsy, the expression evaluates expr_if_true or expr_if_false, respectively.

As you may be guessing from the names, expr_if_true and expr_if_false can
themselves be expressions. This means they can be simple literal values
like 42 or "spam", or other “complicated” expressions.

(Heck, the expressions in conditional expressions can even be other conditional


expressions! Keep reading for that 😉)

Examples of conditional expressions


Here are a couple of simple examples, broken down according to
the expr_if_true, condition, and expr_if_false anatomy presented above.

1.

>>> 42 if True else 0


42
expr_if_tr conditi expr_if_fa
ue on lse

42 True 0

2.

>>> 42 if False else 0


0
expr_if_tr conditi expr_if_fa
ue on lse

42 False 0

3.

>>> "Mathspp".lower() if pow(3, 27, 10) > 5 else "Oh boy."


'mathspp'

s
2
expr_if_fa
expr_if_true condition
lse

"Mathspp".low pow(3, 27, 10)


"Oh boy."
er() >5

For reference:

>>> pow(3, 27, 10)


7

Reading a conditional expression


While the conditional expression presents the operands in an order that may throw
some of you off, it is easy to read it as an English sentence.

Take this reference conditional expression:

value if condition else other_value

Here are two possible English “translations” of the conditional expression:

“Evaluate to value if condition is true, otherwise evaluate to other_value.”

or

“Give value if condition is true and other_value otherwise.”

With this out of the way, ...

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated
programming languages.

With the for loop we can execute a set of statements, once for each item in
a list, tuple, set etc.

ExampleGet your own Python Server


Print each fruit in a fruit list:

s
3
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

The break Statement


With the break statement we can stop the loop before it has looped through
all the items:

ExampleGet your own Python Server


Exit the loop when x is "banana":

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


for x in fruits:
print(x)
if x == "banana":
break

Try it Yourself »

ExampleGet your own Python Server


Exit the loop when x is "banana", but this time the break comes before the
print:

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


for x in fruits:
if x == "banana":
break
print(x)

Try it Yourself »

The continue Statement


With the continue statement we can stop the current iteration of the loop,
and continue with the next:

ExampleGet your own Python Server


Do not print banana:

s
4
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and ends at a specified number.

ExampleGet your own Python Server


Using the range() function:

for x in range(6):
print(x)

Python Function Recursion

Recursion
Python also accepts function recursion, which means a defined function can
call itself.

Recursion is a common mathematical and programming concept. It means


that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

In this example, tri_recursion() is a function that we have defined to call


itself ("recurse"). We use the k variable as the data, which decrements (-1)

s
5
every time we recurse. The recursion ends when the condition is not greater
than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.

ExampleGet your own Python Server


Recursion Example

def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

A file is a container in computer storage devices used for storing data.

When we want to read from or write to a file, we need to open it first. When
we are done, it needs to be closed so that the resources that are tied with
the file are freed.

Hence, in Python, a file operation takes place in the following order:

1. Open a file

2. Read or write (perform operation)

3. Close the file

Opening Files in Python

s
6
In Python, we use the open() method to open files.
To demonstrate how we open files in Python, let's suppose we have a file
named test.txt with the following content.

Opening Files in Python

Now, let's try to open data from this file using the open() function.

# open file in current directory


file1 = open("test.txt")

Here, we have created a file object named file1 . This object can be used
to work with files and directories.
By default, the files are open in read mode (cannot be modified). The code
above is equivalent to

file1 = open("test.txt", "r")

Here, we have explicitly specified the mode by passing the "r" argument
which means file is opened for reading.
Different Modes to Open a File in Python

Mode Description

r Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates
w
the file if it exists.

s
7
Open a file for exclusive creation. If the file already exists, the operation
x
fails.

Open a file for appending at the end of the file without truncating it.
a
Creates a new file if it does not exist.

t Open in text mode. (default)

b Open in binary mode.

+ Open a file for updating (reading and writing)

Here's few simple examples of how to open a file in different modes,

file1 = open("test.txt") # equivalent to 'r' or 'rt'


file1 = open("test.txt",'w') # write in text mode
file1 = open("img.bmp",'r+b') # read and write in binary mode

Reading Files in Python


After we open a file, we use the read() method to read its contents. For
example,

# open a file
file1 = open("test.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

Output

This is a test file.

s
8
Hello from the test file.

In the above example, we have read the test.txt file that is available in
our current directory. Notice the code,

read_content = file1.read

Here, file1.read() reads the test.txt file and is stored in


the read_content variable.

Closing Files in Python


When we are done with performing operations on the file, we need to
properly close the file.

Closing a file will free up the resources that were tied with the file. It is done
using the close() method in Python. For example,

# open a file
file1 = open("test.txt", "r")

# read the file


read_content = file1.read()
print(read_content)

# close the file


file1.close()

Output

This is a test file.


Hello from the test file.

Here, we have used the close() method to close the file.

s
9
After we perform file operation, we should always close the file; it's a good
programming practice.

Exception Handling in Files


If an exception occurs when we are performing some operation with the
file, the code exits without closing the file. A safer way is to use
a try...finally block.
Let's see an example,

try:
file1 = open("test.txt", "r")
read_content = file1.read()
print(read_content)

finally:
# close the file
file1.close()

Here, we have closed the file in the finally block as finally always
executes, and the file will be closed even if an exception occurs.

s
10

You might also like