This page gives a bunch sample programs for a beginner to Python programming. The example scenarios have been chosen to illustrate various core programming concepts illustrated through Python.
# Tuples
values = (101, 201, -5)
print(type(values), values)
for i in range(len(values)):
print(values[i])
values = (501, 1000, 2000)
print(values)
# Error in below statement. Tuple does not support item assignment
#values[1] = 234
# Creating a tuple
fruits = ("apple", "banana", "cherry", "orange")
# Accessing elements
print("The first fruit is:", fruits[0])
print("The last fruit is:", fruits[-1])
# Slicing a tuple
print("The first two fruits are:", fruits[:2])
# Checking if an element exists
if "banana" in fruits:
print("Banana is present in the tuple.")
# Concatenating tuples
numbers = (1, 2, 3)
combined = fruits + numbers
print("Combined tuple:", combined)
# Counting occurrences of an element
count = fruits.count("apple")
print("Count of apples:", count)
# Finding the index of an element
index = fruits.index("cherry")
print("Index of cherry:", index)
# Creating a tuple with a single element
single_tuple = ("apple",)
print("Single tuple:", single_tuple,type(single_tuple),type(single_tuple[0]))
single_element_list = [5,]
print(single_element_list,type(single_element_list))
# Create a dictionary object
# Key:Value pairs are separated with a comma and enclosed within {}
mydict = {
"name": "Ram",
"age": 25,
"city": "Bangalore"
}
# Access Elements and type()
print(type(mydict))
# Print elements (keys and values) of a dictionary
print(mydict)
# Access Value using key
print(mydict["name"])
# Get all keys
print(mydict.keys())
# Get all values
print(mydict.values())
# Modify values in a dictionary
mydict["age"]=30
print(mydict)
# Adding new key value pairs
mydict["marital status"] = "Unmarried"
print(mydict)
# Removing key value pairs
del mydict["city"]
print(mydict)
# Check for presence of a key
if "age" in mydict:
print("age is a key")
if "address" in mydict:
print("address is a key")
else:
print("address is not a key")
# Going through the list of key-value pairs
for key,value in mydict.items():
print(key,value)
# Simple usecase for a dictionary
# Create a Faculty telephone dir
faculty_dir = {
"Ram": 1234,
"Rahim": 5678,
"Robert": 3456
}
namestr = input("Enter name of faculty")
if (namestr in faculty_dir):
print(namestr, faculty_dir[namestr])
else:
print(namestr," is not found in the directory")
# del keyword deletes objects
a = 5
print(a,type(a))
del a
print(a,type(a))
# Python strings
str = "ABCDEF"
for i in str:
print(i)
str = "XYZ"
for i in str:
print(i)
# Error. Cannot edit elements within a string
#str[2] = 'A'