w3resource

Python: Generate a random color hex, alphabetical string, random value and multiple of 7


1. Random Value Generation

Write a Python program to generate a random color hex, a random alphabetical string, random value between two integers (inclusive) and a random multiple of 7 between 0 and 70.

Use random.randint()

Sample Solution:

Python Code:

import random
import string
print("Generate a random color hex:")
print("#{:06x}".format(random.randint(0, 0xFFFFFF)))
print("\nGenerate a random alphabetical string:")
max_length = 255
s = ""
for i in range(random.randint(1, max_length)):
    s += random.choice(string.ascii_letters)
print(s)
print("Generate a random value between two integers, inclusive:")
print(random.randint(0, 10))
print(random.randint(-7, 7))
print(random.randint(1, 1))
print("Generate a random multiple of 7 between 0 and 70:")
print(random.randint(0, 10) * 7)

Sample Output:

Generate a random color hex:
#eb76d4

Generate a random alphabetical string:
lGhPpBDqfCgXKzSbGcnmcDWBEZeiqcUqztgvwcXfVyPslOggKdbIxOejJfFMgspqrgskanNYpscJEOVIpYkGGNxQlaqeeubGDbQSBhBedrdOyqOmKPTZvzKmKVoidsuShSCapEXxxNJRCxXOwYUUPBefKmJiidGxHwvOxAEujZGjJjTqjRtuEXgyRsPQpqlqOJJjKHAPHmIJLpMvLTRVqwSeLCIDRdMnYpbg
Generate a random value between two integers, inclusive:
0
4
1
Generate a random multiple of 7 between 0 and 70:
70

Flowchart:

Flowchart: Generate a random color hex, alphabetical string, random value and random multiple of 7

For more Practice: Solve these Related Problems:

  • Write a Python program to generate a random hex color code and then verify that its length is 7 (including the '#' symbol).
  • Write a Python script that creates a random alphabetical string of length 10 and a random integer between two bounds, then outputs both in a formatted message.
  • Write a Python function that generates a random multiple of 7 between 0 and 70 and also a random integer between 100 and 200 using random.randint(), and prints their sum.
  • Write a Python program that generates a random color hex, a random alphabetical string, and a random integer between 50 and 100, then concatenates them into a single string output.

Go to:


Previous: Python module methods Exercise Home.
Next: Write a Python program to select a random element from a list, set, dictionary (value) and a file from a directory.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.