Intro To Pythin Part 3
Intro To Pythin Part 3
Programming
Part 3
Shrihari A
IIT Guwahati
Opening Files
• The open() Function: The open() function is your gateway to working with files. It takes two
arguments: the filename and the mode.
• file = open("my_file.txt", "r") # Open for reading
• File Modes:
o "r": Read mode (default). Opens the file for reading only.
o "w": Write mode. Creates a new file (or overwrites an existing one) for writing.
o "a": Append mode. Opens the file for appending data to the end.
o "x": Create mode. Creates a new file, but raises an error if the file already exists.
o "b": Binary mode. Used for working with binary files like images or audio.
o "t": Text mode (default). Used for working with text files.
Shuffling Sequences
• The shuffle() Function: Shuffles the elements of a
sequence in place.
• cards = ["Ace", "King", "Queen", "Jack", "10", "9", "8",
"7", "6", "5", "4", "3", "2"]
• random.shuffle(cards)
• print(cards)
roll = random.randint(1, 6)
print("You rolled a", roll)
Practice Time!
Try these exercises:
• Write a program that generates a random password of length 8 using lowercase letters,
uppercase letters, numbers, and symbols.
• Write a program that simulates flipping a coin 10 times and counts the number of
heads and tails.
Daksh Gurukul, IIT Guwahati 12
Data Types and Structures
Lists: Storing Multiple Items
• What is a List? Adding and Removing Items
A list is a collection of items that can be of • Adding Items:
different types. You can think of it as a shopping Use the append() method to add
list where you can store multiple items. an item to the end of the list.
• Creating a List: • fruits.append("orange")