CS 1 Ans - Introduction To Python
CS 1 Ans - Introduction To Python
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
help('modules')
Options 1
import datetime
x = datetime.datetime.now()
print(x)
Options 2
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
Sample Output :
r = 1.1
Area = 3.8013271108436504
from math import pi
r = float(input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is:
" + str(pi * r**2))
4.Write a Python program which accepts the user's first and last name and
print them in reverse order with a space between them
fname = input("Input your First Name : ")
lname = input("Input your Last Name : ")
print ("Hello " + lname + " " + fname)
Sample data : 3, 5, 7, 23
Output :
List : ['3', ' 5', ' 7', ' 23']
Tuple : ('3', ' 5', ' 7', ' 23')
The split() method splits a string into a list.
Syntax
string.split(separator, maxsplit)
list1 = values.split(",")
tuple1 = tuple(list1)
print('List : ',list1)
Other examples -1
x = txt.split(", ")
print(x)
Other examples -2
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
Other examples -3
txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter to 1, will return a list with 2
elements!
x = txt.split("#", 1)
print(x)
6.Write a Python program to accept a filename from the user and print the
extension of that.
str() displays today’s date in a way that the user can understand the date
and time.
repr() prints “official” representation of a date-time object (means using the
“official” string representation we can reconstruct the object).
import datetime
today = datetime.datetime.now()
print (today)
print (str(today))
print (repr(today))
7.Write a Python program to display the first and last colors from the following
list.
color_list = ["Red","Green","White" ,"Black"]
8.Write a Python program that accepts an integer (n) and computes the value
of n+nn+nnn.
Sample value of n is 5
Expected Result : 615
a = int(input("Input an integer : "))
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
print (n1+n2+n3)
9.Write a Python program to get the volume of a sphere with radius 6.
pi = 3.1415926535897931
r= 6.0
V= 4.0/3.0*pi* r**3
print('The volume of the sphere is: ',V)
10. Write a Python program to convert seconds to day, hour, minutes and
seconds.
time = float(input("Input time in seconds: "))
day = time // (24 * 3600)
time = time % (24 * 3600)
hour = time // 3600
time %= 3600
minutes = time // 60
time %= 60
seconds = time
print("d:h:m:s-> %d days :%d hours:%d minutes:%d seconds" %
(day, hour, minutes, seconds))