0% found this document useful (0 votes)
16 views8 pages

Python Aiml 4 2

The document contains various Python programming examples focusing on loops, user input, and basic mathematical operations. It includes examples of while loops, for loops, and nested loops, as well as practical applications like a login system and a guessing game. Additionally, it covers the use of libraries such as math and random, along with exercises for user interaction and calculations.

Uploaded by

nikhilys2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views8 pages

Python Aiml 4 2

The document contains various Python programming examples focusing on loops, user input, and basic mathematical operations. It includes examples of while loops, for loops, and nested loops, as well as practical applications like a login system and a guessing game. Additionally, it covers the use of libraries such as math and random, along with exercises for user interaction and calculations.

Uploaded by

nikhilys2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

# -*- coding: utf-8 -*-

"""python_aiml_4_2.ipynb

Note: Dear students, practice all the programs!

"""while loop example #1"""

# Create a program that counts the number of iterations to 10


count = 0
while count < 10:
print("the count is :", count)
#count = count + 1
count += 1

"""'''While Loop - Example 2'''"""

# Create a program that counts the number of iterations to 10 while incrementing by


2

count_2 = 0

while count_2 < 10:


print(count_2)
count_2 = count_2 + 2

"""'''Infinite Loop - Example'''"""

#while True:
#print("infinite loop")

"""'''While Loop and Else - Example'''"""

# Create a program that simulates a washing machine lock


# If a break is inserted in the loop, the else statement will not execute since the
condition was not completed naturally
# Else statement will only execute as long as the condition breask naturally
(without a break statement)
machine_on = True
door_locked = False
time_limit_count = 1
rotation_per_minute = 0

time_limit = int(input("enter a time limit (minutes) for load: "))


time_remaining = time_limit

while (door_locked and machine_on and time_remaining > 0):


rotation_per_minute += 5
time_remaining = time_remaining - time_limit_count
print("time remaining:", time_remaining, "minutes left")
break
else:
print("Machine powering down")

print("number of cycles executed", rotation_per_minute)

"""'''For Loops'''"""

# Iterate over a range of numbers


n = 23
for index in range(0, n, 2):
print("index: ", index)

"""# Iterate from 5 to 12"""

for i in range(5, 13):


print("idex:", i)

# Iterate throgh a list of fruits


fruits = ['apples', 'oranges', 'bananas', 'grapes']
for i in fruits:
print("the fruit purchased are", i)

"""'''Nested Loops'''"""

# Iterate through a range of numbers 1 to 10 in an inner loop


# Iterate through a range of numbers 1 to 5 in an outter loop
for i in range(1,6):
print("outer loop count is", i)
for i in range(1, 11):
print("inner loop count is", i)
print("\n")

"""For this quiz, write a short program that simulates a lock system.

In this program, a user should be able to enter the correct username and password
when prompted to do so.

The user gets three tries to enter the correct username and password.

If the user does not enter the correct username and password in those three login
attempts, display to the screen “LOGIN ATTEMPT FAILED: ACCOUNT IS NOW LOCKED.”

If the user is able to enter the correct username and password, display to the
screen “LOGGING INTO ACCOUNT…”

The program should look like the following:

Welcome to the Lock System!

Please enter your username and password to login to the system.

Enter Username: User inputs username

Enter Password: User inputs password


"""

"""print("Welcome to the lock system ")


print("please enter your username and password to login to the system ")
login_attempts = 0
set_username = "aiml"
set_password = "python"
while login_attempts < 3 :
username = input("enter the username ")
password = input("enter the password ")
login_attempts = login_attempts + 1
if((username == set_username) and (password == set_password)):
print("LOGGING INTO ACCOUNT...")
break
else:
print("incorrect username and password")
else:
print("LOGIN ATTEMPT FAILED. ACCOUNT IS LOCKED. ") """
# Initialize the number of user entries
number_of_tries = 0
set_user_name = "python_student"
set_user_password = "aiml"

# Welcome Message
print("Welcome to the Lock System!")
print("Please enter your username and password to login to the system.\n")

while number_of_tries < 3:


# Enter username and password
user_name = input("Enter Username: ")
user_password = input("Enter Password: ")
number_of_tries += 1

if ((user_name == set_user_name) and (user_password == set_user_password)):


print("LOGGING INTO ACCOUNT...")
break
else:
print("Incorrect username or password.\n")

else:
print("LOGIN ATTEMPT FAILED. ACCOUNT IS NOW LOCKED.")

# This program will ask the user to guess the correct password. If the user.
# does not enter the correct password in 3 attempts, they lose the game.
# Guessing Game
number_of_attempts = 0
password = "gameover"
print("welcome to the guessing game ")
while number_of_attempts < 3:
user_input = input("enter guess..!")
number_of_attempts += 1
if user_input == password :
print("you win ")
break
else:
print("try again")
else:
print("you loose")

"""Math Library Functions"""

import math

# take the square root of 81


x = math.sqrt(81)
print("square root of 81: ", x)

#take the floor of 2.3


#floor will give you the least value
print("floor of 2.3 ", math.floor(2.3))
#take the ceil of 2.3
#ceil will give you the highest value
print("ceil of 2.3", math.ceil(2.3))

# exponent example: 3**2 using math.pow


print("3 is raised to power of 2", math.pow(3,2))

#constants print the value of pi


print("pi value ", math.pi)

# print the value of epsilon


print("epislon value", math.e)

"""# import math using a shorter name (this is another option you can use)"""

import math as m

print(m.sqrt(25))
print(math.sqrt(25))

"""# now import a few functions from math using from"""

from math import sqrt, pow

x = sqrt(25)
y = pow(5,2)
print(x)
print(y)

"""# find all the functions available in the math library"""

help('math')

"""Random librabry examples

"""

import random

#print a random value from a list of integers

my_list = [11, 24, 23, 30]


print(random.choice(my_list))

# print the random value from a tuple


import random

my_tuple = (22.4, 19.4, 31.5, 33.2)


print(random.choice(my_tuple))

"""**random.seed()** method in Python is used to initialize the random number


generator, ensuring the same random numbers on every run. By default, Python
generates different numbers each time, but using .seed() allows result
reproducibility.
It’s most commonly used in:
*Machine Learning*- to ensure model consistency
*Simulations*- to repeat experiments
*Game Development*- for consistent gameplay mechanics during testing
*Testing*- to verify output correctness
"""

# random numbers depend on a seeding value


# when the seed value is 5, the number generated will always be the same
#In Python, a "seed value" is used with the random module to initialize the pseudo-
random number generator,
#ensuring repeatable results when the same seed is used across different runs.
import random
random.seed(5)

print(random.random())
print(random.random())

# Generate a random integer using randint() which takes in a range of integers


import random
print(random.randint(1,5))
print(random.randint(-7,-3))

# Generate a random float between 0.0 to 1 value using random()


import random
print(random.random())

# Shuffle a list using the random library


import random
fruits = ['apples', 'oranges', 'grapes', 'lemons']
print("List before shuffle", fruits)
random.shuffle(fruits)
print("List after shuffle", fruits)

# Create a program that generates ten random integer values. Display these ten
generated numbers to the screen\n"
import random
random_list_1 = []
for i in range(0,10):
random_number = random.randint(1, 20)
random_list_1.append(random_number)
print(random_list_1)

"""#random module seed value example"""

import random

# Set the seed


random.seed(20) # Or any integer you choose

# Generate some random numbers


print(random.randint(1, 10))
print(random.random())

# The same seed will produce the same sequence of random numbers
random.seed(20)
print(random.randint(1, 10))
print(random.random())

import random

for i in range(2):
# Generated random number will be between 1 to 1000 but different in every run.
print(random.randint(1, 1000))

for i in range(2):
# Any number can be used in place of '0'.
random.seed(2)
# Generated random number will be between 1 to 1000 but same in every run.
print(random.randint(1, 1000))

"""1)write a python program to add n numbers accepted from the user"""

# Program to add n numbers provided by the user

# Get the number of elements to add


n = int(input("How many numbers do you want to add? "))

# Initialize sum variable


total_sum = 0

# Loop to accept n numbers and add them


for i in range(n):
num = float(input(f"Enter number {i+1}: ")) # Accept each number as a float
total_sum += num # Add the number to the total sum

# Output the result


print(f"The sum of the {n} numbers is: {total_sum}")

"""2)write a python program to check armstrong number


#An Armstrong number is a number that is equal to the sum of its own digits each
raised to the power of the number of digits.
For example:

153 is an Armstrong number. 1^3 + 5^3 + 3^3 = 153.

"""

# Taking user input


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

# Convert number to string to find the number of digits


num_str = str(num)
num_digits = len(num_str)

# Initializing sum and temp variable


sum = 0
temp = num

# Loop to calculate the sum of digits raised to the power of num_digits


while temp > 0:
digit = temp % 10 # Get the last digit
sum = sum + digit ** num_digits # Add the digit raised to the power of
num_digits to sum
temp //= 10 # Remove the last digit

# Check if the number is equal to the sum of its digits raised to the power of
num_digits
if num == sum:
print(f"{num} is an Armstrong number!")
else:
print(f"{num} is not an Armstrong number.")

"""1)a). Develop a program to read the student details like Name, USN, and Marks in
three subjects. Display the student details, total marks and percentage with
suitable messages."""

studentname = input('Enter the Name of the student: ')


usn = input('Enter the USN of the student: ')
m1 = int(input('Enter the mark in first subject: '))
m2 = int(input('Enter the mark in second subject: '))
m3 = int(input('Enter the mark in third subject: '))
total = m1+m2+m3
percentage = round((total/300)*100)
print('\nName of the Student: ', studentname)
print('USN: ', usn)
print('Mark in Subject 1: ', m1)
print('Mark in Subject 2: ', m2)
print('Mark in Subject 3: ', m3)
print('Total Score = ', total)
print('Percentage = ', percentage)
if percentage >=90:
print('First Class Exemplary.')
elif percentage >=75 and percentage <90:
print('First Class with Distinction.')
elif percentage >=60 and percentage <75:
print('First Class.')
elif percentage >=35 and percentage <60:
print('Second Class.')
else:
print('work hard to pass.')

"""1)b.) Develop a program to read the name and year of birth of a person. Display
whether the person is a senior citizen or not."""

person_name = input('Enter the Name of the person: ')


year_of_birth = int(input('Enter the Year of Birth: '))
#currentyear = 2025
current_year = int(input('Enter the current year: '))
age = current_year - year_of_birth
print('\nName of the person: ', person_name)
print('Year of Birth of the person: ', year_of_birth)
print('Age of the person: ', age)
if age >= 60:
print('The person is a Senior Citizen.')
else:
print('The person is not a Senior Citizen.')

"""**TEST:**

1) Write a Python Program to add n numbers accepted from the user


2) python program to check Armstrong number.
#An Armstrong number is a number that is equal to the sum of its own digits each
raised to the power of the number of digits.
For example: 153 is an Armstrong number. 1^3 + 5^3 + 3^3 = 153.
3) Python program to check prime number
4) Python program to convert decimal into binary, octal and hexadecimal.
5) Python program to count number of digits in a number.
6) Python program to check if a number is positive, negative and zero.
7) Program to print the first 5 multiples of any number
8) Program to print all letters except 'e' and 'o' from the user's input
9) Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.

MODULE1 Questions:
1) Explain with an example: a) input() b) print() c) len() d) format() e) range()
f) sys.exit()
2) Explain in brief string concatenation and string replication with two examples.
3) Explain if, elif, for, while, break and continue statements with examples and
flowcharts.

"""

You might also like