0% found this document useful (0 votes)
12 views11 pages

Python Programming Course Overview

It is python question and and their answers for revision for exam and college record book written ..

Uploaded by

coledi2951
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)
12 views11 pages

Python Programming Course Overview

It is python question and and their answers for revision for exam and college record book written ..

Uploaded by

coledi2951
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

Name of Course [Link].

DS FY
Semester I Semester
Name of Subject Programming with python
Subject Code SDTSMT1102

1. WAP to demonstrate the variables in python

2. WAP to demonstrate string operations.

3. WAP to demonstrate the concept of data type conversion.

4. WAP to demonstrate the operators in python.

5. WAP to demonstrate the decision making statements in python.

6. WAP to demonstrate the control statements in python.

7. WAP to demonstrate the Looping statements in python.

8. WAP to demonstrate List data type.

9. WAP to demonstrate Dictionary data type.

10. WAP to demonstrate Set data type.

11. WAP to demonstrate the Input and Output Formatting

12. WAP to demonstrate function and types of function argument

13. WAP to demonstrate the import statements in python.


1] WAP to demonstrate the variables in python

Python Variables are the containers that stores the values which is used during the
program and can be changed at the time of execution.

Followings are the rules of variable declaration.


- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _).
- Variable names are case-sensitive (name, Name and NAME are three
different variables).
- The reserved words(keywords) cannot be used naming the variable.

CODE:
# Demonstrating variables in Python

# Integer
num = 10
print("Integer:", num)

# Float
pi = 3.14
print("Float:", pi)

# String
name = "Alice"
print("String:", name)

# Boolean
is_active = True
print("Boolean:", is_active)

# List
fruits = ["apple", "banana", "cherry"]
print("List:", fruits)

# Tuple
coordinates = (10, 20)
print("Tuple:", coordinates)

# Dictionary
person = {"name": "John", "age": 25}
print("Dictionary:", person)

# Set
unique_numbers = {1, 2, 3, 4}
print("Set:", unique_numbers)

OUTPUT:
Integer: 10
Float: 3.14
String: Alice
Boolean: True
List: ['apple', 'banana', 'cherry']
Tuple: (10, 20)
Dictionary: {'name': 'John', 'age': 25}
Set: {1, 2, 3, 4}
2] WAP to demonstrate string operations.

In Python, a string is a sequence of characters used to store and represent text-based


data.

It is one of the most important and commonly used data types in programming.

A string in Python is an immutable, ordered collection of Unicode characters. Being


immutable means once a string is created, it cannot be changed.

➢ Creating a String:
Strings in Python can be created using single quotes or double quotes or even triple
quotes.

CODE:
# Creating string using single quote.
String1= ‘Welcome to python programming.’
print(“String using single Quote: ”,String1)

# Creating string using double quote.


String1 = "My name is SP"
print("\n String using Double Quotes: ",String1)

# creating string using triple quote.


String1= ‘’’ My subject is python. ‘’’’
print("\n String using Triple Quotes: ",String1)

# String with triple quote allow multiple lines.


String1 = '''
Keep
Learning
keep
Coding
'''
print("\n Creating a multiline String: ",String1)
OUTPUT: -

String using Single Quotes: Welcome to Python Programming


String using Double Quotes: My name is SP
String using Triple Quotes: My subject is python Creating a
multiline String:
Keep
learning
Keep
coding

Accessing character from String:

CODE:
# Program to Access characters of String String1 = "HELLOCOCSITLATUR"
print("Initial String:",String1)

# Printing First character


print("\n First character of String is: ",String1[0])

# Printing Last character


print("\n Last character of String is: ",String1[-1])

OUTPUT:
Initial String: HELLOCOCSITLATUR

First character of String is: H

Last character of String is: R


Modifying String:-
Python strings are immutable Followings methods are used to modify the string:

❖ len(a) – returns the length of the string.

❖ [Link]() – converts all characters to uppercase.

❖ [Link]() – converts all characters to lowercase.

❖ [Link]() – capitalizes only the first letter of the string.

❖ [Link]() – capitalizes the first letter of each word.

❖ [Link]() – swaps uppercase to lowercase and vice versa.

❖ [Link]('o') – counts how many times 'o' appears.

❖ [Link]('_') – counts how many times '_' appears.

❖ [Link]('Name') – returns position of 'Name', or -1 if not found.

❖ [Link]('T') – returns position of 'T', or -1 if not found.

❖ [Link]('on') – returns index of first occurrence of 'on', error if not found.

❖ [Link]('is') – splits string at each 'is', returns list of parts.

❖ [Link]('dis') – splits at 'dis', returns list (no change if not found).

❖ [Link]('Y') – checks if string starts with 'Y', returns True/False.

❖ [Link]('.') – checks if string ends with '.', returns True/False.

❖ "."*30 – repeats the '.' character 30 times.

❖ [Link]('You', 'Our') – replaces 'Your' with 'Our' in string.

❖ " ".join(a) – adds a space between every character.

❖ "+" .join(a) – adds a plus between every character.

❖ b + c – joins two strings, called concatenation.


CODE:-
# Program to demonstrate the methods for modifying the string

# initializing string

a = "keep Learning and keep Coding"

print("\n My string is:",a)

print("\n Length of string",len(a))

# Modifying string

print("\n String in uppercase:",[Link]())

print("\n String in lowercase:",[Link]())

print("\n String in capitalized form:",[Link]())

print("\n String in title form:",[Link]())

print("\n swaping cases:",[Link]())

print("\n Counting char o:",[Link]('o'))

print("\n Finding the position in string:",[Link]('Learning'))

print("\n Finding the letters on in string:",[Link]('C'))

print("\n Spliting the string",[Link]('and'))

print("\n Checking is string starts with:",[Link]('k'))

print("\n Checking is string ends with:",[Link]('.'))

print(" ",' _ '*10)

print("\n Replacing the word:",[Link]('and',','))

print("\n whitespace between every char:"," ".join(a))

print("\n whitespace + between every char:",".".join(a))

b = 'SM' c = ' Patel' print("\n String concatinating:",b+c)


OUTPUT:

My string is: keep Learning and keep Coding

Length of string 29

String in uppercase: KEEP LEARNING AND KEEP CODING

String in lowercase: keep learning and keep coding

String in capitalized form: Keep learning and keep coding

String in title form: Keep Learning And Keep Coding


swaping cases: KEEP lEARNING AND KEEP cODING Counting char o: 1

Finding the position in string: 5

Finding the letters on in string: 23

Spliting the string ['keep Learning ', ' keep Coding']

Checking is string starts with: True


Checking is string ends with: False
_ _ _ _ _ _ _ _ _ _

Replacing the word: keep Learning , keep Coding

whitespace between every char: k e e p L e a r n i n g a n d k e


e p C o d i n g

whitespace + between every char: k.e.e.p. .L.e.a.r.n.i.n.g. .a.n.d.


.k.e.e.p. .C.o.d.i.n.g
String concatinating: SM Patel
3] WAP to demonstrate the concept of data type conversion.
Type conversion is also known as type casting
Type Casting is the method to convert the data type of the variable into another data
type in order to the operation required to be performed by users.
There can be two types of Type Casting in Python
– 1. Implicit Type Casting
2. Explicit Type Casting

1] Implicit Type Casting


In this, methods, Python converts data type into another data type automatically. In
this process, users don’t have to involve in this process.
In this type data can be loss.

CODE:

# Program for implicit type Casting

# a declaring
int a = 7

# b declaring
float b = 3.0

# c automatically convert into float


c = a + b

print(c)

print(type(a))

print(type(b))

print(type(c))

OUTPUT:
10.0
<class 'int'>
<class 'float'>
<class 'float'>
2] Explicit Type Casting
In this method, Python need user involvement to convert the variable from one data
type into another data type in order to the operation required.
Mainly in type casting can be done with following function:

 int() → Converts to integer

 float() → Converts to float

 str() → Converts to string

 list() → Converts to list

 tuple() → Converts to tuple

 set() → Converts to set

CODE:

x = "100" # string

y = int(x) # convert string to


integer print("Value of x in string
form:",x) print(type(x)) print("Value
of x is converted into integer",y)
print(type(y)) print(y + 10)

# This statement will throw an error because we are


trying to add int and str without conversion

a = 5

print(a + "0")

OUTPUT:
Value of x in string form: 100
<class 'str'>
Value of x is converted into integer 100
<class 'int'>
110
50
Prepared by, Ms. Safura .M. Patel
COCSIT, Latur

Common questions

Powered by AI

Control statements in Python direct the flow of execution using constructs like loops (`for`, `while`) and conditionals (`if`, `elif`, `else`). They execute repeatedly or conditionally based on the logic designed by the programmer . Decision-making statements are a type of control statement focused on evaluating conditions to decide which code block is executed. Thus, control statements manage flow, while decision-making is about conditions and choices, influencing execution paths by assessing logical expressions .

Python loops, such as `for` and `while`, automate repetitive tasks and iterate through data structures. `for` loops allow iteration over iterable objects like lists and dictionaries, executing block commands for each element. For example, iterating through a list `fruits = ['apple', 'banana', 'cherry']` prints each element in sequence . `while` loops continue executing as long as a condition is true. These constructs enable efficient data traversal and manipulation, reducing redundancy in repetitive operations.

The set data type in Python is designed for storing unique elements, inherently disallowing duplicates, which simplifies operations like membership testing, ensuring efficient data storage and retrieval. Sets support mathematical operations like union and intersection, aiding in distinct data management tasks, such as eliminating duplicates from a list and implementing fast membership tests due to their hashed storage mechanism . Their uniqueness constraint drives efficient identity and integrity management in data-centric applications.

Python variables can hold different data types such as integers, floats, strings, booleans, lists, tuples, dictionaries, and sets, which define the kind of data the variable can store . The rules for naming variables include starting with a letter or underscore, not beginning with a number, using only alphanumeric characters and underscores, and being case-sensitive. Reserved keywords cannot be used as variable names .

Python strings are immutable, meaning once a string is created, its characters cannot be changed. This immutability affects string operations by requiring methods that create new strings rather than modifying the original. For instance, methods like `upper()`, `replace()`, or `split()` return new strings rather than altering the existing one, preserving the original string's state .

Import statements in Python facilitate modular programming by allowing code from one module to be used in another, thus managing dependencies efficiently. They enable reuse of code libraries, enhancing functionality without redundancy. For instance, importing math functions using `import math` allows access to advanced mathematical operations, fostering code efficiency and maintainability without manually implementing such features . Thus, they are vital in integrating external resources and structuring complex programs.

The `print()` function in Python is essential for visualizing data outputs across different data types, supporting integers, strings, lists, dictionaries, and control structures through formatted output. It reveals the content and structure of data, as seen in examples like printing a dictionary `{'name': 'John', 'age': 25}` which outputs in a readable format . This capability is crucial for debugging and presentational purposes in programming environments.

Python string operations can transform text formats using methods like `upper()`, `title()`, and `replace()`. For instance, to convert 'keep Learning and keep Coding' into uppercase, use `a.upper()` resulting in 'KEEP LEARNING AND KEEP CODING'. To title case, apply `a.title()`, yielding 'Keep Learning And Keep Coding'. To replace 'and' with ',', use `a.replace('and', ',')` yielding 'keep Learning, keep Coding' . These transformations assist in standardizing and enhancing readability of textual data.

String splitting methods in Python, such as `split()`, facilitate text parsing and manipulation by breaking down a string into a list of components based on a specified delimiter. This is useful for data extraction and analysis in text processing tasks. For example, `split('and')` divides 'keep Learning and keep Coding' into parts ['keep Learning', 'keep Coding'], allowing for targeted operations on specific segments . These methods enable efficient data parsing and restructuring in programming tasks.

Implicit type casting in Python occurs automatically when Python converts one data type to another without user intervention, often when an operation involves different types. For example, adding an integer and a float results in a float . Explicit type casting requires the user to convert data types manually using functions like `int()`, `float()`, `str()`, etc.; for instance, converting a string '100' to an integer with `int('100')` .

You might also like