Task - Functions - Practice Problems #8
Replies: 11 comments
-
import math
def square(n):
return lambda x: math.pow(x,n)
print("Give number to square")
number = int(input())
ans = square(2)
print(ans(number)) def get_info(name, city, hobby):
print("Name: ", name, "\nCity: ", city, "\nHobby: ", hobby)
print("Give Name")
name = input()
print("Give City")
city = input()
print("Give Hobby")
hobby = input()
get_info(name, city, hobby) def swap(a,b):
c = a
a = b
b = c
print(f"Swapped a = {a}, b = {b}")
print("Give num a ")
num1 = int(input())
print("Give num b")
num2 = int(input())
print(f"Original a = {num1}, b = {num2}")
swap(num1, num2) def evenOrOdd(num):
if num % 2 == 0:
print("Even")
else:
print("Odd")
print("Give a number ")
num = int(input())
evenOrOdd(num) def reverse(num):
stringNum = str(num)
print(stringNum [::-1])
print("Give a number to reverse")
num = int(input())
reverse(num) def isPrime(i):
if(i == 2):
print("prime")
quit('')
for k in range(2,i):
if(i % k == 0):
print("composite")
quit("")
if (k == i-1 or i == 2):
print("Prime")
print("Enter number")
num = int(input())
answer = isPrime(num) def isPerfect(i):
divisors = [1]
for k in range(2,i):
if i % k == 0:
divisors.append(k)
sum = 0
for k in range(0,len(divisors)):
sum += divisors[k]
if(sum == i):
print(f"{i} is a perfect number")
else:
print(f"{i} is not a perfect number")
print("Give number")
num = int(input())
isPerfect(num) def getDivisors(i):
divisors = [1]
for k in range(2,i):
if i % k == 0:
divisors.append(k)
for k in range(0,len(divisors)):
print(divisors[k])
print("Give number")
num = int(input())
getDivisors(num) def convertTemp(i):
fahrenheit = i * (9/5) + 32
print(fahrenheit)
print("Give temp in celcius")
num = int(input())
convertTemp(num) def checkPalindrome(i):
revString = i [::-1]
if(i == revString):
print(f"{i} is a palindrome")
else:
print(f"{i} is not a palindrome")
print("Give a string to check")
pal = input()
checkPalindrome(pal) |
Beta Was this translation helpful? Give feedback.
-
Function 1import math
def squared(num):
print("The square of the number:", math.pow(num, 2))
#Main Method
value = input("Enter a number: ")
squared(int(value)) Function 2def info(name, city, hobby):
print("Name:", name, "\nCity:", city, "\nHobby:", hobby)
#Main Method
x1 = input("Enter your name: ")
x2 = input("Enter your city: ")
x3 = input("Enter your hobby: ")
print()
info(x1, x2, x3) Function 3def swapNum(a, b):
#Temporal variables
newa = b
newb = a
print("a =", newa, "\tb =", newb)
#Main Method
y1 = input("Enter value a: ")
y2 = input("Enter value b: ")
swapNum(y1, y2) Function 4def isEvenorOrodd(number):
if((number & 2) == 0):
print("The number is even.")
else:
print("The number is odd.")
#Main Method
z = input("Enter value: ")
isEvenorOrodd(int(z)) Function 5def reverse(number):
newNum = number
print(newNum[::-1])
#Main Method
a = input("Enter a number: ")
reverse(a) Function 6def isPrime(num):
for i in range(2, num):
if (num % i) == 0:
print("Is not prime.")
break
else:
print("Is prime.")
break
b = input("Enter a number: ")
isPrime(int(b)) Function 7def isPerf(val):
sum = 0
for i in range(1, val):
if val % i == 0:
sum += i
return sum == val
ex = input("Enter a number: ")
if(isPerf(int(ex))):
print("The number is perfect.")
else:
print("The number is not perfect.") Function 8def factors(value):
print("The factors of", value, "are:")
for i in range(1, value + 1):
if value % i == 0:
print(i)
exe = input("Enter a number: ")
factors(int(exe)) Function 9def calFahren(temp):
return (temp * 1.8) + 32
te = input("Enter degrees:")
print("Temp:", te, "°C\t", calFahren(int(te)), "°F") Function 10def palindrome(word):
word = word.replace(" ", "")
reverse = word[::-1]
if (word == reverse):
print("The word is a palindrome.")
else:
print("Is not palindrome.")
text = input("Enter a word: ")
palindrome(text) |
Beta Was this translation helpful? Give feedback.
-
1. WAF which computes the square of a number.# Function to square number
def square(x):
return x**2
# square of the number
def main():
# using lambda
square = lambda x : x ** 2
print("-- Help: to close input 'exit' -- ")
while True:
x = input("Enter a number: ")
if x == 'exit':
break
print(f"{int(x)} ^ 2 = {square(int(x))}")
# run main
main() 2. WAF to print your name, city, and hobby in a formatted manner.# print name, city and hobby in formated way
def userDetails(name, city, hobby):
return f"Name: {name} \nCity: {city} \nHobby: {hobby}"
print(userDetails("Olvar", "Monterrey", "Playing videogames")) 3. WAF to swap two numbers.# swap to numbers
def swapNumbers(a,b):
return f"a = {b} \tb = {a}"
print(swapNumbers(1,10)) 4. WAF to print whether a number is even or odd.# even or odd
def oddEven(num):
if num%2 == 0:
return f"{num} is even"
else:
return f"{num} is odd"
# test function
print(oddEven(9)) 5. Write a function that reverses a number.# reverse number
def reverseNum(num):
return int(str(num)[::-1])
print(reverseNum(32245)) 6. Write a function that accepts a number as a parameter and checks whether the number is prime or not.Note: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. # prime function
def primeNumber(num):
for i in range(2,num):
if num%i == 0:
return f"{num} is not prime."
return f"{num} is prime."
# try function
print(primeNumber(76)) 7. Write a function that says whether a number is perfect.# perfect number
def perfectNumber(num):
divisors = []
# find all divisors
for i in range(1,num+1):
if num%i == 0:
divisors.append(i)
# check if num is perfect
if num == sum(divisors)//2:
return f"{num} is a perfect number"
else:
return f"{num} is not a perfect number"
# Try function
print(perfectNumber(28)) 8. Write a function to compute the factors of a positive integer.# find all factors
def getFactors(num):
factors = []
# find all divisors
for i in range(1,num+1):
if num%i == 0:
factors.append(i)
return f'The factors of {num} are: \n{factors}'
# Try function
print(getFactors(28)) 9. Write a function to convert Celsius to Fahrenheit.# celsius to fahrenheit
def celFahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
# try function
temp = 10
print(f"{temp}°C --> {celFahrenheit(temp)}°F") 10. Write a function to check if an input string is a palindrome.#palindrome function
def checkPalindrome(phrase):
word = ''.join(phrase.split(' '))
if word == word[::-1]:
return f"'{phrase}' is a palindrome."
else:
return f"'{phrase}' is not a palindrome."
# try function
print(checkPalindrome("nurses run")) |
Beta Was this translation helpful? Give feedback.
-
def square(num):
return pow(num, 2) def format(name, city, hobby):
print(f"Name: {name}\nCity: {city}\nHobby: {hobby}") def swap(arr):
return [arr[1], arr[0]] def evenOdd(num):
if num % 2 == 0:
return "even"
else:
return "odd" def reverse(num1):
st = str(num1)
maxi = st.__len__() - 1
ret = ""
while(maxi >= 0):
ret += st[maxi]
maxi-=1
return int(ret) def prime(num):
flag = False
for x in range(2, num):
if(num%x == 0):
flag = True
break
if(flag):
return False
else:
return True def perfectNumber(num):
acu = 0
for x in range(1, num):
if num%x == 0:
acu += x
if acu == num:
return True
return False def factors(num):
ret = []
for x in range(2, num):
if num%x == 0:
ret.append(x)
return ret def calFarenheit(celsius):
return (celsius * 9/5) + 32 import math
def palindrome(str):
total = str.__len__()
half = math.floor(str.__len__() / 2)
flag = True
x = 0
while(x < half):
superior = total - (x+1)
if(str[x] == str[superior]):
x+=1
continue
flag = False
break
if(flag):
return True
else:
return False |
Beta Was this translation helpful? Give feedback.
-
def num(n):
return lambda x:n*n
square = num(7)
square1 = square(2)
print(square1)
# full details
def show(name,city,hobbies):
return f"{name}{city}{hobbies}"
details = show(name ="name:akashdas",city = "city:bhunesware",hobbies = "hobbies:giving tasks")
print(details)
#swap of two numbers
a=30
b=40
def swap(c):
i=c()
i=a
a=b
b=i
print(a,b)
#even or odd |
Beta Was this translation helpful? Give feedback.
-
def num(n):
if n%2 == 0:
return f"{num} is even"
else:
return f"{num} is odd"
print(num(10))
# reverse of a number
def reverse(num):
stringNum = str(num)
print(stringNum [::-1])
print("Give a number to reverse")
num = int(input())
reverse(num) |
Beta Was this translation helpful? Give feedback.
-
1.- import math
def square():
return lambda x:math.pow(int(num), 2)
num = input("Digit a number to raise to the power of two: ")
npow = square()
print(npow(num)) 2.- def info():
print("Name:", name)
print("City:", city)
print("hobby:", hobby)
name = input("Enter your name: ")
city = input("Enter your city: ")
hobby = input("Enter your hobby: ")
info() 3.- def swap(num1, num2):
print(f"swapping a='{num1}' and b='{num2}'")
swap = 0
swap = num1
num1 = num2
num2 = swap
print(f"The result is a='{num1}' and b='{num2}'")
a = int(input("Enter the fisrt number to swap: "))
b = int(input("Enter the second number to swap: "))
swap(num1=a, num2=b) 4.- def even_or_odd(n):
if n % 2 == 0:
print(f"The number '{n}' is even")
else:
print(f"The number '{n}' is odd")
num = int(input('Enter a digit: '))
even_or_odd(num) 5.- def reverse(n):
n = str(n)
n = n[::-1]
int(n)
print("reverse:", n)
number = int(input('Number to reverse: '))
reverse(number) 6.- def prime(n):
if n > 1:
for i in range(2, n):
if (n % i) == 0:
print("The {} is not a prime number".format(n))
break
else:
print("The {} is a prime number".format(n))
else:
print("The {} is not a prime number".format(n))
num = int(input("Enter a number: "))
prime(num) 7.- num = int(input("Enter a digit: "))
def perfect(n):
sdiv = 0
for i in range(1,n):
if (n % i) == 0:
sdiv = sdiv + i
if sdiv == n:
print("The number is perfect!")
else:
print("The number is NOT perfect!")
perfect(num) 8.- num = int(input("Enter a digit: "))
def factor(n):
mul = 1
for i in range(1, n+1):
mul = mul*i
print(mul)
factor(num) 9.- tempC = int(input("temperature in Celsius: "))
def calFahrenheit(cel):
return (cel * 9 / 5) + 32
print(calFahrenheit(tempC)) 10.- def reverse(n):
nr = n[::-1]
if nr == n:
print("The word is a palindrome")
else:
print("The word is NOT a palindrome")
word = input('Word: ')
reverse(word.lower()) |
Beta Was this translation helpful? Give feedback.
-
1.- import math
def square(num):
return math.trunc(math.pow(num, 2))
def main():
print("enter a number?")
num = int(input(">"))
print(square(num))
main() 2.- def printformat(name, city, hobby):
print("Name: ", name, "\nCity: ", city, "\nHobby: ", hobby)
def main():
print("Enter your Name:")
name = input(">")
print("Enter your city:")
city = input(">")
print("Enter your hobby:")
hobby = input(">")
printformat(name, city, hobby)
main() 3.- def swap(num1, num2):
print("Fisrt number:" , num1 , "second number:", num2 )
num3 = num1
num1 = num2
num2 = num3
print("Fisrt number:" , num1 , "second number:", num2 )
def main():
print("Enter Fisrt number:")
num1 = input(">")
print("Enter second number:")
num2 = input(">")
swap(num1, num2)
main() 4.- def evenorodd(num):
if int(num) % 2 == 0:
print("The number is even")
else:
print("The number is odd")
def main():
print("Enter a number:")
num = input(">")
evenorodd(num)
main() 5.- def numberreverse(num):
if len(str(num)) == 0:
return
else:
print(str(num)[len(str(num))-1:len(str(num))],end="")
numberreverse(str(num)[0:len(str(num))-1])
def main():
print("enter a number?")
num = input(">")
numberreverse(num)
main() 6.- def prime(num):
primetf = True
for n in range(2, num):
if num % n == 0:
primetf = False
if primetf:
print("The number is prime")
else:
print("The number is not a prime")
def main():
print("Please put a number")
num = int(input(">"))
prime(num)
main() 7.- def perfectnumber(num):
divisor = [1]
number = 0
for n in range(2, num):
if num % n == 0:
divisor.append(n)
for n in range(len(divisor)):
number = divisor[n] + number
if number == num:
print("YES")
else:
print("NO")
def main():
print("Is your number perfect?")
num = int(input(">"))
perfectnumber(num)
main() 8.- def factors(num):
divisor = [1]
number = 0
for n in range(2, num+1):
if num % n == 0:
divisor.append(n)
print(divisor)
def main():
print("factors of the number:")
num = int(input(">"))
factors(num)
main() 9.- def ctof(num):
f = (num * (9/5)) + 32
print("Fahrenheit: ", f)
def main():
print("Transform C to F:")
num = int(input(">"))
ctof(num)
main() 10.- def palindrome(word):
i = len(word)
reverseword = ""
while (i > 0):
reverseword = reverseword + word[i - 1:i]
i = i - 1
if word.replace(" ", "") == reverseword.replace(" ", ""):
print("is a palindrome")
else:
print("is not a palindrome")
def main():
print("Is the word a palindrome")
word = input(">")
palindrome(word)
main() |
Beta Was this translation helpful? Give feedback.
-
Task 1 x = int(input("Enter a number to square"))
def square (x):
result = x**2
return f'The square of number is: {result}'
print(square(x)) Task 2 def data(name, city, hobby):
return f'Name: {name} \nCity: {city} \nHobby: {hobby} \n'
print(data("Francisco","Ags","Videogames")) Task 3 a = input("a: ")
b = input("b: ")
def swap(a,b):
temp = a
a = b
b = temp
return f'a: {a}\nb: {b}'
print(swap(a,b)) Task 4 x = 3
def isEven(x):
if(x%2==0):
print("Even number")
else:
print("Odd number")
isEven(x) Task 5 x = input("Enter a number: ")
print(x[::-1]) Task 6 x = 29
def primeNumber(x):
isPrime=False
for i in range(2, x):
if (x % i and x>1) == 0:
isPrime = True
if isPrime:
print(x, "is NOT prime number")
else:
print(x, "is a prime number")
primeNumber(x) Task 7 x = int(input("Enter a number: "))
def isPerfect(x):
list = []
for i in range(1,x+1):
if( x%i==0):
list.append(i)
res = "Perfect number" if(x == sum(list)//2) else "Not perfect number"
print(res)
isPerfect(x) Task 8 def factor(x):
for i in range (1, x):
if(int(x)%i==0):
print(i)
print(x)
x = 17
factor(x) Task 9 def calFahrenheit(cels):
return (cels* (9/5) + 32)
cels = 180
print(calFahrenheit(cels)) Task 10 myStr = input("Enter a word: ")
def palindrome(myStr):
if(myStr == myStr[::-1]):
print("Palindrome")
else:
print("NOT a palindrome")
palindrome(myStr.lower()) |
Beta Was this translation helpful? Give feedback.
-
1. WAF which computes the square of a number.number=int(input("Enter a number"))
def square(number):
print(number ** 2)
square(number) 2. WAF to print your name, city, and hobby in a formatted manner.name = input("Enter your name")
city = input("Enter your city")
hobby = input("Enter your city")
def formatted(name, city, hobby):
return f"Name: {name} \nCity: {city} \nHobby: {hobby}"
print(formatted(name,city,hobby)) 3. WAF to swap two numbers.x= int(input("Enter number"))
y= int(input("Enter number"))
def swap (x,y):
y1=x
x1=y
print(x1,y1)
swap(x,y) 4. WAP to take a number as input and print whether it is even or odd.number = int(input("Enter a number"))
def even_odd(number):
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
even_odd(number) ##Write a function that reverses a number. number = str(input()) for digit in number[::-1]: 5. Write a function that reverses a number.#Example x = 32245; number = str(input())
for digit in number[::-1]:
print (digit) 6. WAP to take a number as input and print whether it is prime or composite.number = int(input("Enter a number"))
def prime_composite(number):
if number % 2 == 0 or number % 3 == 0:
print("The number is composite")
else:
print("the number is prime")
prime_composite(number) 7. Write a function that says whether a number is perfect.According to Wikipedia: In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). number = int(input("Enter your number"))
list = []
total = 0
for i in range (1,number):
if number % i == 0:
list.append(i)
for i in list:
total = total + i
if total == number:
print(number) |
Beta Was this translation helpful? Give feedback.
-
##1. import math
digit = int(input("Enter a integer numbers: "))
square = digit**2
print(f" square of {digit}is {square}") def details():
Name = "Jyothi"
City = "Khammam"
Hobby = "Badmenten"
print("Name: {}\n City: {}\n Hobby: {}".format(Name,City,Hobby))
details() x = 5
y = 7
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
# code to swap 'x' and 'y'
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y) num = int (input (“Enter any number to test whether it is odd or even: “)
if (num % 2) == 0:
print (“The number is even”)
else:
print (“The provided number is odd”) num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num)) num = 9
for i in range(2,num):
if num % i== 0:
print("Not prime")
else:
print("prime") x = int(input("Enter a number: "))
def isPerfect(x):
list = []
for i in range(1,x+1):
if( x%i==0):
list.ap #pend(i)
res = "Perfect number" if(x == sum(list)//2) else "Not perfect number"
print(res)
isPerfect(x)
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Nagetive number") |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
WAF which computes the square of a number.
WAF to print your name, city, and hobby in a formatted manner.
Sample Output:
WAF to swap two numbers.
WAF to print whether a number is even or odd.
Write a function that reverses a number.
Example x = 32245;
Expected Output: 54223
Write a function that accepts a number as a parameter and checks whether the number is prime or not.
Note: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Write a function that says whether a number is perfect.
According to Wikipedia: In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128.
Write a function to compute the factors of a positive integer.
Write a function to convert Celsius to Fahrenheit.
Function
calFahrenheit()
returns the converted Celsius value to Fahrenheit value based on the formula(Celsius × 9/5) + 32 = Fahrenheit
.Write a function to check if an input string is a palindrome.
A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
Beta Was this translation helpful? Give feedback.
All reactions