0% found this document useful (0 votes)
7 views15 pages

Intro To Pythin Part 3

This document is an introduction to Python programming, covering file handling, random number generation, and data types. It explains how to open, read, write, and close files, as well as generate random numbers and utilize lists and dictionaries. Each section includes examples and practice exercises to reinforce learning.

Uploaded by

Swadhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Intro To Pythin Part 3

This document is an introduction to Python programming, covering file handling, random number generation, and data types. It explains how to open, read, write, and close files, as well as generate random numbers and utilize lists and dictionaries. Each section includes examples and practice exercises to reinforce learning.

Uploaded by

Swadhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Introduction to Python

Programming
Part 3

Shrihari A
IIT Guwahati

Daksh Gurukul, IIT Guwahati 1


Agenda
• File Handling
o Opening Files
o Reading from files
o Writing to files
o Closing files
• Random Number Generation
o Random Integers
o Random Floats
o Random Choice
o Random Shuffle
• Data Types
o Numeric
o Strings
o Tuple
o List
o Dictionary

Daksh Gurukul, IIT Guwahati 2


File Handling
File handling is a crucial skill in programming, allowing you to interact with files on your computer,
store data persistently, and work with external information. Let's dive into the world of file handling in
Python.

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.

Daksh Gurukul, IIT Guwahati 3


File Handling
Reading from Files
• The read() Method: Reads the file’s entire contents as a single string.
• file = open("my_file.txt", "r")
• content = file.read()
• print(content)
• file.close()
• The readline() Method: Reads a single line from the file.
• file = open("my_file.txt", "r")
• line1 = file.readline()
• line2 = file.readline()
• print(line1, line2)
• file.close()
• The readlines() Method: Reads all lines of the file into a list.
• file = open("my_file.txt", "r")
• lines = file.readlines()
• for line in lines:
• print(line, end="")
• file.close()

Daksh Gurukul, IIT Guwahati 4


File Handling
Writing to Files
• The write() Method: Writes a string to the file.
• file = open("my_file.txt", "w")
• file.write("This is some new text.")
• file.close()
• The writelines() Method: Writes a list of strings to the
file.
• file = open("my_file.txt", "w")
• lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
• file.writelines(lines)
• file.close()

Daksh Gurukul, IIT Guwahati 5


File Handling
Closing Files
• The close() Method: It's essential to close files after
you're done using them to release resources and prevent
potential errors.
• file = open("my_file.txt", "r")
• # ... work with the file ...
• file.close()

Daksh Gurukul, IIT Guwahati 6


File Handling
Example: A Simple File Writer
Practice Time!
Let's create a program that writes user
input to a file: Try these exercises:
filename = input("Enter filename: ") • Write a program that reads a
file = open(filename, "w")
text file and counts the number
while True: of words in it.
line = input("Enter text (or 'quit' to
exit): ") • Write a program that creates a
if line == "quit":
break
new file and writes a list of
file.write(line + "\n") your favourite hobbies to it.
file.close()
print("File saved successfully!")

Daksh Gurukul, IIT Guwahati 7


Random Number Generation
Random number generation is a fundamental concept in programming, used for
everything from creating games to simulating real-world events. Let's explore how to
generate random numbers in Python.
The random Module
• Importing the Module: The random module provides functions for generating
random numbers. You need to import it first.
• import random

Generating Random Integers


• The randint() Function: Generates a random integer within a specified range
(inclusive).
• random_number = random.randint(1, 10) # Generates a random number between 1 and 10
• print(random_number)

Daksh Gurukul, IIT Guwahati 8


Random Number Generation
Generating Random Floats
• The random() Function: Generates a random float between 0.0
(inclusive) and 1.0 (exclusive).
• random_float = random.random() # Generates a random float between
0.0 and 1.0
• print(random_float)
• The uniform() Function: Generates a random float within a
specified range.
• random_float = random.uniform(2.5, 7.5) # Generates a random
float between 2.5 and 7.5
• print(random_float)

Daksh Gurukul, IIT Guwahati 9


Random Number Generation
Choosing Random Elements
• The choice() Function: Selects a random element from a
sequence (list, tuple, or string).
• colors = ["red", "green", "blue", "yellow"]
• random_color = random.choice(colors)
• print(random_color)
• The sample() Function: Returns a list of k unique random
elements from a sequence.
• numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
• random_sample = random.sample(numbers, 3) # Chooses 3 unique
random numbers
• print(random_sample)

Daksh Gurukul, IIT Guwahati 10


Random Number Generation

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)

Daksh Gurukul, IIT Guwahati 11


Random Number Generation
Example: A Simple Dice Roller
Let's create a program that simulates rolling a six-sided die:
import random

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")

You create a list by placing items inside square • Removing Items:


brackets [], separated by commas. Use the remove() method to
• fruits = ["apple", "banana", "cherry"]
remove a specific item.
• Accessing List Items: • fruits.remove("banana")

You can access items in a list using their index


(starting from 0).
• print(fruits[0]) # Output: apple
Daksh Gurukul, IIT Guwahati 13
Data Types and Structures
Dictionaries: Key-Value Pairs
• What is a Dictionary?
A dictionary is a collection of key-value pairs, similar to a real dictionary
where you look up a word (key) to find its definition (value).
• Creating a Dictionary:
You create a dictionary using curly braces {}.
• student = {"name": "Alice", "age": 20, "major": "Computer Science"}
• Accessing Values:
You can access values using their keys.
print(student["name"]) # Output: Alice

Daksh Gurukul, IIT Guwahati 14


Data Types and Structures
Example: Using Lists and
Practice Time!
Dictionaries
Try these exercises to reinforce
Let’s create a simple program that stores your understanding:
student information using a list of dictionaries:
• Create a list of your favourite
students = [
{"name": "Alice", "age": 20}, movies and print each one.
{"name": "Bob", "age": 22},
{"name": "Charlie", "age": 21} • Create a dictionary to store
] information about your
for student in students: favourite book (title, author,
print(student["name"], "is", year) and print it.
student["age"], "years old.")

Daksh Gurukul, IIT Guwahati 15

You might also like