#pyton #The try block will generate an error, because x is not defined: try: print(x) except: print("An exception occurred") price = 49 txt = "The price is {} dollars" print(txt.format(price)) if 5 > 2: print("Five is greater than two!") if 5 > 2: print("Five is greater than two!") import json # some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary: print(y["age"]) x = 5 y = "John" print(x) print(y) x = "awesome" def myfunc(): print("Python is " + x) myfunc() myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" print(myvar) print(my_var) print(_my_var) print(myVar) print(MYVAR) print(myvar2) x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) import re #Check if the string starts with "The" and ends with "Spain": txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) if x: print("YES! We have a match!") else: print("No match") # Python Program to calculate the square root # Note: change this value for a different result num = 8 # To take the input from the user #num = float(input('Enter a number: ')) num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) # Python Program to find the area of triangle a = 5 b = 6 c = 7 # Uncomment below to take inputs from the user # a = float(input('Enter first side: ')) # b = float(input('Enter second side: ')) # c = float(input('Enter third side: ')) # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) # Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath a = 1 b = 5 c = 6 # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2)) # Python Program to convert temperature in celsius to fahrenheit # change this value for a different result celsius = 37.5 # calculate fahrenheit fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) # Python program to find the largest number among the three input numbers # change the values of num1, num2 and num3 # for a different result num1 = 10 num2 = 14 num3 = 12 # uncomment following lines to take three numbers from user #num1 = float(input("Enter first number: ")) #num2 = float(input("Enter second number: ")) #num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number is", largest) # Python program to check if the number is an Armstrong number or not # take input from the user num = int(input("Enter a number: ")) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") while True: # take input from the user choice = input("Enter choice(1/2/3/4): ") # check if choice is one of the four options if choice in ('1', '2', '3', '4'): try: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) except ValueError: print("Invalid input. Please enter a number.") continue if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) # check if user wants another calculation # break the while loop if answer is no next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break else: print("Invalid Input") Run Code x = 5 while x < 15: if x % 2 == 0: print("Even number found") break print(x) x += 2 else: print("All numbers were odd") //// number1 = input("First number: ") number2 = input("\nSecond number: ") # Adding two numbers # User might also enter float numbers sum = float(number1) + float(number2) # Display the sum # will print value in float print("The sum of {0} and {1} is {2}" .format(number1, number2, sum)) /// #jj Python program to swap two variables x = 5 y = 10 # To take inputs from the user #x = input('Enter value of x: ') #y = input('Enter value of y: ') # create a temporary variable and swap the values temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) x = 5 y = 10 x, y = y, x print("x =", x) print("y =", y) # Display the powers of 2 using anonymous function terms = 10 # Uncomment code below to take input from the user # terms = int(input("How many terms? ")) # use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) print("The total terms are:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) # Python Program to find the factors of a number # This function computes the factor of the argument passed def print_factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) num = 320 my_list = [21, 44, 35, 11] for index, val in enumerate(my_list): print(index, val) print_factors(num) print(b'Easy \xE2\x9C\x85'.decode("utf-8")) num = 3452 count = 0 while num != 0: num //= 10 count += 1 print("Number of digits: " + str(count)) import os # file name with extension file_name = os.path.basename('/root/file.ext') # file name without extension print(os.path.splitext(file_name)[0]) base = 3 exponent = 4 result = 1 while exponent != 0: result *= base exponent-=1 print("Answer = " + str(result)) import pathlib # path of the given file print(pathlib.Path("my_file.txt").parent.absolute()) # current working directory print(pathlib.Path().absolute()) import time def countdown(time_sec): while time_sec: mins, secs = divmod(time_sec, 60) timeformat = '{:02d}:{:02d}'.format(mins, secs) print(timeformat, end='\r') time.sleep(1) time_sec -= 1 print("stop") countdown(5) #Python Strings #Two strings are said to be anagram if we can form one string by a Care. #Python program to check if two strings are anagrams using sorted() str1 = "Race" str2 = "Care" # convert both the strings into lowercase str1 = str1.lower() str2 = str2.lower() # check if length is same if(len(str1) == len(str2)): # sort the strings sorted_str1 = sorted(str1) sorted_str2 = sorted(str2) # if sorted char arrays are same if(sorted_str1 == sorted_str2): print(str1 + " and " + str2 + " are anagram.") else: print(str1 + " and " + str2 + " are not anagram.") else: print(str1 + " and " + str2 + " are not anagram.") import os file_stat = os.stat('my_file.txt') print(file_stat.st_size) import os file_stat = os.stat('my_file.txt') print(file_stat.st_size) /////