__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Techno solutions PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> what is randint() module?
--> Errors and Exceptions
--> Program demonstrating the ValueError
--> Program demonstrating the TypeError
--> Examples
"""
""" random module """
import random, string # python in-built modules /Internal modules
from random import randint, choice
# from string import *
"""
randint() is an inbuilt function of the random module in Python3.x
Syntax : randint(start, end) # Note for arguments : (start, end) : Both of them must be integer type values.
Returns: A random integer within the given range as arguments.
Errors and Exceptions :
ValueError : Returns a TypeError when anything other than numeric values are passed as arguments.
TypeError : Returns a ValueError when floating point values are passed as arguments.
"""
# # Generates a random number between +ve values
start_val, end_val = 50, 100
rand_num = random.randint(start_val, end_val) # a given positive range
# print("Random number between {} and {} is {}".format(start_val, end_val, rand_num))
# print(f"Random number between {start_val} and {end_val} is {rand_num}") #this line also .format
# # Generates a random number between -ve values
start_val, end_val = -10, -1 # Initialization
# rand_num = random.randint(start_val, end_val) # two given negative range
# print("Random number between {} and {} is {}".format(start_val, end_val, rand_num))
# # Generates a random number between negative and positive range
start_val, end_val = -15, 15 # Initialization
rand_num = random.randint(start_val, end_val)
# print(f"Random number between {start_val} and {end_val} is {rand_num}")
"""Code #2 : Program demonstrating the TypeError : Returns a TypeError when floating point values are passed as arguments.
If we pass floating point values as parameters in the randint() function"""
start_val, end_val = 1, 6.5 # Initialization
#
# rand_num = randint(start_val, end_val)
# print(rand_num) # it will give ValueError
# print("jaya")
# print("Kavya and Kruthika")
# print("Narendra")
# Output :
# Traceback (most recent call last):
# File "E:\Narendra_Training_Data\Narendra_Python_Training_Mar_2025\Class_31_random_string_module\random_string_module.py", line 53, in <module>
# rand_num = randint(start_val, end_val)
# File "C:\Users\Narendra\AppData\Local\Programs\Python\Python313\Lib\random.py", line 340, in randint
# return self.randrange(a, b+1)
# ~~~~~~~~~~~~~~^^^^^^^^
# File "C:\Users\Narendra\AppData\Local\Programs\Python\Python313\Lib\random.py", line 305, in randrange
# istart = _index(start)
# TypeError: 'float' object cannot be interpreted as an integer
"""Code #2 : Program demonstrating the TypeError
If we pass floating point values as parameters in the randint() function"""
start_val, end_val = 'swetha', 'meera' # Initialization
# rand_num = randint(start_val, end_val)
# print(rand_num) # it will give ValueError
# print("jaya")
# print("Kavya and Kruthika")
# print("Narendra")
# Output :
# Traceback (most recent call last):
# File "E:\Narendra_Training_Data\Narendra_Python_Training_Mar_2025\Class_31_random_string_module\random_string_module.py", line 52, in <module>
# rand_num = randint(start_val, end_val)
# File "C:\Users\Narendra\AppData\Local\Programs\Python\Python313\Lib\random.py", line 340, in randint
# return self.randrange(a, b+1)
# ~^~
# TypeError: can only concatenate str (not "int") to str
"""By using exception concept we can continue to execute remaining code"""
# start_val, end_val = 12, 5.6 # Initialization
# try:
# rand_num = randint(start_val, end_val)
# print(rand_num)
# # except TypeError as err_info:
# # print(err_info)
# # print("Wrong iput values Provided")
# # except ValueError as err_info:
# # print(err_info)
# except Exception as error_info:
# print(error_info, "--> user has to provide integer values")
# print("Meera")
# print("Kavya and Kruthika")
# print("Narendra")
from random import randint # importing randint function
# print(randint(2, 7)) # generate random +ve number
# print(randint(-10, -1)) # generate random -ve number
# print(randint(-5, 5)) # generate random +ve / -ve number
""" Write a Function which generates required no of random_numbers in the given range"""
def rand_int_generator(start_val, end_val, num_of_vals):
"""
:param start_val: should provide staring integer value
:param end_val:should provide ending integer value
:param num_of_vals: how many values you want ?
:return: Will generate list of random integer values, for the provided range of a, b
"""
random_numbers_list = []
for element in range(num_of_vals): # range(4)--> range(0,4) -->[0,1,2,3]
try:
result = randint(start_val,end_val)
random_numbers_list.append(result) # all the required random values will append to single list
except Exception as error_info:
print(error_info)
return random_numbers_list
# random_numbers_list = rand_int_generator(2, 19.9, 14)
# print(random_numbers_list)
# print("venkat ")
# print("sujana")
# print("ganesh, rindha and priyanka")
""" Write a Function which generates required no of random_numbers in the given range"""
# start_val, end_val, num_of_vals = 2, 199, 10
# print([randint(start_val, end_val)for element in range(num_of_vals)]) # list comprehension
"""
Let’s say User has participated in a lucky draw competition.
The user gets three chances to guess the number between 1 and 10.
If guess is correct user wins, else loses the competition."""
def rand_guess():
"""
True : If win-condition is satisfied then, the function rand_guess returns True
False: If user's choice doesn't match, win-condition then it is printed
:return: this function returns True or False
"""
# calls generator() which returns a random integer between 1 and 10
machine_chosen_random_number = randint(1, 10)
# defining the number of guesses the user gets
guess_left = 3
# Setting a flag variable to check the win-condition for user
flag = 0
# looping the number of times the user gets chances
while guess_left > 0:
# Taking a input from the user
user_guess_value = int(input("Pick your number to enter the lucky draw : "))
# checking whether user's guess matches the generated win-condition
if user_guess_value == machine_chosen_random_number:
# setting flag as 1 if user guessses correctly and then loop is broken
flag = 1
break
else:
# If user's choice doesn't match, win-condition then it is printed
print("Wrong Guess!!")
# # Decrementing number of guesses left by 1
guess_left -= 1 # guess_left = guess_left - 1 ( assignment operator)
# If win-condition is satisfied then, the function rand_guess returns True
if flag == 1:
return True
# Else the function returns False
else:
return False
if __name__ == '__main__':
if rand_guess() is True:
print("Congrats!! You Win.")
else:
print("Sorry, You Lost!")
# Output :
#
# Pick your number to enter the lucky draw
# 8
# Wrong Guess!!
# Pick your number to enter the lucky draw
# 9
# Wrong Guess!!
# Pick your number to enter the lucky draw
# 0
# Congrats!! You Win.==================================================================================
String_module
==================================================================================__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> string modules : ascii_uppercase, ascii_lowercase, ascii_letters, digits, punctuation, whitespace, printable
--> practice program
"""
""" string module"""
import string
from random import choice, randint
# print(string.ascii_uppercase) # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# print(string.ascii_lowercase) # 'abcdefghijklmnopqrstuvwxyz'
# print(string.ascii_letters) # 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
# print(string.digits) # '0123456789'
# print(string.punctuation) # r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
# print(string.whitespace) # ' \t\n\r\v\f'
# print(string.printable) # digits + ascii_letters + punctuation + whitespace
"""============== from string import * ==============================="""
from string import *
# print(ascii_uppercase) # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# print(ascii_lowercase) # 'abcdefghijklmnopqrstuvwxyz'
# print(ascii_letters) # 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
# print(digits) # '0123456789' --> it will give digits as string format
# print(punctuation) # r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
# print(whitespace) # ' \t\n\r\v\f'
# print(printable) # digits + ascii_letters + punctuation + whitespace
# #=========================================================================
# user_data_1 = string.ascii_letters + string.punctuation + string.digits # import string
# print(user_data_1)
user_data = ascii_letters + punctuation + digits # from string import *
user_data = ascii_letters + "^@$%" + digits # used for password generation
# user_data = ascii_letters + digits # used for captcha generation
# print(user_data)
# print(choice(user_data)) # from random import choice --> gives random character from input_data
""" Practice programs"""
# print([randint(10, 200)for i in range(6)]) # list comprehension
# OTP /capche generation
# print([choice(user_data) for no_of_vals in range(6)])
# print("".join([choice(user_data) for no_of_char in range(6)]))
No comments:
Post a Comment