Python Assignment
Python Assignment
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:
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:
OUTPUT:
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:-
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)
OUTPUT:-
Python Operators
Python if...else Statement
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.
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.
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.
OUTPUT:-
Enter a number: 43
43 is Odd
PRACTICAL-4
Write a python program to display table of given number.
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
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Looping Through a String
Example
for x in "banana":
print(x)
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
for x in range(2, 6):
print(x)
OUTPUT:-
2
3
4
5
CODE:-
num = 12
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:
# Python program to convert decimal number into binary, octal and hexadecimal number system
dec = 344
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")
Output
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.
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Parameters
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")
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
CODE:-
def info():
b=(a)
print(b)
info()
OUTPUT:-
CODE:-
# Program to sort alphabetically the words form a string provided by the user
OUTPUT:-
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.
# define string
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# print count
print("The count is:", count)
output:-
String find()
The find() method returns the lowest index of the substring (if found). If not found, it returns -1.
find() Parameters
The find() method takes maximum of three parameters:
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('small')
print("Substring 'small ':", result)
Substring 'small': -1
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.
string.join(iterable)
join() Parameters
The join() method takes an iterable - objects capable of returning its members one at a time
Native datatypes - List, Tuple, String, Dictionary and Set
File objects and objects you define with an __iter__() or __getitem()__ method
The join() method returns a string concatenated with the elements of an iterable.
s1 = 'abc'
s2 = '123'
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.
string.lower()
The lower() method returns the lowercased string from the given string. It converts all uppercase
characters to lowercase.
# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())
OUTPUT:-
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.
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'))
OUTPUT:-
Jack
26
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
# add item
my_dict['address'] = 'Downtown'
OUTPUT:-
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
PRACTICAL-10
Using python create the calculator.
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:-
OUTPUT:-