[go: up one dir, main page]

0% found this document useful (0 votes)
37 views7 pages

3

Uploaded by

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

3

Uploaded by

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

1, Introduction to python

Python is a popular and versatile programming language that has gained widespread
adoption in various domains. Let’s explore some key aspects of Python:

1. What is Python?
o Python was created by Guido van Rossum and released in 1991.
o It is used for:
 Web development (server-side)
 Software development
 Mathematics
 System scripting
2. What Can Python Do?
o Python can be used to:
 Create web applications on servers.
 Build workflows alongside software.
 Connect to database systems.
 Read and modify files.
 Handle big data and perform complex mathematics.
 Rapidly prototype or develop production-ready software.
3. Why Python?
o Python has several advantages:
 Platform Independence: It works on different platforms (Windows,
Mac, Linux, Raspberry Pi, etc.).
 Readable Syntax: Python’s syntax is simple and similar to the English
language.
 Concise Code: Developers can write programs with fewer lines
compared to other languages.
 Interpreted Execution: Code can be executed as soon as it’s written,
allowing quick prototyping.
 Versatility: Python supports procedural, object-oriented, and
functional programming styles.
4. Python Versions:
o The most recent major version is Python 3, which we’ll use in this tutorial.
o Python 2, although not actively updated, is still in use for legacy systems.
5. Syntax Comparison:
o Python emphasizes readability:
 New lines complete commands (no semicolons or parentheses).
 Indentation defines scope (loops, functions, classes).
 No curly braces for scoping (unlike other languages).
6. Example:

print("Hello, World!")

1
2. Introduction to python Data Types

1. Numeric Data Types:


o Integers (int): Represent whole numbers (positive or negative) without
fractions or decimals. There’s no limit to the length of an integer value.
o Floats (float): Represent real numbers with a decimal point. Optionally,
scientific notation (e.g., 1.23e-4) can be used.
o Complex Numbers (complex): Represent numbers with both a real part and
an imaginary part (e.g., 2 + 3j).
2. Sequence Data Types:
o Strings (str): Sequences of characters (letters, numbers, symbols). Enclosed in
single or double quotes.
o Lists: Ordered collections of elements (mutable). Lists can contain different
data types.
o Tuples: Similar to lists but immutable (cannot be modified after creation).
o Ranges: Represents an immutable sequence of numbers (often used for loops).
3. Mapping Data Types:
o Dictionaries (dict): Key-value pairs. Keys must be unique, and values can be
of any data type.
4. Set Data Types:
o Sets: Unordered collections of unique elements. Useful for removing
duplicates and performing set operations (union, intersection, etc.).
5. Boolean Data Type:
o Booleans (bool): Represent truth values (True or False). Used for logical
operations.
6. Binary Data Types:
o Bytes: Immutable sequences of bytes (used for raw binary data).
o Bytearray: Mutable version of bytes.
o Memoryview: Provides a view of the memory of an object (used for efficient
manipulation of large data).
7. Special Value:
o None: Represents the absence of a value or a null value.

___________________________________________________________________________
3. Program to accept two numbers and swap them with each other

x = int(input("Enter value of x: ")) # Input from user


y = int(input("Enter value of y: ")) # Input from user

x, y = y, x

2
print("x =", x)
print("y =", y)

4. Program to accept three integers and print the largest

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print(f"The largest number is {largest}")

5. Program to accept an integer and find out whether it is even or


odd
# Python program to check if the input number is odd or even
num = int(input("Enter a number: ")) # Input from user

# Check if the remainder when divided by 2 is zero


if (num % 2) == 0:
print(f"{num} is **Even**")
else:
print(f"{num} is **Odd**")

6. Program to accept an integer and find out whether it is prime or


Not
from math import sqrt

num = int(input("Enter a number: "))

3
prime_flag = 0

if num > 1:
for i in range(2, int(sqrt(num)) + 1):
if (num % i) == 0:
prime_flag = 1
break

if prime_flag == 0:
print("True")
else:
print("False")

7. Program to calculate and print the sums of even and odd integers
of the first n natural numbers

n = int(input("Enter a positive integer (n): "))

even_total = sum(range(2, n + 1, 2))


odd_total = sum(range(1, n + 1, 2))

print(f"The sum of even numbers from 1 to {n} = {even_total}")


print(f"The sum of odd numbers from 1 to {n} = {odd_total}")

8. Program to display the following output using nested for loops


#
##
###
####
#####

for i in range(1, 6):


for j in range(i):

4
print("#", end="")
print()

9. Program to input a string and check if it is a palindrome string

using a string slice

user_input = input("Enter a string: ")

cleaned_input = user_input.replace(" ", "").lower()

if cleaned_input == cleaned_input[::-1]:
print(f"{user_input} is a palindrome!")
else:
print(f"{user_input} is not a palindrome.")

10. Program to check if the highest element of the list lies in the first half of the list or in
second half

def find_max_halves(arr):
n = len(arr)
mid = n // 2
max_first = max(arr[:mid])
if n % 2 == 1:
max_first = max(max_first, arr[mid])

max_second = max(arr[mid:])

print(f"The maximum element in the first half: {max_first}")


print(f"The maximum element in the second half: {max_second}")

arr = [1, 12, 14, 5]


find_max_halves(arr)

5
11. Program to accept a tuple of ten integers. After accepting whole tuple replace the
value of 3rd element with 101

def replace_third_element(tup, new_value):


lst = list(tup)
lst[2] = new_value
new_tuple = tuple(lst)
return new_tuple
original_tuple = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
new_value = 101
updated_tuple = replace_third_element(original_tuple, new_value)

print(f"Original tuple: {original_tuple}")


print(f"Updated tuple: {updated_tuple}")

12. Program to create a dictionary containing names of competition


winner students as keys and the numbers of their wins as values Example – ‘Aradhya’:3
def create_winner_dictionary():
n = int(input("Enter the number of students: "))
winners = {}

for _ in range(n):
student_name = input("Enter student name: ")
wins = int(input(f"Enter the number of wins for
{student_name}: "))
winners[student_name] = wins

return winners
competition_winners = create_winner_dictionary()
print("Competition Winners:")
for student, wins in competition_winners.items():

6
print(f"{student}: {wins} wins")

You might also like