0% found this document useful (0 votes)
6 views3 pages

Python Basics: Programs and Functions

Uploaded by

Aditya Sharma
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)
6 views3 pages

Python Basics: Programs and Functions

Uploaded by

Aditya Sharma
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

BASIC PROGRAMS

a, b = 5, 10 a, b = b, a print(a, b)
name = input("Enter name: ") age = input("Enter age: ") print(f"My name
is {name} and I am {age} years old.")
length = 5 breadth = 3 area = length * breadth perimeter = 2 * (length +
breadth) print(area, perimeter)
p, r, t = 1000, 5, 2 si = (p * r * t) / 100 print(si)
c = float(input("Enter temperature in Celsius: ")) f = (c * 9/5) + 32
print(f"Fahrenheit: {f}")
name, age, city = "John", 25, "New York" print(name, age, city)
a, b, c, d = 5, 5.5, "Hello", True print(type(a), type(b), type(c),
type(d))
a, b, c = 5, 9, 3 print(max(a, b, c))
p, r, t = 1000, 5, 2 ci = p * (1 + r/100) ** t - p print(ci)
a, b = 10, 20 temp = a a = b b = temp print(a, b)

STRINGS
s = "hello" print(s[::-1])
s = "hello world" vowels = sum(1 for i in s if i in 'aeiouAEIOU')
consonants = len([i for i in s if [Link]()]) - vowels print(vowels,
consonants)
s = "madam" print("Palindrome" if s == s[::-1] else "Not Palindrome")
s = "Hello" print([Link]()) print([Link]())
s = "hello" for ch in set(s): print(ch, [Link](ch))
s = "remove spaces" print([Link](" ", ""))
s = "hello" for v in 'aeiouAEIOU': s = [Link](v, '*') print(s)
a, b = "listen", "silent" print(sorted(a) == sorted(b))
sentence = "Python is an awesome language" words = [Link]()
print(max(words, key=len))
s = "12345" print([Link]())

LOOPS
for i in range(1, 51): print(i)
n = int(input("Enter number: ")) for i in range(1, 11): print(n, 'x', i,
'=', n*i)
n = int(input("Enter number: ")) f = 1 for i in range(1, n+1): f *= i
print(f)
a, b = 0, 1 n = int(input("Enter terms: ")) for _ in range(n): print(a)
a, b = b, a + b
for num in range(2, 101): for i in range(2, num): if num % i == 0: break
else: print(num)
for i in range(1, 6): print('*' * i)
n = 1234 sum = 0 while n > 0: sum += n % 10 n //= 10 print(sum)
n = 1234 rev = 0 while n > 0: rev = rev*10 + n%10 n //= 10 print(rev)
even = [i for i in range(1,51) if i%2==0] odd = [i for i in range(1,51) if
i%2!=0] print(even) print(odd)
s = sum(range(1,21)) print(s)

DATA STRUCTURES
lst = [3,6,1,8,9,2,4,5,7,10] print(max(lst), min(lst))
lst = [1,2,3,4,5,6] even = len([i for i in lst if i%2==0]) odd = len(lst)
- even print(even, odd)
lst = [4,2,9,1] print(sorted(lst)) print(sorted(lst, reverse=True))
lst = [1,2,2,3,4,4] print(list(set(lst)))
lst = [1,2,3,4,5] print(sum(lst), sum(lst)/len(lst))
t = (1,2,3,4,5) for i in t: print(i)
a, b = [1,2,3,4], [3,4,5,6] print(set(a) & set(b))
lst = [1,2,2,3] print(set(lst))
students = {'A':85, 'B':90, 'C':75, 'D':95, 'E':80} print(max(students,
key=[Link]))
d1 = {'a':1, 'b':2} d2 = {'c':3, 'd':4} [Link](d2) print(d1)
sentence = "this is a test this is" words = [Link]() count = {}
for w in words: count[w] = [Link](w,0)+1 print(count)
d = {'a':1, 'b':2} print('a' in d)
keys = ['a','b','c'] values = [1,2,3] print(dict(zip(keys, values)))
d = {'a':1,'b':1,'c':2} res = {k:v for k,v in [Link]() if
list([Link]()).count(v)==1} print(res)
students = {'S1':{'name':'A','age':20},'S2':{'name':'B','age':22}}
print(students)

FUNCTIONS
def is_prime(n): if n<2:return False for i in range(2,int(n**0.5)+1): if
n%i==0:return False return True print(is_prime(7))
def factorial(n): f=1 for i in range(1,n+1):f*=i return f
print(factorial(5))
def maximum(a,b,c): return max(a,b,c) print(maximum(3,7,5))
def reverse(s): return s[::-1] print(reverse('hello'))
def square(n): return n*n print(square(4))
def even_list(lst): return [i for i in lst if i%2==0]
print(even_list([1,2,3,4,5,6]))
def area_circle(r): from math import pi return pi*r*r
print(area_circle(5))
def fib(n): if n<=1:return n return fib(n-1)+fib(n-2) print([fib(i) for i
in range(6)])
def sum_n(n): if n==0:return 0 return n+sum_n(n-1) print(sum_n(10))
def is_palindrome(s): return s==s[::-1] print(is_palindrome('madam'))

FILE HANDLING
f=open("[Link]","w") [Link]("Hello World") [Link]()
f=open("[Link]") print([Link]()) [Link]()
f=open("[Link]") print(len([Link]())) [Link]()
f1=open("[Link]") f2=open("[Link]","w") [Link]([Link]())
[Link]();[Link]()
f=open("[Link]","a") [Link]("\nAppended text") [Link]()
f=open("[Link]") print(len([Link]().split())) [Link]()
f=open("[Link]") print(max([Link]().split(), key=len)) [Link]()
f=open("[Link]") data=[Link]().replace("old","new")
open("[Link]","w").write(data)
f=open("[Link]","w") for i in range(3): name=input("Name: ")
marks=input("Marks: ") [Link](name+' '+marks+'\n') [Link]()
f=open("[Link]") print(sum(map(int,[Link]().split()))) [Link]()

LIBRARIES
import random print([[Link](1,100) for _ in range(5)])
import math print([Link](16))
from datetime import datetime print([Link]())
import random print([Link](1,6))
import random print([Link](100000,999999))

Common questions

Powered by AI

The use of set operations in Python is effective for tasks involving unique item extraction and comparison because sets inherently store only unique elements. Operations like finding intersections `set(a) & set(b)`, differences, or unions are highly optimized and perform efficiently even with large collections. Sets provide clear and concise syntax for these tasks, improving the readability and efficiency compared to manual iteration methods. Using sets allows for straightforward solutions to problems involving duplicate removal, fast membership testing, and mathematical set operations, making them an essential tool in Python for tasks that require uniqueness and comparison.

List slicing and reversal in Python, such as `s[::-1]`, facilitates string manipulation tasks by using concise and efficient syntax to reverse strings. This operation is performed in linear time and is more readable than manually iterating over the string indices to build the reversed string. The `s[::-1]` syntax utilizes Python's slicing capabilities to express complex string operations in a straightforward manner, which makes string reversal faster to write, understand, and execute. This enhances the ability to perform common string manipulations efficiently, which is crucial in applications demanding frequent or sophisticated string processing.

Custom Python functions for computing factorials, checking prime numbers, and generating the Fibonacci sequence, such as `def factorial(n)`, `def is_prime(n)`, and `def fib(n)`, enhance algorithmic learning by providing hands-on experience with fundamental mathematical concepts and recursive problem-solving techniques. Implementing these algorithms manually helps learners understand the underlying logic and efficiency of different approaches, such as recursion versus iteration, especially in cases like Fibonacci sequences where optimization techniques (e.g., memoization) can be explored. Writing these functions fosters a deeper understanding of algorithmic efficiency, complexity analysis, and the strengths and weaknesses of different computational approaches.

Tuples in Python are used for immutable sequences, which means that once a tuple is created, its elements cannot be changed. This immutability is significant for preserving data integrity, as it ensures the content of a tuple remains constant throughout the operation of a program, which prevents accidental modifications that could lead to erroneous outcomes. The use of tuples can improve safety and consistency when the stored data should remain unchanged, such as configuration settings or fixed collections of items, and is a critical aspect for applications where data immutability is a requirement.

Calculating the area and perimeter of a rectangle using the formulas `area = length * breadth` and `perimeter = 2 * (length + breadth)` in Python shows computational efficiency and simplicity by directly applying mathematical concepts to solve real-world problems. These operations involve basic arithmetic, which is executed quickly and efficiently by the Python interpreter. The mathematical simplicity of the formulas, combined with Python's straightforward syntax, enables these computations to be implemented in a clear and concise manner, making it an ideal approach for educational purposes and practical applications.

The Python construct `for else` illustrates control flow flexibility by allowing additional code execution (the `else` block) if the loop completes without interruption (e.g., without hitting a `break`). In searching algorithms, this can be used to implement a clear and concise way to handle the case where a search is unsuccessful. For example, checking for prime numbers, the `for` loop may break upon finding a divisor, while the `else` runs if no divisor is found, indicating the number is prime. This use in control flow allows for more readable and logical structuring of loop-dependent algorithms where a comprehensive check is required.

Using dictionary operations like merging, `d1.update(d2)`, and element access, `'a' in d`, in Python is often more intuitive and straightforward compared to other languages due to Python's expressive and concise syntax. Python's `dict` provides built-in methods for common operations that are easy to learn and use, reducing the need for verbose code that may be required in languages like Java or C++. The simplicity of accessing, updating, and checking elements in dictionaries makes these operations highly functional and user-friendly, which enhances the productivity and efficiency of coding when using Python's dictionaries.

Using list comprehensions for filtering even numbers, such as `[i for i in lst if i%2==0]`, enhances code maintainability and performance by providing a compact, readable, and efficient way to process lists. List comprehensions are highly optimized for performance as they execute faster than traditional for-loops. Additionally, they reduce boilerplate code, which makes maintenance easier and improves the readability of the code. This syntactic sugar allows developers to express ideas in fewer lines, which can reduce bugs and simplify future modifications.

Python's `input()` function plays a crucial role in interactive programs by allowing for real-time user interaction. This function halts program execution, waiting for user input, hence making programs dynamically responsive to user actions. The immediate feedback loop between user input and program response results in an engaging interactive experience. However, reliance on `input()` also demands careful handling of user inputs to ensure robustness and error-proofing, such as validating data types and ranges. This interactive feature underlines Python's capability as a flexible language for developing user-facing applications quickly and efficiently.

Swapping values in Python without using a third variable, like `a, b = b, a`, improves code efficiency and readability by reducing the number of operations and making the code more concise. This eliminates the need for a temporary storage variable, thus streamlining the operation and reducing possible sources of error or additional overhead in memory allocation. This Python-specific syntax uses tuple unpacking, which is a more Pythonic way to swap variables compared to using a temporary variable.

You might also like