Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
260 views

Python Assignment

The document provides code examples to demonstrate: 1) Accepting user input of first and last name and printing them in reverse order with a space. 2) Explaining the difference between raw_input() and input() functions in Python for accepting user input. 3) Taking comma separated user input, converting to a list and tuple, and printing them. 4) Code to check if a number input by the user is even or odd using if/else statement. 5) Code to display the multiplication table of a number up to 10 using for loop. 6) Converting a decimal number to binary, octal and hexadecimal representations using built-in functions. 7

Uploaded by

Jayant Deshmukh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
260 views

Python Assignment

The document provides code examples to demonstrate: 1) Accepting user input of first and last name and printing them in reverse order with a space. 2) Explaining the difference between raw_input() and input() functions in Python for accepting user input. 3) Taking comma separated user input, converting to a list and tuple, and printing them. 4) Code to check if a number input by the user is even or odd using if/else statement. 5) Code to display the multiplication table of a number up to 10 using for loop. 6) Converting a decimal number to binary, octal and hexadecimal representations using built-in functions. 7

Uploaded by

Jayant Deshmukh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

PRACTICAL 1

1) Write a Python program which accepts the user's first and last name and print them in reverse order
with a space between them.

Python has two functions designed for accepting data directly from the user:

 Python 2.x. -> input()

 Python 3.x. -> raw_input()

raw_input():
 raw_input() asks the user for a string of data and simply returns the string, the string data ended
with a newline). It can also take an argument, which is displayed as a prompt before the user
enters the data.
 print raw_input('Input your name: ')
 prints out
 Input your name:
 To assign the user's name to a variable "x" you can use following command :
 x = raw_input('Input your name: ')

input():
 In 3.x .raw_input() is renamed to input(). input() function reads a line from sys.stdin and returns it
with the trailing newline stripped.
 To assign the user's name to a variable "y" you can use following command :
 y = input('Input your name: ')

CODE:

fname = input("Input your First Name : ")

lname = input("Input your Last Name : ")

print ("Hello " + lname + " " + fname)

OUTPUT:

Input your First Name : Dany


Input your Last Name : Boon
Hello Boon Dany
PRACTICAL 2
Python list:

A list is a container which holds comma separated values (items or elements) between square brackets
where items or elements need not all have the same type. In general, we can define a list as an object that
contains multiple data items (elements). The contents of a list can be changed during program execution.
The size of a list can also change during execution, as elements are added or removed from it.

Python tuple:

A tuple is container which holds a series of comma separated values (items or elements) between
parentheses such as an (x, y) co-ordinate. Tuples are like lists, except they are immutable (i.e. you cannot
change its content once created) and can hold mix data types.

CODE:-

values = input("Input some comma seprated numbers : ")

list = values.split(",")

tuple = tuple(list)

print('List : ',list)

print('Tuple : ',tuple)

OUTPUT:-

Input some comma seprated numbers : 3,5,7,23


List : ['3', '5', '7', '23']
Tuple : ('3', '5', '7', '23')
PRACTICAL -3
To understand this example, you should have the knowledge of following Python programming topics:

 Python Operators
 Python if...else Statement

What are if...else statement in Python?

 Decision making is required when we want to execute a code only if a certain condition is
satisfied.
 The if…elif…else statement is used in Python for decision making.

Python if Statement
Syntax

 if test expression:
 statement(s)

 Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
 If the text expression is False, the statement(s) is not executed.
 In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.
 Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart

Python if...else Statement

Syntax of if...else
if test expression:

Body of if

else:

Body of else

The if..else statement evaluates test expression and will execute body of if only when test condition
is True.

If the condition is False, body of else is executed. Indentation is used to separate the blocks.

Python if..else Flowchart

A number is even if it is perfectly divisible by 2. When the number is divided by 2, we use the remainder
operator % to compute the remainder. If the remainder is not zero, the number is odd.

CODE:-
# Python program to check if the input number is odd or even.
# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.

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


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

OUTPUT:-

Enter a number: 43

43 is Odd
PRACTICAL-4
Write a python program to display table of given number.

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 language, 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.

Example

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":
  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.

Example

Using the start parameter:

for x in range(2, 6):
  print(x)
OUTPUT:-
2
3
4
5

CODE:-

''' Python program to find the

multiplication table (from 1 to 10)'''

num = 12

# To take input from the user

# num = int(input("Display multiplication table of? "))

# use for loop to iterate 10 times

for i in range(1, 11):

print(num,'x',i,'=',num*i)

OUTPUT:-

12 x 1 = 12

12 x 2 = 24

12 x 3 = 36

12 x 4 = 48

12 x 5 = 60

12 x 6 = 72

12 x 7 = 84

12 x 8 = 96

12 x 9 = 108
12 x 10 = 120

PRACTICAL-5
Decimal system is the most widely used number system. But computer only understands binary. Binary,
octal and hexadecimal number systems are closely related and we may require to convert decimal into
these systems. Decimal system is base 10 (ten symbols, 0-9, are used to represent a number) and
similarly, binary is base 2, octal is base 8 and hexadecimal is base 16.

A number with the prefix '0b' is considered binary, '0o' is considered octal and '0x' as hexadecimal. For
example:

60 = 0b11100 = 0o74 = 0x3c

# Python program to convert decimal number into binary, octal and hexadecimal number system

# Change this line for a different result

dec = 344

print("The decimal value of",dec,"is:")

print(bin(dec),"in binary.")

print(oct(dec),"in octal.")

print(hex(dec),"in hexadecimal.")

Output

The decimal value of 344 is:

0b101011000 in binary.

0o530 in octal.

0x158 in hexadecimal.

Note: To test the program, change the value of dec in the program. In this program, we have used built-in
functions bin(), oct() and hex() to convert the given decimal number into respective number systems.
These functions take an integer (in decimal) and return a string.

PRACTICAL-6
Write a program using function to get and display user information.

Python - Functions. A function is a block of organized, reusable code that is used to perform a single,
related action. ... As you already know, Pythongives you many built-in functions like print(), etc. but you
can also create your own functions. Thesefunctions are called user-defined functions.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example
def my_function():
  print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example
def my_function():
  print("Hello from a function")

my_function()

Parameters

Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses. You can add as many parameters
as you want, just separate them with a comma.

The following example has a function with one parameter (fname). When the function is called, we pass
along a first name, which is used inside the function to print the full name:

Example
def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:

Example
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Return Values

To let a function return a value, use the return statement:

Example
def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

CODE:-

def info():

a=input("plz enter name")

b=(a)

print(b)

info()

OUTPUT:-

plz enter name XYZ


XYZ
PRACTICAL-7
Python Program to Sort Words in Alphabetic Order

Here we use inbuilt functions in python library to sort words.

CODE:-
# Program to sort alphabetically the words form a string provided by the user

# change this value for a different result


my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

OUTPUT:-

The sorted words are:


Example
Hello
Is
With
an
cased
letters
this
PRACTICAL-8
Python Program to Sort Words in Alphabetic Order
Write a program to implement following String operations
Count
Find
Join
Lower

String Count:-

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

In simple words, count() method searches the substring in the given string and returns how many times
the substring is present in it.

It also takes optional parameters start and end to specify the starting and ending positions in the string
respectively.

The syntax of count() method is:

string.count(substring, start=..., end=...)

# define string
string = "Python is awesome, isn't it?"
substring = "is"

count = string.count(substring)

# print count
print("The count is:", count)

output:-

When you run the program, the output will be:


The count is: 2

String find()
The find() method returns the lowest index of the substring (if found). If not found, it returns -1.

The syntax of find() method is:

str.find(sub[, start[, end]] )

find() Parameters
The find() method takes maximum of three parameters:

 sub - It's the substring to be searched in the str string.


 start and end (optional) - substring is searched within str[start:end]

Return Value from find()


The find() method returns an integer value.

 If substring exists inside the string, it returns the lowest index where substring is found.
 If substring doesn't exist inside the string, it returns -1.

Code:-
quote = 'Let it be, let it be, let it be'

result = quote.find('let it')


print("Substring 'let it':", result)

result = quote.find('small')
print("Substring 'small ':", result)

# How to use find()


if (quote.find('be,') != -1):
print("Contains substring 'be,'")
else:
print("Doesn't contain substring")
output:-

When you run the program, the output will be:

Substring 'let it': 11

Substring 'small': -1

Contains substring 'be,'

String join()
The join() is a string method which returns a string concatenated with the elements of an iterable.

he join() method provides a flexible way to concatenate string. It concatenates each element of an iterable
(such as list, string and tuple) to the string and returns the concatenated string.

The syntax of join() is:

string.join(iterable)

join() Parameters

The join() method takes an iterable - objects capable of returning its members one at a time

Some of the example of iterables are:

 Native datatypes - List, Tuple, String, Dictionary and Set
 File objects and objects you define with an __iter__() or __getitem()__ method

Return Value from join()

The join() method returns a string concatenated with the elements of an iterable.

If the iterable contains any non-string values, it raises a TypeError exception.


CODE:-
numList = ['1', '2', '3', '4']
seperator = ', '
print(seperator.join(numList))

numTuple = ('1', '2', '3', '4')


print(seperator.join(numTuple))

s1 = 'abc'
s2 = '123'

""" Each character of s2 is concatenated to the front of s1"""


print('s1.join(s2):', s1.join(s2))

""" Each character of s1 is concatenated to the front of s2"""


print('s2.join(s1):', s2.join(s1))

OUTPUT:-

1, 2, 3, 4

1, 2, 3, 4

s1.join(s2): 1abc2abc3

s2.join(s1): a123b123c

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

The syntax of lower() method is:

string.lower()

String lower() Parameters()


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

Return value from String lower()

The lower() method returns the lowercased string from the given string. It converts all uppercase
characters to lowercase.

If no uppercase characters exist, it returns the original string.


CODE:-

# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())

# string with numbers


# all alphabets whould be lowercase
string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())

OUTPUT:-

this should be lowercase!


th!s sh0uld b3 l0w3rcas3!
PRACTICAL-9

Create the dictionary using python.

How to create a dictionary?

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.

An item has a key and the corresponding value expressed as a pair, key: value.

While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.

How to access elements from a dictionary?

While indexing is used with other container types to access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method.

The difference while using get() is that it returns None instead of KeyError, if the key is not found.

CODE:-
my_dict = {'name':'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
# my_dict['address']

OUTPUT:-

Jack
26

How to change or add elements in a dictionary?


Dictionary are mutable. We can add new items or change the value of existing items using assignment
operator.

If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

CODE:-
my_dict = {'name':'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

OUTPUT:-
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
PRACTICAL-10
Using python create the calculator.

Basic calculator program using Python


Create a simple calculator which can perform basic arithmetic operations like addition, subtraction,
multiplication or division depending upon the user input.
Approach :
 User choose the desired operation. Options 1, 2, 3 and 4 are valid.

 Two numbers are taken and an if…elif…else branching is used to execute a particular section.

 Using functions add(), subtract(), multiply() and divide() evaluate respective operations.

CODE:-

Please select operation -


1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 : 1
Enter first number : 20
Enter second number : 13
20 + 13 = 33

# Python program for simple calculator


  
# Function to add two numbers 
def add(num1, num2):
    return num1 + num2
  
# Function to subtract two numbers 
def subtract(num1, num2):
    return num1 - num2
  
# Function to multiply two numbers
def multiply(num1, num2):
    return num1 * num2
  
# Function to divide two numbers
def divide(num1, num2):
    return num1 / num2
  
print("Please select operation -\n" \
        "1. Add\n" \
        "2. Subtract\n" \
        "3. Multiply\n" \
        "4. Divide\n")
  
  
# Take input from the user 
select = input("Select operations form 1, 2, 3, 4 :")
  
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
  
if select == '1':
    print(number_1, "+", number_2, "=",
                    add(number_1, number_2))
  
elif select == '2':
    print(number_1, "-", number_2, "=",
                    subtract(number_1, number_2))
  
elif select == '3':
    print(number_1, "*", number_2, "=",
                    multiply(number_1, number_2))
  
elif select == '4':
    print(number_1, "/", number_2, "=",
                    divide(number_1, number_2))
else:
    print("Invalid input")

OUTPUT:-

Please select operation -


1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 : 1
Enter first number : 15
Enter second number : 14
15 + 14 = 29

You might also like