lab manual for programming with python lab, Study notes of Programming Languages

lab manual for programming with python lab

Typology: Study notes

2021/2022

Uploaded on 06/29/2022

aliasger
aliasger 🇮🇳

5

(1)

5 documents

1 / 108

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Experiment – I Introduction to Python
1. How to execute simple commands in Python Command Prompt
Unless you use some sort of integrated development environment, you will end up typing
Windows commands into what is variously referred to as a “DOS window” or “Command prompt
window”. Usually you can create such a window from your Start menu; under Windows 7 the
menu selection is Start Programs Accessories Command Prompt. You should be able to
recognize when you have started such a window because you will see a Windows “command
prompt”, which usually looks like this:
C:\>
You need to realize that your Python scripts have to be processed by another program called the
Python interpreter. The interpreter reads your script, compiles it into byte codes, and then
executes the byte codes to run your program. So, how do you arrange for the interpreter to
handle your Python?
First, you need to make sure that your command window recognizes the word “python” as an
instruction to start the interpreter. If you have opened a command window, you should try
entering the command python and hitting return.
C:\Users\YourName> python
You should then see something like:
Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
You have started the interpreter in “interactive mode”. That means you can enter Python
statements or expressions interactively and have them executed or evaluated while you wait.
This is one of Python’s strongest features. Check it by entering a few expressions of your choice
and seeing the results:
>>> print "Hello"
Hello
>>> "Hello" * 3
'HelloHelloHello'
How do I make Python scripts executable?
On Windows, the standard Python installer already associates the .py extension with a file type
(Python.File) and gives that file type an open command that runs the interpreter (D:\Program
Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command
prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no
extension you need to add .py to the PATHEXT environment variable.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download lab manual for programming with python lab and more Study notes Programming Languages in PDF only on Docsity!

Experiment – I Introduction to Python

  1. How to execute simple commands in Python Command Prompt Unless you use some sort of integrated development environment, you will end up typing Windows commands into what is variously referred to as a “DOS window” or “Command prompt window”. Usually you can create such a window from your Start menu; under Windows 7 the menu selection is Start ‣ Programs ‣ Accessories ‣ Command Prompt. You should be able to recognize when you have started such a window because you will see a Windows “command prompt”, which usually looks like this: C:> You need to realize that your Python scripts have to be processed by another program called the Python interpreter. The interpreter reads your script, compiles it into byte codes, and then executes the byte codes to run your program. So, how do you arrange for the interpreter to handle your Python? First, you need to make sure that your command window recognizes the word “python” as an instruction to start the interpreter. If you have opened a command window, you should try entering the command python and hitting return. C:\Users\YourName> python You should then see something like: Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win Type "help", "copyright", "credits" or "license" for more information. >>> You have started the interpreter in “interactive mode”. That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python’s strongest features. Check it by entering a few expressions of your choice and seeing the results: >>> print "Hello" Hello >>> "Hello" * 3 'HelloHelloHello' How do I make Python scripts executable? On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable.
  1. Howto execute simple commands in Python IDLE interactive shell What is IDLE? IDLE is the integrated development environment (IDE) provided with Python. An IDE combines a program editor and a language environment as a convenience to the programmer. Using IDLE is not a requirement for using Python. There are many other IDEs that can be used to write Python programs, not to mention a variety of text-based programmer's editors that many programmers prefer to IDEs. We are covering IDLE because it comes with Python, and because it is not too complex for beginning programmers to use effectively. You are welcome to use another editor or IDE if you wish, but if you don't already know one, IDLE is a good choice.

Using the Python Shell Window

The top of IDLE's Python Shell window will look something like this: Experimenting with Python Commands Python, by design, is an interpreted language (as opposed to a compiled language). Programs written with interpreted languages do tend to execute a little more slowly than do compiled programs, but for most tasks the difference is insignificant. The big advantage of an interpreted language is experimentation: A programmer can try out algorithms and play around with different commands interactively (that is, without having to write a complete program to do either). For people just starting to learn programming in general, or Python in particular, interactive experimentation is very useful. This interactivity is the main purpose of the IDLE's Python Shell window. You probably noticed already that the last line of text in the window is the set of three 'greater-than' symbols. This is the prompt symbol; when you see it on a line by itself, Python is waiting for you to do something -- such as type in a command. Let's give it a try. Click on the Python Shell window (to make sure that it has the keyboard's attention) and then type this line, just like you see it: print("Bear Down, Wildcats!")

  1. Writingprogram in script mode

Script Mode

In interactive mode, Python displays the results of expressions. In script mode, however, Python doesn’t automatically display results. In order to see output from a Python script, we’ll introduce the print statement and the print() function. The print statement is the Python 2.6 legacy construct. The print() function is a new Python 3 construct that will replace the print statement. We’ll visit this topic in depth in Seeing Output with the print() Function (or print Statement).

· Implicitly from the command line. In this case, we’ll either use the GNU/Linux shell comment (sharp-bang marker) or we’ll depend on the file association in Windows. This is slightly more complex, and we’ll look at this in detail below. · Manually from within IDLE. It’s important for newbies to remember that IDLE shouldn’t be part of the final delivery of a working application. However, this is a great way to start development of an application program. Running Python scripts from the command-line applies to all operating systems. It is the core of delivering final applications. We may add an icon for launching the application, but under the hood, an application program is essentially a command-line start of the Python interpreter.

4. Program Using Variables and Assignment In algebra, variables represent numbers. The same is true in Python, except Python variables also can represent values other than numbers. Listing 2.1 (variable.py) uses a variable to store an integer value and then prints the value of the variable. x = 10 print(x) Listing 2.1 (variable.py) contains two statements x = 10 This is an assignment statement. An assignment statement associates a value with a variable. The key to an assignment statement is the symbol = which is known as the assignment operator. The statement assigns the integer value 10 to the variable x. Said another way, this statement binds the variable named x to the value 10. At this point the type of x is int because it is bound to an integer value. A variable may be assigned and reassigned as often as necessary. The type of a variable will change if it is reassigned an expression of a different type. print(x) This statement prints the variable x’s current value. Note that the lack of quotation marks here is very important. If x has the value 10, the statement print(x) prints 10, the value of the variable x, but the statement print('x') prints x, the message containing the single letter x.

The meaning of the assignment operator (=) is different from equality in mathematics. In mathematics, asserts that the expression on its left is equal to the expression on its right. In Python, = makes the variable on its left take on the value of the expression on its right. It is best to read x = 5 as “x is assigned the value 5,” or “x gets the value 5.” This distinction is important since in mathematics equality is symmetric: if x = 5, we know 5 = x. In Python this symmetry does not exist; the statement 5 = x attempts to reassign the value of the literal integer value 5, but this cannot be done because 5 is always 5 and cannot be changed. Such a statement will produce an error. >>>x = 5 >>>x 5 >>> 5 = x File "", line 1 Syntax Error: can’t assign to literal Variables can be reassigned different values as needed, as Listing 2.2 (multipleassignment.py) shows. 2: multipleassignment.py x = 10 print('x = ' + str(x)) x = 20

print y print z Output: >>> 50 50 50 >>>

7. Program to assign multiple values to multiple variables: a,b,c=5,10, print a print b print c Output: >>> 5 10 15 >>>

Experiment – II Control Statements

What are Conditional Statements in Python?

Conditional Statement in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. Conditional statements are handled by IF statements in Python. In this tutorial, we will see how to apply conditional statements in Python.

What is Python If Statement?

Python if Statement is used for decision-making operations. It contains a body of code which runs only when the condition given in the if statement is true. If the condition is false, then the optional else statement runs which contains some code for the else condition. When you want to justify one condition while the other condition is not true, then you use Python if else statement. Python if Statement Syntax: if expression Statement else Statement

#Example file for working with conditional statement

def main(): x,y = 2 , 8 if(x < y): st= "x is less than y" print(st)

1. Program to demonstrate use of if statement in python a= if a==10: print "Hello User" **Output: Hello User

  1. Program to demonstrate use of if-else statement in python**

year= if year%4==0: print "Year is Leap" else: print "Year is not Leap" Output: Year is Leap

3. Program to demonstrate use of nested if-else statement in python a= if a>=20: print "Condition is True" else: if a>=15: print "Checking second value" else: print "All Conditions are false" **Output: All Conditions are false.

  1. Program to demonstrate the display table of number using for-loop statement.**

print Output: >>> 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 >>>

7. Program to add digits of a number using while loop. n= sum= while n>0: r=n% sum+=r n=n/ print sum Output: >>> 9 >>>

8. Program to demonstrate the use of the break statement. for i in [1,2,3,4,5]: if i==4: print "Element found" break print i, Output: >>> 1 2 3 Element found **>>>

  1. Program to demonstrate the use of the continue statement.** a= while a<=5: a=a+ if a%2==0: continue print a print "End of Loop"

Let us define a function by using the command ” def func1():” and call the function. The output of the function will be “I am learning Python function”. Now, when you add the indent (space) in front of “print” function, it should print as expected. At least, one indent is enough to make your code work successfully. But as a best practice it is advisable to leave about 3-4 indent to call your function. It is also necessary that while declaring indentation, you have to maintain the same indent for the rest of your code. For example, in below screen shot when we call another statement “still

in func1” and when it is not declared right below the first print statement it will show an indentation error “unindent does not match any other indentation level.” Now, when we apply same indentation for both the statements and align them in the same line, it gives the expected output.

How Function Return Value?

Return command in Python specifies what value to give back to the caller of the function. Let’s understand this with the following example Step 1) Here – we see when function is not “return”. For example, we want the square of 4, and it should give answer “16” when the code is executed. Which it gives when we simply use “print

Step 4) Functions in Python are themselves an object, and an object has some value. We will here see how Python treats an object. When you run the command “print square” it returns the value of the object. Since we have not passed any argument, we don’t have any specific function to run over here it returns a default value (0x021B2D30) which is the location of the object. In practical Python program, you probably won’t ever need to do this.

Arguments in Functions

The argument is a value that is passed to the function when it’s called. In other words on the calling side, it is an argument and on the function side it is a parameter. Let see how Python Args works – Step 1) Arguments are declared in the function definition. While calling the function, you can pass the values for that args as shown below

Step 2) To declare a default value of an argument, assign it a value at function definition. Example: x has no default values. Default values of y=0. When we supply only one argument while calling multiply function, Python assigns the supplied value to x while keeping the value of y=0. Hence the multiply of x*y= Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will return the output as (4×2)=8.