Python Basics Exercises

Exercises: Python Basics                                                                                    Go to editor!!!


  • Print a string

print "I am getting started"
  • Arithmetic Operators

expression=2+3*6/2
print expression

  • Get user input

 fname = raw_input("Input your First Name : ")  #use Input()in python 3.X
lname = raw_input("Input your Last Name : ")
print ("Hello  " + lname + " " + fname)

  • String functions

str = "this is string example....wow!!!";
print str.capitalize()
print str.upper()
print str.lower()
print len(str)
print str.replace(" is", " was")
print str.split( )

  • List Functions

 ls = [32,12,43,23,55]
print len(ls)
ls.sort();
print ls
ls.reverse();
print ls
ls.insert(1,22);
print ls
print ls.count(12)

  • Tuple functions

tp = (32,12,43,23,55)
print len(tp)
print max(tp)
print min(tp)
print list(tp) # conversion to list
tp.sort(); #Tuple cannot be sorted

  • Dictionary functions

dict = {'Name': 'RDJ', 'Age': 50}

print "Value : %s" %  dict.get('Age')
print "Value : %s" %  dict.get('Education', "Never")

print "Value : %s" %  dict.has_key('Age')
print dict.keys()
print dict.items()
 

  • Datetime example

from datetime import date
min_date = date(2017, 10, 16)
max_date = date(2017, 10, 31)
delta = max_date - min_date
print(delta.days)



  • Conditionals

# Checking whether a number is positive or negative 

numb=raw_input("Enter a number:")
numb=int(numb)
if numb==abs(numb):       # comparing entered value with it's absolute value
  print "You have entered a positive number"
else:
  print "You have entered a negative number"

#Judging length of a word

word=raw_input("Enter a word:")
if len(word)<=4:       
  print "Word is too small"
elif len(word)>=9:
  print "Word is too big"
else:

  print "Word is of optimum length"


FUNCTIONS:
  • Compute birth year based on user's age

print "Birth year calculator"
import datetime
now = datetime.datetime.now()
year=now.year
age=int(input ("enter your age:"))
year_born=year-age
print year_born



FUNCTIONS WITH LOOPS:
  • Count occurrence of a list member

def list_count(nums):
  count = 0 
  for num in nums:
    if num == 10:
      count = count + 1

  return count

print(list_count([10, 24, 60, 27, 44,10]))

  • Odd number generator

 print "Odd number generator"

limit=input("Enter the upper limit:")

odd_list=[]


def odd(x):
 
    for i in range(0,x):
  
          if i%2!=0:
    
            odd_list.append(i)

    return odd_list

print odd(limit)



MORE TO COME ❤❤❤


Comments