Beginners
Question 1: Given a two integer numbers return their product and if the product is greater than 1000, then return their sum
number1 = 20number2 = 30The result is 600number1 = 40number2 = 30The result is 70
Question 2: Given a range of first 10 numbers, Iterate from start number to the end number, print the sum of the current number and previous number.**
Printing current and previous number sum in a given range(10)Current Number 0 Previous Number 0 Sum: 0Current Number 1 Previous Number 0 Sum: 1Current Number 2 Previous Number 1 Sum: 3Current Number 3 Previous Number 2 Sum: 5Current Number 4 Previous Number 3 Sum: 7Current Number 5 Previous Number 4 Sum: 9Current Number 6 Previous Number 5 Sum: 11Current Number 7 Previous Number 6 Sum: 13Current Number 8 Previous Number 7 Sum: 15Current Number 9 Previous Number 8 Sum: 17
Question 3: Given a string, display only those characters which are present at an even index number. For example str = “pynative”, so you should display ‘p’, ‘n’, ‘t’, ‘v’.
Orginal String is: pynativePrinting only even index charspntv
Question 4: Given a string and an integer number n, remove characters from a string starting from zero up to n and return a new string
**
For example, removeChars("pynative", 4) so output must be tive.
Note: n must be less than the length of the string.
Question 5: Given a list of numbers, return True if first and last number of a list is same**
Given list is [10, 20, 30, 40, 10]result is TrueGiven list is [10, 20, 30, 40, 50]result is False
Question 6: Given a list of numbers, Iterate it and print only those numbers which are divisible of 5
Given list is [10, 20, 33, 46, 55]Divisible of 5 in the list:102055
Question 7: Return the total count of sub-string “Emma” appears in the given string
Given string is “Emma is good developer. Emma is a writer”
Emma appeared 2 times
Question 8: Print the following pattern
12 23 3 34 4 4 45 5 5 5 5
Question 9: Reverse a given number and return true if it is the same as the original number
original number 121The original and reverse number is the sameoriginal number 125The original and reverse number is not same
Question 10: Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list
First List [10, 20, 23, 11, 17]Second List [13, 43, 24, 36, 12]result List is [23, 11, 17, 24, 36, 12]
Question 11: Write a code to extract each digit from an integer, in the reverse order
For example, if the given int is 7536, the output shall be “6 3 5 7”, with a space separating the digits.
Question 12: Calculate income tax for the given income by adhering to the below rules
| Taxable Income | Rate (%) |
|---|---|
| First $10,000 | 0 |
| Next $10,000 | 10 |
| The remaining | 20 |
For example, suppose that the taxable income is $45000, then the income tax payable is:
$100000% + $1000010% + $2500020% = $6000
*
Question 13: Print multiplication table form 1 to 10
1 2 3 4 5 6 7 8 9 102 4 6 8 10 12 14 16 18 203 6 9 12 15 18 21 24 27 304 8 12 16 20 24 28 32 36 405 10 15 20 25 30 35 40 45 506 12 18 24 30 36 42 48 54 607 14 21 28 35 42 49 56 63 708 16 24 32 40 48 56 64 72 809 18 27 36 45 54 63 72 81 9010 20 30 40 50 60 70 80 90 100
Question 14: Print downward Half-Pyramid Pattern with Star (asterisk)
* * * * ** * * ** * ** **
Question 15: Write a function called exponent(base, exp) that returns an int value of base raises to the power of exp.
Note here exp is a non-negative integer, and the base is an integer.
====================Case 1====================base = 2exponent = 52 raises to the power of 5 is: 32 i.e. (2 *2 * 2 *2 *2 = 32)====================Case 2====================base = 5exponent = 45 raises to the power of 4 is: 625 i.e. (5 *5 * 5 *5 = 625)
Input and Output
Question 1: Accept two numbers from the user and calculate multiplication
Question 2: Display “My Name Is James” as “MyNameIsJames” using output formatting of a print() function**
Use
print()statement formatting to display ** separator between each word.For example: print(‘My’, ‘Name’, ‘Is’, ‘James’) will display MyNameIsJames
So use one of the formatting argument of
print()to turn the output into MyNameIs**James
Question 3: Convert decimal number to octal using print() output formatting
Display decimal number 8 as 10
Question 4: Display float number with 2 decimal places using print()
Display 458.541315 as 458.54
Question 5: Accept list of 5 float numbers as a input from user
//Numbers can be any[78.6, 78.6, 85.3, 1.2, 3.5]
Question 6: write all file content into new file by skiping line 5 from following file
test.txt file:
line1line2line3line4line5line6line7
newFile.txt should be
line1line2line3line4line6line7
Question 7: Accept any three string from one input() call
Question 8: You have the following data.
totalMoney = 1000quantity = 3price = 450
display above data using string.format() method
I have 1000 dollars so I can buy 3 football for 450.00 dollars.
Question 9: How to check file is empty or not
Question 10: Read line number 4 from the following file
test.txt file:
line1line2line3line4line5line6line7
Loop
Question 1: Print First 10 natural numbers using while loop
012345678910
Question 2: Print the following pattern
11 21 2 31 2 3 41 2 3 4 5
Question 3: Accept number from user and calculate the sum of all number between 1 and given number
For example user given 10 so the output should be 55
Question 4: Print multiplication table of given number
For example num = 2 so the output should be
2468101214161820
Question 5: Given a list iterate it and display numbers which are divisible by 5 and if you find number greater than 150 stop the loop iteration
list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]155575150
Question 6: Given a number count the total number of digits in a number
For example, the number is 75869, so the output should be 5.
Question 7: Print the following pattern using for loop
5 4 3 2 14 3 2 13 2 12 11
Question 8: Reverse the following list using for loop
list1 = [10, 20, 30, 40, 50]5040302010
Question 9: Display -10 to -1 using for loop
-10-9-8-7-6-5-4-3-2-1
Question 10: Display a message “Done” after successful execution of for loop
For example, the following loop will execute without any error.
for i in range(5):print(i)
So the Expected output should be:
01234Done!
Functions
String
Data Structure
List
Dictionary
Set
tuple
JSON
Random Data Generation
NumPy
Pandas
Matplotlib
Database
Question 1: Connect to your database server and print its version
Write SQL query to get the database server version.
Connect to the database and use cursor.execute() to execute this query.
Next, use cursor.fetchone() to fetch the record.
import sqlite3def get_connection():connection = sqlite3.connect('python_db.db')return connectiondef close_connection(connection):if connection:connection.close()def read_database_version():try:connection = get_connection()cursor = connection.cursor()cursor.execute("select sqlite_version();")db_version = cursor.fetchone()print("You are connected to SQLite version: ", db_version)close_connection(connection)except (Exception, sqlite3.Error) as error:print("Error while getting data", error)print("Question 1: Print Database version")read_database_version()
Question 2: Fetch Hospital and Doctor Information using hospital Id and doctor Id
Implement the functionality to read the details of a given doctor from the doctor table and Hospital from the hospital table. i.e., read records from Hospital and Doctor Table as per given hospital Id and Doctor Id.
import sqlite3def get_connection():connection = sqlite3.connect('python_db.db')return connectiondef close_connection(connection):if connection:connection.close()def get_hospital_detail(hospital_id):try:connection = get_connection()cursor = connection.cursor()select_query = """select * from Hospital where Hospital_Id = ?"""cursor.execute(select_query, (hospital_id,))records = cursor.fetchall()print("Printing Hospital record")for row in records:print("Hospital Id:", row[0], )print("Hospital Name:", row[1])print("Bed Count:", row[2])close_connection(connection)except (Exception, sqlite3.Error) as error:print("Error while getting data", error)def get_doctor_detail(doctor_id):try:connection = get_connection()cursor = connection.cursor()select_query = """select * from Doctor where Doctor_Id = ?"""cursor.execute(select_query, (doctor_id,))records = cursor.fetchall()print("Printing Doctor record")for row in records:print("Doctor Id:", row[0])print("Doctor Name:", row[1])print("Hospital Id:", row[2])print("Joining Date:", row[3])print("Specialty:", row[4])print("Salary:", row[5])print("Experience:", row[6])close_connection(connection)except (Exception, sqlite3.Error) as error:print("Error while getting data", error)print("Question 2: Read given hospital and doctor details \n")get_hospital_detail(2)print("\n")get_doctor_detail(105)
Questions 3: Get the list of doctors as per the given specialty and salary
Note: Fetch all doctors whos salary higher than the input amount and specialty is the same as the input specialty.
import sqlite3def get_connection():connection = sqlite3.connect('python_db.db')return connectiondef close_connection(connection):if connection:connection.close()def get_specialist_doctors_list(speciality, salary):try:connection = get_connection()cursor = connection.cursor()sql_select_query = """select * from Doctor where Speciality = ? and Salary > ?"""cursor.execute(sql_select_query, (speciality, salary))records = cursor.fetchall()print("Printing doctors whose specialty is", speciality, "and salary greater than", salary, "\n")for row in records:print("Doctor Id: ", row[0])print("Doctor Name:", row[1])print("Hospital Id:", row[2])print("Joining Date:", row[3])print("Specialty:", row[4])print("Salary:", row[5])print("Experience:", row[6], "\n")close_connection(connection)except (Exception, sqlite3.Error) as error:print("Error while getting data", error)print("Question 3: Get Doctors as per given Speciality\n")get_specialist_doctors_list("Garnacologist", 30000)
Question 4: Get a list of doctors from a given hospital
Note: Implement the functionality to fetch all the doctors as per the given Hospital Id. You must display the hospital name of a doctor.
import sqlite3def get_connection():connection = sqlite3.connect('python_db.db')return connectiondef close_connection(connection):if connection:connection.close()def get_hospital_name(hospital_id):# Fetch Hospital Name using Hospital idtry:connection = get_connection()cursor = connection.cursor()select_query = """select * from Hospital where Hospital_Id = ?"""cursor.execute(select_query, (hospital_id,))record = cursor.fetchone()close_connection(connection)return record[1]except (Exception, sqlite3.Error) as error:print("Error while getting data", error)def get_doctors(hospital_id):# Fetch Hospital Name using Hospital idtry:hospital_name = get_hospital_name(hospital_id)connection = get_connection()cursor = connection.cursor()sql_select_query = """select * from Doctor where Hospital_Id = ?"""cursor.execute(sql_select_query, (hospital_id,))records = cursor.fetchall()print("Printing Doctors of ", hospital_name, "Hospital")for row in records:print("Doctor Id:", row[0])print("Doctor Name:", row[1])print("Hospital Id:", row[2])print("Hospital Name:", hospital_name)print("Joining Date:", row[3])print("Specialty:", row[4])print("Salary:", row[5])print("Experience:", row[6], "\n")close_connection(connection)except (Exception, sqlite3.Error) as error:print("Error while getting doctor's data", error)print("Question 4: Get List of doctors of a given Hospital Id\n")get_doctors(2)
Operation 5: Update doctor experience in years
The value of the experience column for each doctor is null. Implement the functionality to update the experience of a given doctor in years.
import sqlite3import datetimefrom dateutil.relativedelta import relativedeltadef get_connection():connection = sqlite3.connect('python_db.db')return connectiondef close_connection(connection):if connection:connection.close()def update_doctor_experience(doctor_id):# Update Doctor Experience in Yearstry:# Get joining dateconnection = get_connection()cursor = connection.cursor()select_query = """select Joining_Date from Doctor where Doctor_Id = ?"""cursor.execute(select_query, (doctor_id,))joining_date = cursor.fetchone()# calculate Experience in yearsjoining_date_1 = datetime.datetime.strptime(''.join(map(str, joining_date)), '%Y-%m-%d')today_date = datetime.datetime.now()experience = relativedelta(today_date, joining_date_1).years# Update doctor's Experience nowconnection = get_connection()cursor = connection.cursor()sql_select_query = """update Doctor set Experience = ? where Doctor_Id = ?"""cursor.execute(sql_select_query, (experience, doctor_id))connection.commit()print("Doctor Id:", doctor_id, " Experience updated to ", experience, " years")close_connection(connection)except (Exception, sqlite3.Error) as error:print("Error while getting doctor's data", error)print("Question 5: Calculate and Update experience of all doctors \n")update_doctor_experience(101)
