My daily goals of writing python

#friday

try:

  first =int(input('Enter a number:'))

except Exception as e:

  print(f'you should enter numbers only {e}')

  print('thanks for your input')  

try:

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

  b=int(input("Enter second number:"))

  except Exception as e:

    print(f'you should enter numberss only')

if (b==0):

  raise ZeroDivisionError ('program is not created for divison by zero')


print(f'your divison is: {a/b}')

#final keyword

def func():

  try:

    first =int(input('Enter a number:'))

    return

  except Exception as e:

    print(f'you should enter numbers only {e}')

    return

  else:

      print('else')

      return

# we are using final keyword and it always print while using a function final value will automatically print and we don't have to return the value


  finally:

      print('This is final')

func() 

#python scope

y=18

def fa():

    x="faizan"

    print(f' name is :{x} and age is {y}')

fa()

#global keyword makes variable outside of a function

a='adil'

def fa():

    global a

    a='faizan'

fa()

print(a)

#nonlocal keyword makes that it doesn't belong to the function

def af():

    x='adil'

    def fa():

      nonlocal x

      x='faizan'

      

    fa()

    return x


print(af())

#adding into the list

fa = ['faizan','ayaan','azfaar']

mbu=['adil']

af=('freinds','brothers')

#append means it add at the last

fa.append('umar')

#insert is to add at index value+

fa.insert(2,'mohammed')

#adding two lists by extend keyword

fa.extend(mbu)

#we can extend the tuples  by extend

fa.extend(af)

#print all adding keywords

print(fa)   

#creating objects

class faizan:
  name='faizan'
  def __init__(self,roll,pin,clg):
    self.roll= roll
    self.pin =pin
    self.clg =clg
  print(name)
obj = faizan(779,518301,'mbu')
print(obj.roll,obj.pin,obj.clg,)

#constructor

class ab:
  def __init__(self,i) :
    self.i =i
  def square(self):
      print(f'the square is {self.i*self.i}')
  def cube(self):
    print(f'the cube is {self.i*self.i*self.i}')
  def  squareroot(self):
    print(f'the squareroot is {self.i**1/2}')    
     
obj = ab(5)
obj.square()
obj.cube()
obj.squareroot()
#o/p is :
[Running] python -u "c:\Users\faiza\OneDrive\Desktop\second.py\tempCodeRunnerFile.python"
the square is 25
the cube is 125
the squareroot is 2.5

#inheritance

class parent:
  name ='faizan'
  clg = 'mbu'
  def first(self):
    print(f"My name is {self.name} and my clg name is {self.clg} ")
class child1():
  name ='adil'  
  clg ='mbu'
  def second(self):
     
      print(f"My name is {self.name} and my clg name is {self.clg} ")
class smallchild (parent,child1):
  def last(self):
       
    print(f"My name is {self.name} and my clg name is {self.clg} ")
       
   
   
a= parent()
b = smallchild()
c= child1()
a.first()
c.second()
b.second()
b.last()
#o/p is:
My name is faizan and my clg name is mbu
My name is adil and my clg name is mbu
My name is faizan and my clg name is mbu
My name is faizan and my clg name is mbu

#multilevel inheritance

class first:
  a=10
class second(first):
  b=100  
class  third(second):
  c=1000
obj = third()
print(obj.a)
print(obj.a,obj.b)
print(obj.a,obj.b,obj.c)
#o/p is:
10
10 100
10 100 1000  

#polymorphism

class first:
  def __init__(self,name,age):
    self.name=name
    self.age =age
  def one (self):
    print('poly one')
class second:
  def __init__(self,name,age):
    self.name=name
    self.age =age
  def one (self):
    print('poly two')
class third:
  def __init__(self,name,age):
    self.name=name
    self.age =age
  def one (self):
    print('poly three')
first1=first('faizan',18)
second2=second('umar',19)
third3=third('adil',17)
for a in (first1,second2,third3):
   print(f'your name is :{a.name}, and your age is:{a.age}')
   a.one()

 # Using walrus operator

if (n := len([1, 2, 3, 4, 5])) > 3:
    print(f"List is too long ({n} elements, expected <= 3)") # Output: List is too long (5 elements, expected <= 3
o/p is:
List is too long (5 elements, expected <= 3)
#modules importing and creating first creating a file named as math_s.py and another fa.py
#code in math_s.py
def greet(na):
    print('hello',na)
def op(age):
    print('age is',age)    
def add(a,b):
    return a+b
def sub(a,b):
    return a-b
def multi(a,b):
    return a*b
def div(a,b):
    if b!=0:
        return a/b
    else:
        return "It can't divided by zero"

 #importing module and taking specific module:
import math_s as ma
from math_s import greet
x=int(input('enter first number:'))
y=int(input('Enter second number:'))
result=ma.add(x,y)
print(f'a+b is: {result}')
result1=ma.sub(x,y)
print(f'a-b is: {result1}')
result2=ma.multi(x,y)
print(f'a*b is: {result2}')
result3=ma.div(x,y)
print(f'a/b is: {result3}')
greet('faizan')
ma.op(18)
#module
# persons.py persons = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 20}, {"name": "David", "age": 35}, {"name": "Eve", "age": 22} ]
#importing
import persons def find_person_with_lowest_age(): # Write your code here min_age=persons.persons[0] for a in persons.persons[1:]: if a['age']<min_age['age']: min_age=a return min_age lowest_age_person = find_person_with_lowest_age() print("Person with the lowest age:") print(f"Name: {lowest_age_person['name']}") print(f"Age: {lowest_age_person['age']}")
#o/p is:
import persons def find_person_with_lowest_age(): # Write your code here min_age=persons.persons[0] for a in persons.persons[1:]: if a['age']<min_age['age']: min_age=a return min_age #o/p is: lowest_age_person = find_person_with_lowest_age() print("Person with the lowest age:") print(f"Name: {lowest_age_person['name']}") print(f"Age: {lowest_age_person['age']}")

#module:
# mysteryModule.py

input_value = # hidden

def mystery_function(input):
    """
    This function takes an input and performs some operations on it.
    
    Parameters:
    input : int
        The input value
    
    Returns:
    int
        The result of mystery operations performed on the input
    """
    # The actual implementation of the mystery function is hidden
    # You need to determine the output it generates based on the given input

Your task is to write the code for "main.py" to import "mysteryModule.py", call the mystery function with the provided input value, and print the output.

#importing:

#Write your code here# main.py


# Importing the module

import mysteryModule as ma



# Getting the input value from the module

input=ma.input_value


# Calling the mystery function with the provided input value



# Printing the output of the mystery function

print(ma.mystery_function(input))

#generators in python i used yield and next method:

def fa():
    for i in range(1,10):
        yield i
a=fa()
for j in range(1,10):
   
    print(next(a))
#another method for for loop:
def fa():
    for i in range(1,10):
        yield i
ob_j=fa()
#for j in range(1,10):
 #or
for valu_e in ob_j:  
    print(valu_e)
       
#o/p is:
1 2 3 4 5 6 7 8 9
def args(func):
    def wra_p(*args,**kwargs):
        print(f'decorater name:{func.__name__}')
        print(f'positional argument is by using args:{args}')
        print(f'keyword argument is by using kwargs:{kwargs}')
        return func(*args,**kwargs)
    return wra_p
@args
def info(name,age):
    print(f'my name is {name} and my age is{age}')  
info('faizan',age=18)

def repeat(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            result = None
            for _ in range(n):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    return f"Hello, {name}!"

result = greet("Alice")
print(result)  # Prints "Hello, Alice!" once
'''
B) "Hello, Alice!"
Explanation:
In the given code, we have a decorator `repeat` that takes an argument `n`, which specifies the number of times the decorated function should be called. Inside the decorator, a nested function `wrapper` is defined to execute the decorated function `n` times.

The `greet` function is decorated with `@repeat(3)`, meaning it will be called three times when invoked. It returns the string "Hello, Alice!", and since it is decorated with `@repeat(3)`, it will be called three times.

After calling it three times, result will store the value returned by the last execution. Thus the answer will be

A) "Hello, Alice!"

'''
def log_addition(func):
    # Write your code here
    def add1(*args,**kwargs):
        print(f'Adding {a} and {b}')
        res=func(a,b)
        print(f'Result of addition: {res}')
        return res
    return add1    
           
   

@log_addition
def add(a, b):
    return a + b

a = int(input())
b = int(input())

# Call the decorated function
add(a, b)
def is_valid(func):
    # Write your code here
    def wrap(name,age):
        if name.isalpha() and age.isdigit():
             return func(name,int(age))
    return wrap        



@is_valid
def print_person_details(name, age):
    print(f"Name: {name}, Age: {age}")

name = input()
age = input()
print_person_details(name, age)
#The above o/p is:
decorater name:info positional argument is by using args:('faizan',) keyword argument is by using kwargs:{'age': 18} my name is faizan and my age is18
#divisble number finder:
def find_divisibles(start, end, divisor):
    # TODO: Implement the function using List comprehension
    return [i for i in range(start,end+1) if i%divisor==0]

if __name__ == "__main__":
    start, end, divisor = map(int, input().split())
    result = find_divisibles(start, end, divisor)
    print(result)
#o/p is:
1 20 3 [3, 6, 9, 12, 15, 18]
#position of the alphabets:
def alphabet_position(text):
    # Your list comprehension goes here
    # Hint: Use ord() to get ASCII value and chr() to convert back to character if needed
    return [ord(char.lower())-96 for char in text if char.isalpha()]

if __name__ == "__main__":
    input_string = input().strip()
    result = alphabet_position(input_string)
    print(result)

#o/p is:
faizan is great [6, 1, 9, 26, 1, 14, 9, 19, 7, 18, 5, 1, 20]
#tuesday after dussera holidays:
x,y = map(int,input().split())
# write your code here
if y>x:
    print('YES')
else:
    print('No')
'''
o/p is:
PS C:\four.py> python -u "c:\four.py\chef.py" 99 56 No PS C:\four.py> python -u "c:\four.py\chef.py" 8 99 YES
'''
#alternate uppercase letters:
def alternating_case(text): # TODO: Implement the generator expression to alternate case # Hint: Use enumerate() and a ternary operator in the generator expression alternated =(a.upper()if i%2==0 else a.lower() for i,a in enumerate(text)) # Your generator expression here return ''.join(alternated) if __name__ == "__main__": input_string = input().strip() result = alternating_case(input_string) print(result) 
#o/p is:
'''
Sample Input
hello world
Your Output
HeLlO WoRlD
 '''
#taking input
x,y,z=map(float,input().split())
#calculate average of this three
print((x+y+z)/3)
#o/p is:
'''
99 98.5 97.5 98.33333333333333
'''
#problems in py in these the avg of two no is greter then YES otherwise NO
#It takes an integer input from the user. This input determines how many test cases the code will run. For example, if the user inputs 2, the loop will run twice.
for i in range(int(input('Enter no of times to loop:'))):
  x,y,z=map(int,input().split())
  if (((x+y)/2 )> z):
      print('YES')
  else:
      print('NO')
#o/p is:   
'''
Enter no of times to loop:3 1 8 2 YES 6 8 4 YES 9 7 2 YES
'''
'''
A group of N friends in Chefland want to buy Chef-TV subscriptions. We know that 6 people can share one Chef-TV subscription. Also, the cost of one Chef-TV subscription is X rupees. Determine the minimum total cost that the group of N friends will incur so that everyone in the group is able to use Chef-TV.
'''
#imporing maths
#no of inputs
import math
for i in range(int(input())):
    n,x=map(int,input().split())#Taking the input from the user
    n=math.ceil(n/6)# smallest integer greater than or equal to the given number.
    print(n*x)

#o/p is:
'''
3 1 100 100 2 250 250 9 100 200
'''
# a guy has to submit assingment before 10 it takes 3 hours
#no of times to loop
for i in range(int(input('no of loop:'))):
    a=int(input())#taking input
    b=10
    if a<=7:
        print('Yes')
    else:
        print('No')
#o/p is:
'''
no of loop:2 2 Yes 9 No
#To check a prime number in my way
def prime(no):
    if no<=1:
        return False
    for i in range(2,no):
        if no%i==0:#if any number is dividble by this then it's sshows false
            return False
    else:
       return True
def af():  
  number=[]    
  for i in range (int(input('Enter number of test cases:'))):      
    no=int(input("Enter number:"))
    number.append(no)#here we are adding no list in number list
  for no in number:
     if prime(no):
        print('yes')
     else:
        print('no')  
af()      
#o/p is:
'''
Enter number of test cases:5 Enter number:1 Enter number:2 Enter number:3 Enter number:4 Enter number:5 no yes yes no yes
'''     
#This is a hackerrank quetion about range starts from i to n if it is 3and 5 multiple
then FizzBuzz if 3 then Fizz and 5 for Buzz:
def fizzBuzz(n):
    # Write your code here
   
    for i in range(1,n+1):
        if i%3==0 and i%5==0:
            print('FizzBuzz')
        elif i%3==0 and i%5!=0:
            print('Fizz')
        elif i%5==0 and i%3!=0:
            print('Buzz')
        elif i%3!=0 or i%5!=0:
            print(i)            
   
if __name__ == '__main__':
    n = int(input().strip())

    fizzBuzz(n)
#o/p is:
'''
15 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
'''
'''
File Handling:
os.environ.get('OUTPUT_PATH') checks for the OUTPUT_PATH environment variable. If it's set, the result is written to that file.
If OUTPUT_PATH is not set (which is likely the cause of your error), the result is printed to the console instead.
Running the Code:
If you're running this locally and don't have an OUTPUT_PATH variable, it will now simply print the result to the console, avoiding the error.
'''
import math
import os
import random
import re
import sys

# Complete the 'reverse_words_order_and_swap_cases' function below.
# The function is expected to return a STRING.
# The function accepts STRING sentence as parameter.

def reverse_words_order_and_swap_cases(sentence):
    # Split the sentence into words, reverse the list of words, and join them back into a string
    words = sentence.split()
    reversed_words = ' '.join(words[::-1])
   
    # Swap cases
    swapped_and_reversed = ''.join([char.lower() if char.isupper() else char.upper() for char in reversed_words])
   
    return swapped_and_reversed

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')#it shows error beause of file handling
    sentence = input()
    result = reverse_words_order_and_swap_cases(sentence)
    fptr.write(result + '\n')
    fptr.close()
 
mport os

def reverse_words_order_and_swap_cases(sentence):
    # Split the sentence into words, reverse the list of words, and join them back into a string
    words = sentence.split()
    reversed_words = ' '.join(words[::-1])
   
    # Swap cases
    swapped_and_reversed = ''.join([char.lower() if char.isupper() else char.upper() for char in reversed_words])
   
    return swapped_and_reversed

if __name__ == '__main__':
    # Check if OUTPUT_PATH is set in environment variables; otherwise, use standard output
    output_path = os.environ.get('OUTPUT_PATH')
   
    sentence = input("Enter a sentence: ")  # Prompt user for input
    result = reverse_words_order_and_swap_cases(sentence)
   
    if output_path:
        with open(output_path, 'w') as fptr:
            fptr.write(result + '\n')
    else:
        # If no OUTPUT_PATH, print to console
        print(result)
#o/p is:
'''
Enter a sentence: fAIZAN iS Great gREAT Is Faizan PS C:\four.py> python -u "c:\four.py\chef.py" Enter a sentence: faiZANpython -u "c:\four.py\chef.py" "C:\FOUR.PY\CHEF.PY" -U FAIzanPYTHON
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in range(int(input())):
    try:
       a,b=map(int,input().split())
       print(a//b)
    except ZeroDivisionError as e:
      print('Error Code: integer division or modulo by zero')
    except ValueError as e:
      print('Error Code:',e)
#o/p is:
'''
3
1 0
2 $
3 1
Expected Output
Error Code: integer division or modulo by zero
Error Code: invalid literal for int() with base 10: '$'
3
'''
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    result=[ [i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k!=n ]
    print(result)
#o/p is:
'''
1 1 2 3 [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 2]]
'''   
 

Comments

Popular posts from this blog

py2

project.py