0% found this document useful (0 votes)
2 views10 pages

Intro to Programming m251064

The document outlines a course on Introduction to Programming at Great Zimbabwe University, detailing course information, student details, and various programming exercises. It includes Python code snippets for calculating GCD, checking for prime numbers, finding the second largest number, and creating a basic calculator using Tkinter. Additionally, it covers file handling, error handling, and data analysis tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Intro to Programming m251064

The document outlines a course on Introduction to Programming at Great Zimbabwe University, detailing course information, student details, and various programming exercises. It includes Python code snippets for calculating GCD, checking for prime numbers, finding the second largest number, and creating a basic calculator using Tkinter. Additionally, it covers file handling, error handling, and data analysis tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

GREAT ZIMBABWE UNIVERSITY

SCHOOL OF NATURAL SCIENCES


DEPARTMENT of MATHEMATICS AND COMPUTER
SCIENCE
BACHELOR OF SCIENCE HONOURS DEGREE[COMPUTER
SCIENCE]
BLOCK RELEASE MASVINGO COHORT
Course Information

Course Code ISH 126

Course Title introduction to programming

Year One

Semester One

Lecturer Mr mugomo

STUDENT INFORMATION

Student Name HOVE MITCHELL

Reg Number M251064

Program BSC COMPUTER SCIENCE

Phone Number 0775129602


Question 1.1

def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
num1=int(input("enter the first integer:"))
num2=int(input("enter the second integer:"))
result=gcd(num1,num2)
print(f"The GCD of{num1} and {num2}is{result}")

Qestion 1.2

def is_prime(n):
"""check if a number is prime."""
if n<= 1:
return False
if n <= 3:
return True
if n%2==0 or n%3==0:
return False
i=5
while i*i<=n:
if n%i==0 or n%(i+2)==0:

return False
i += 6
return True
def find_primes(start,end):
"""Find all prime numbers between start and end(inclusive)."""
primes =[]
for num in range(start,end + 1):
if is_prime(num):
primes.append(num)
return primes
try:
num1=int(input("Enter the first number:"))
num2=int(input("Enter the second number:"))
except ValueError:
print("Please enter valid integers.")
exit()
lower=min(num1,num2)
upper=max(num1,num2)
prime_numbers= find_primes(lower,upper)
with open ("primes.txt","w") as file:
for prime in prime_numbers:
file.write(str(prime)+"/n")
print(f"Prime numbers between{lower} and{upper} have been written
to'primes.txt'.")

Question 1.3

def second_largest(numbers):
"""Return the second largest number in the list."""
unique_numbers=list(set(numbers))
if len(unique_numbers)<2:
return None
max_num=max(unique_numbers)
unique_numbers.remove(max_num)
return max(unique_numbers)
user_input=input("Enter a list of numbers seperated by spaces:")
try:
number_list = list(map(float,user_input.strip().split()))
except ValueError:
print("Please enter valid numbers separated by spaces.")
exit()
result=second_largest(number_list)

if result is None:
print("There are not enough unique numbers to determine the second largest.")
else:
print(f"The second largest number is:{result}")

Question 2.1

try:
user_input=input("Please enter an integer:")
number=int(user_input)
print(f"you entered the integer:{number}")
except ValueError:
print("Error: That is not a valid integer.")

Question 2.2

import tkinter as tk
from tkinter import colorchooser
def choose_color():
color_code= colorchooser.askcolor(title="Choose a color")
if color_code:
selected_color=color_code[1]
color_display.config(text=selected_color,bg=selected_color,fg='white',font=('Arial',14))
root=tk.Tk()
root.title("Color Picker Example")
pick_color_button= tk.Button(root,text="Pick a Color",command=choose_color)
pick_color_button.pack(pady=20)
color_display = tk.Label(root,text="No color selected",width=20,height=2,font=('Arial',14))
color_display.pack(pady=10)
root.mainloop()

Question 2.3

import tkinter as tk
from tkinter import colorchooser
def choose_color():
color_code= colorchooser.askcolor(title="Choose a color")
if color_code:
selected_color=color_code[1]
color_display.config(text=selected_color,bg=selected_color,fg='white',font=('Arial',14))
root=tk.Tk()
root.title("Color Picker Example")
pick_color_button= tk.Button(root,text="Pick a Color",command=choose_color)
pick_color_button.pack(pady=20)
color_display = tk.Label(root,text="No color selected",width=20,height=2,font=('Arial',14))
color_display.pack(pady=10)
root.mainloop()
Question3.1

Musoro=(2689.56,2770.38,2394.04,2099.91,3182.20,3267.12,1746.83,2545.72,3328.20,3147.30,2462
.61,3890.45)
Zvagwamba=[1969.62,3939.37,2241.59,3968.27,3068.80,1755.02,3885.66,2491.67,3828.49,3171.32,
2771.32,3380.37]
musoro_more_months = 0
for i in range(len(Musoro)):
if Musoro[i]>Zvagwamba[i]:
musoro_more_months += 1
print("Musoro spent more in",musoro_more_months,"months")

Question 3.2

scores=[('Mike',10),('Mike',8),('Mike',6),('John',7,),('John',8),('John',5),('Tom',8),('Tom',9),('Tom',8)]
total_scores={}
for name, score in scores:
if name in total_scores:
total_scores[name] +=score
else:
total_scores[name]=score
print(total_scores)

Question 3.3

int_list=[1,2,3,4,5]
str_list=(map(str,int_list))
print(str_list)

Question 4.1

numbers=[1,2,3,4,5,6,7,8,9,10]
odd_numbers=[]
even_numbers=[]
for num in numbers:
if num % 2!=0:
odd_numbers.append(num)
else:
even_numbers.append(num)
odd_numbers_tuple=tuple(odd_numbers)
numbers = even_numbers
print("Even numbers:",numbers)
print("Odd numbers tuple:",odd_numbers_tuple)

Question 4.2

input_phrase=input("Enter a word or phrase:")


processed_phrase= join(input_phrase.split()).lower()
if processed_phrase==processed_phrase[::-1]:
print("The input is a palindrome.")
else:
print("The input is not a palindrome.")

Question 4.3

import tkinter as tk
def button_click(item):
current=display.get()
display.delete(0,tk.END)
display.insert(0,current+str(item))
def clear():
display.delete(0,tk.END)
def evaluate():
try:
expression=display.get()
result=eval(expression)
display.delete(0,tk.END)
display.insert(0,str(result))
except ZeroDivisionError:
display.delete(0,tk.END)
display.insert(0,"Error: Div by 0")
except Exception:
display.delete(0,tk.END)
display.insert(0,"Error")
root = tk.Tk()
root.title("Basic Calculator")
display=tk.Entry(root,width=16, font=("Arial",24),bd=2,relief="raised",justify='right')
display.grid(row=0, column=0, columnspan=4)
buttons =[('7',1,0),('8',1,1),('9',1,2),('+',1,3),('4',2,0),('5',2,1),
('6',2,2),('-',2,3),('1',3,0),('2',3,1),('3',3,2),('*',3,3),('0',4,0),('C',4,1),('=',4,2) ,
('/',4,3),]
for (text,row,col) in buttons:
if text =='=':
btn=tk.Button(root,text=text,width=5,height=2,font=("Arial",18),command=evaluate)
elif text=='C':
btn=tk.Button(root,text=text,width=5,height=2,font=("Arial",18),command=clear)
else:
btn=tk.Button(root,text=text,width=5,height=2,font=("Arial",18),command=lambda t=text:
button_click(t))
btn.grid(row=row, column=col)
root.mainloop()

Question 5.1

def power(a,b):
if b == 0:
return 1
elif b < 0:
return1/power(a,-b)
else:
return a*power(a,b-1)
a=float(input("Enter te base number(a):"))
b= int(input("Enter the exponent (b):"))
result=power(a,b)
print("{a}raised to the power of{b} is {result}")

Question 5.2

start=int(input("Enter the first value:"))


end=int(input("Enter the second value:"))
if start > end:
start, end = end, start
total=0
for num in range(start,end + 1):
if num% 2!=0:
total += num
print(f"The sum of all odd numbers between {start} and {end} is {total}"
Question 5.3
def calculate_area(length):
return length*width
def calulate_perimeter(length,width):
return 2 *(length+width)
length =float(input("Enter the length of the rectangle:"))
width=float(input("Enter the width of the rectangle:"))
area=calculate_area(length,width)
perimeter=calculate_perimeter(length,width)
print(f"Area of the rectangle:{area}")
print(f"Perimeter of the rectangle:{perimeter}")

Question 6.1

try:
numerator=float(input("Enter the numerator:"))
denominator=float(input("Enter the denominator:"))
result=numerator/denominator
print(f"The result of{numerator} divided by{denominator} is {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter a valid number.")

Question 6.3

for i in range(1, 13):


print(f"Multiplication Table for {i}")
for j in range(1, 13):
print(f"{i} x {j} = {i * j}")
print("-" * 20)
Question 7.1

def count_lines_in_file(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
print(f"The file '{filename}' contains {len(lines)} lines.")
except FileNotFoundError:
print(f"File '{filename}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

# Example usage:
file_name = input("Enter the path to the .py file: ")
count_lines_in_file(file_name)

Question 7.3

from collections import Counter


number_list = [5, 8, 2, 7, 3, 5, 6, 9, 2, 4, 8, 7, 1, 5, 3]
counts = Counter(number_list)
result = [num for num, count in counts.items() if count >= 3]
print("Numbers that appear 3 or more times:", result)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy