Python-2 Unit-6 Random

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Random

In [2]:

1 import random
2 print(random.random())

0.4712911061710572

Seed
In [31]:

1 import random
2 random.seed(10)
3 print(random.random())

0.5714025946899135

In [81]:

1 import random
2
3 random.seed(10)
4 print(random.random())
5
6 random.seed(30)
7 print(random.random())
8
9 print(random.random())

0.5714025946899135
0.5390815646058106
0.2891964436397205

In [84]:

1 import random
2
3 random.seed(10)
4 print(random.random())
5
6 random.seed(30)
7 print(random.random())
8
9 random.seed()
10 print(random.random())

0.5714025946899135
0.5390815646058106
0.0028110627162818425
Choice
In [109]:

1 import random
2
3 x = "WELCOME"
4
5 print(random.choice(x))

In [124]:

1 import random
2 mylist = ["apple", "banana", "cherry"]
3 print(random.choice(mylist))

apple

In [132]:

1 import random
2 x=["apple"]
3 print(random.choice(x))

apple

randint
In [161]:

1 import random
2 x=random.randint(3,9)
3 print(x)

In [210]:

1 import random
2 x=random.randrange(3,9,3)
3 print(x)

6
shuffle
In [314]:

1 import random
2
3 def myfunction():
4 return 0.9
5 #Here myfunction is argument not function called
6 #Here myfunction is written or passed as an argument so it will give same list by ru
7
8 mylist = ["apple", "banana", "cherry"]
9 random.shuffle(mylist,myfunction)
10
11 print(mylist)

['apple', 'banana', 'cherry']

C:\Users\pdsin\AppData\Local\Temp\ipykernel_8468\1355317860.py:9: Deprecat
ionWarning: The *random* parameter to shuffle() has been deprecated
since Python 3.9 and will be removed in a subsequent version.
random.shuffle(mylist,myfunction)

In [293]:

1 import random
2
3 random.seed(13)
4 #Here myfunction is argument not function called
5 #Here myfunction is written or passed as an argument so it will give same list by ru
6
7 mylist = ["apple", "banana", "cherry"]
8 random.shuffle(mylist)
9
10 print(mylist)

['apple', 'cherry', 'banana']

In [304]:

1 import random
2
3 mylist = ["apple", "banana", "cherry"]
4 random.shuffle(mylist)
5
6 print(mylist)

['cherry', 'banana', 'apple']


In [305]:

1 help(random.shuffle)

Help on method shuffle in module random:

shuffle(x, random=None) method of random.Random instance


Shuffle list x in place, and return None.

Optional argument random is a 0-argument function returning a


random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.

Mystical Octosphere
In [5]:

1 import random
2 def number_to_fortune(number):
3 if number == 0:
4 return 'Yes, for sure!!'
5 elif number == 1:
6 return 'Probably yes..'
7 elif number == 2:
8 return 'Seems like yes..'
9 elif number == 3:
10 return 'Definitely not!!'
11 elif number == 4:
12 return 'Probably not.'
13 elif number == 5:
14 return 'I really doubt it...'
15 elif number == 6:
16 return 'Not sure, check back later!'
17 elif number == 7:
18 return "I really can't tell."
19
20 def mystical_octosphere(question):
21 print('Your question was...',question)
22 answer_number = random.randrange(0,8)
23 answer_fortune = number_to_fortune(answer_number)
24 print('The mystical octosphere says...',answer_fortune)
25
26 question = input('Enter your question: ')
27 mystical_octosphere(question)

Enter your question: Will it Rain today?


Your question was... Will it Rain today?
The mystical octosphere says... Probably yes..

Number guessing game


In [315]:

1 import random
2
3 def number_guessing_game():
4 secret_number = random.randint(1, 100)
5 attempts = 0
6
7 print("Welcome to the Number Guessing Game!")
8 print("I'm thinking of a number between 1 and 100.")
9
10 while True:
11 guess = int(input("Take a guess: "))
12 attempts += 1
13
14 if guess < secret_number:
15 print("Too low! Try a higher number.")
16 elif guess > secret_number:
17 print("Too high! Try a lower number.")
18 else:
19 print(f"Congratulations! You guessed the number in {attempts} attempts."
20 break
21
22 number_guessing_game()
23

Welcome to the Number Guessing Game!


I'm thinking of a number between 1 and 100.
Take a guess: 50
Too low! Try a higher number.
Take a guess: 60
Too high! Try a lower number.
Take a guess: 55
Too low! Try a higher number.
Take a guess: 56
Too low! Try a higher number.
Take a guess: 57
Too low! Try a higher number.
Take a guess: 58
Congratulations! You guessed the number in 6 attempts.

Rock, Paper Scissors


In [319]:

1 import random
2
3 def rock_paper_scissors():
4 choices = ["rock", "paper", "scissors"]
5 computer_choice = random.choice(choices)
6
7 print("Welcome to Rock-Paper-Scissors!")
8 print("Choose one: rock, paper, or scissors.")
9
10 player_choice = input("Your choice: ").lower()
11
12 if player_choice not in choices:
13 print("Invalid choice. Please try again.")
14 return
15
16 print("Computer chooses:", computer_choice)
17
18 if player_choice == computer_choice:
19 print("It's a tie!")
20 elif (player_choice == "rock" and computer_choice == "scissors") or \
21 (player_choice == "paper" and computer_choice == "rock") or \
22 (player_choice == "scissors" and computer_choice == "paper"):
23 print("You win!")
24 else:
25 print("Computer wins!")
26
27 rock_paper_scissors()
28

Welcome to Rock-Paper-Scissors!
Choose one: rock, paper, or scissors.
Your choice: paper
Computer chooses: rock
You win!

Dice Rolling Game


In [320]:

1 import random
2
3 def dice_rolling_game():
4 print("Welcome to the Dice Rolling Game!")
5 print("Press enter to roll the dice. Enter 'q' to quit.")
6
7 while True:
8 user_input = input()
9
10 if user_input.lower() == 'q':
11 break
12
13 dice_value = random.randint(1, 6)
14 print("You rolled:", dice_value)
15
16 print("Thank you for playing!")
17
18 dice_rolling_game()
19

Welcome to the Dice Rolling Game!


Press enter to roll the dice. Enter 'q' to quit.

You rolled: 3

You rolled: 3

You rolled: 2

You rolled: 4

You rolled: 5

You rolled: 5

You rolled: 4

You rolled: 6
q
Thank you for playing!

Word Guessing Game


In [321]:

1 import random
2
3 def word_guessing_game():
4 words = ["apple", "banana", "orange", "grape", "melon"]
5 secret_word = random.choice(words)
6 attempts = 0
7 guessed_letters = []
8
9 print("Welcome to the Word Guessing Game!")
10 print("Guess the secret word by entering one letter at a time.")
11
12 while True:
13 display_word = ""
14 for letter in secret_word:
15 if letter in guessed_letters:
16 display_word += letter
17 else:
18 display_word += "_"
19
20 print("Secret word:", display_word)
21
22 if "_" not in display_word:
23 print("Congratulations! You guessed the word.")
24 break
25
26 guess = input("Enter a letter: ").lower()
27
28 if guess.isalpha() and len(guess) == 1:
29 if guess in guessed_letters:
30 print("You already guessed that letter. Try again.")
31 else:
32 attempts += 1
33 guessed_letters.append(guess)
34
35 if guess in secret_word:
36 print("Correct guess!")
37 else:
38 print("Wrong guess!")
39 else:
40 print("Invalid input. Please enter a single letter.")
41
42 print("Thank you for playing! You took", attempts, "attempts.")
43
44 word_guessing_game()
45
Welcome to the Word Guessing Game!
Guess the secret word by entering one letter at a time.
Secret word: ______
Enter a letter: a
Correct guess!
Secret word: __a___
Enter a letter: b
Wrong guess!
Secret word: __a___
Enter a letter: o
Correct guess!
Secret word: o_a___
Enter a letter: r
Correct guess!
Secret word: ora___
Enter a letter: n
Correct guess!
Secret word: oran__
Enter a letter: ge
I lid i t Pl t i l l tt

Rock, Paper Scissors, Spock, Lizard


In [322]:

1 import random
2
3 def rock_paper_scissors_spock_lizard():
4 choices = ["rock", "paper", "scissors", "spock", "lizard"]
5 win_conditions = {
6 "rock": ["scissors", "lizard"],
7 "paper": ["rock", "spock"],
8 "scissors": ["paper", "lizard"],
9 "spock": ["scissors", "rock"],
10 "lizard": ["paper", "spock"]
11 }
12
13 print("Welcome to Rock-Paper-Scissors-Spock-Lizard!")
14 print("Choose one: rock, paper, scissors, spock, or lizard.")
15
16 player_choice = input("Your choice: ").lower()
17
18 if player_choice not in choices:
19 print("Invalid choice. Please try again.")
20 return
21
22 computer_choice = random.choice(choices)
23 print("Computer chooses:", computer_choice)
24
25 if player_choice == computer_choice:
26 print("It's a tie!")
27 elif computer_choice in win_conditions[player_choice]:
28 print("You win!")
29 else:
30 print("Computer wins!")
31
32 rock_paper_scissors_spock_lizard()
33

Welcome to Rock-Paper-Scissors-Spock-Lizard!
Choose one: rock, paper, scissors, spock, or lizard.
Your choice: rock
Computer chooses: spock
Computer wins!

Random Password Generator


In [ ]:

1 def generate_random_password(length):
2 characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$
3 password = ''.join(random.choice(characters) for _ in range(length))
4 return password
5
6 def check_password_strength(password):
7 length = len(password)
8 has_upper = any(char.isupper() for char in password)
9 has_lower = any(char.islower() for char in password)
10 has_digit = any(char.isdigit() for char in password)
11 has_special = any(char in "!@#$%^&*()_-+=[]{}|:;,.<>?/" for char in password)
12 print(has_upper)

In [4]:

1 import random
2 characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*
3 password = ''.join(random.choice(characters) for _ in range(10))
4 has_upper = any(char.isupper() for char in password)
5 print(has_upper)
6 print(password)

True
9d&Va4gJP$

Card Deck Shuffling


In [2]:

1 import random
2 suits=['♥','♦','♣','♠']
3 ranks=['Ace','1','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
4 deck=[(rank,suit) for suit in suits for rank in ranks]
5 random.shuffle(deck)
6 for card in deck:
7 print(card[0],'of',card[1])
8 of ♣
Queen of ♥
Ace of ♦
1 of ♥
6 of ♠
9 of ♣
Jack of ♣
Jack of ♦
3 of ♣
10 of ♠
7 of ♣
3 of ♠
1 of ♠
3 of ♥
5 of ♦
1 of ♦
Queen of ♣
4 of ♦
8 of ♥
9 of ♠
10 of ♣
6 of ♣
Ace of ♣
8 of ♠
2 of ♣
9 of ♦
1 of ♣
4 of ♠
Queen of ♦
Jack of ♠
4 of ♥
10 of ♥
7 of ♠
4 of ♣
3 of ♦
Jack of ♥
Queen of ♠
10 of ♦
2 of ♥
King of ♥
5 of ♥
2 of ♦
King of ♠
7 of ♥
5 of ♣
Ace of ♠
7 of ♦
5 of ♠
8 of ♦
2 of ♠
9 of ♥
King of ♦
King of ♣
6 of ♦
6 of ♥
Ace of ♥

You might also like