Jump to content
import random
random_name = random.randint(1, 3)
random_question = random.randint(1, 3)
# print(random_question) Used to test if random number is working.
## name = "" and name = "Alex" is being used to test if questions print without a name.
name = ""
name = "Alex"
name = "Steve"
if random_name == 1:
  name == 1
  print(" ")
elif random_name == 2:
  name == 2
  print("Alex")
elif random_name == 3:
  name == 3
  print("Steve")
else:
  name == ("Please provide a name")
question = ""
print(name,  "Asks: ",  question)
if random_question == 1:
  question = 1
  print("Is today Wednesday?")
elif random_question == 2:
  question = 2
  print("Is 28 an old age")
elif random_question == 3:
  question = 3
  print("did this work")
else:
  random_question == "Error"
#The above should print differer 3 Questions and an error, Below should answer 9 different Questions and give an error.#
random_number = random.randint(1, 9)
answer = ""
print("Magic 8-Ball's answer: ", answer)
if random_number == 1:
  answer = 1
  print("Yes - definitely")
elif random_number == 2:
  answer = 2
  print("It is decidedly so.")
elif random_number == 3:
  answer = 3
  print("Without a doubt.")
elif random_number == 4:
  answer = 4
  print("Reply hazy, try again.")
elif random_number == 5:
  answer = 5
  print("Ask again later.")
elif random_number == 6:
  answer = 6
  print("Better not tell you now.")
elif random_number == 7:
  answer = 7
  print("My sources say no.")
elif random_number == 8:
  answer = 8
  print("Outlook not so good.")
elif random_number == 9:
  answer = 9
  print("Very doubtful.")
else:
  answer = "Error"

Hi, so i'm learning pythong currently and been set with the task of creating a magic 8 ball, i've managed to get it working for 1 name to output 3 different questions with 9 possible answers, now ive been tasked with printing out the questions without a name but instead its printing 2 different names with a different question and answer each time. does anybody know why my code wont ask a question with a blank name.

 

 

image.thumb.png.b7c1f30a74fd14007e06c14b973f198d.png

 

#Murica(butinternational)parrotgang

Link to comment
https://linustechtips.com/topic/1415063-magic-8-ball-python3/
Share on other sites

Link to post
Share on other sites

23 minutes ago, Alexsheff93 said:

but instead its printing 2 different names with a different question and answer each time.

 

name = ""
name = "Alex"
name = "Steve"

This assigns a value to "name", but it will always take the last assignment, so the value of name will always be "Steve".

 

if random_name == 1:
  name == 1
  print(" ")
elif random_name == 2:
  name == 2
  print("Alex")
elif random_name == 3:
  name == 3
  print("Steve")
else:
  name == ("Please provide a name")

This checks the value of random name (good so far, except it's ignoring "name" from before now). In each block, you do a Boolean evaluation of "name" (hint: '=' is assignment, '==' is comparison), which doesn't return or modify anything, then prints the hardcoded line.

 

print(name,  "Asks: ",  question)

Because you never changed the assignment of "name", it's still "Steve" from before. However, if you change the previous block to have correct assignments, "name" is now a number?

 

if random_question == 1:
  question = 1
  print("Is today Wednesday?")
elif random_question == 2:
  question = 2
  print("Is 28 an old age") // No, it isn't ;)
elif random_question == 3:
  question = 3
  print("did this work")
else:
  random_question == "Error"

Why are you assigning a value to "question" that never gets used? Also, technically the final else is unneeded because you constrained the input values to 1-3, but not technically a bad idea.

 

answer = ""
print("Magic 8-Ball's answer: ", answer)

Don't bother printing the empty string of answer because it will never be defined other than that.

 

if random_number == 1:
  answer = 1
  print("Yes - definitely")
elif random_number == 2:
  answer = 2
  print("It is decidedly so.")
...

Again, don't assign a value to "answer" that will never be used.

Main System (Byarlant): Ryzen 9 5950X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 32GB G.Skill DDR4 3600MT/s CL16 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 990 EVO Plus 4TB | Corsair RM750X | StarTech 4× USB 3.0 Card | Realtek RTL8127 10G NIC | Hyte Y60 Case | Dell U3415W Monitor | Keychron K12 Blue (RGB backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB DDR4 3200MT/s (soldered) | Vega II 384SP Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi | Asus 2.5G USB NIC | Asus ProArt PA278QV | Keychron K4 Brown (white backlight)

 

Proxmox Server (Veda): Ryzen 7 3800XT | ASRock Rack X470D4U | Corsair H80i v2 | 128GB Micron DDR4 ECC 3200MT/s | 2× Samsung PM963a 960GB SSD / 4× WD 10TB / 4× Seagate 14TB Exos / 4× Micron MX500 2TB / 8× WD 12TB (custom external SAS enclosure) | Seasonic Prime Fanless 500W | Intel X550-T2 10G NIC | LSI 9300-8i HBA | Adaptec 82885T SAS Expander | Fractal Design Node 804 Case

 

Proxmox Server (La Vie en Rose)GMKtec Mini PC | Ryzen 7 5700U | 32GB Lexar DDR4 (SODIMM) | Vega II 512SP Graphics | Lexar 1TB 610 Pro SSD | 2× Realtek 8125 2.5G NICs


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / TEAMGROUP MS30 1TB | Corsair CX450M | Viewcast Osprey 260e Video Capture | TrendNet (AQC107) 10G NIC | LG WH14NS40 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Workbench (Doven Wolf): Lenovo m715q | Ryzen Pro 3 2200GE | 16GB Crucial DDR4 3200MT/s (SODIMM) | Vega 8 Graphics | SKHynix (OEM) 256GB NVMe SSD | uni 2.5G USB NIC | HDMI add-in module

 

Network:

Spoiler
                       ┌─────────────── Office/Rack ───────────────────────────────────────────────┐
Google Fiber Webpass ── Cloud Gateway Max ══╦═ Pro XG 8 ══╦═ Flex 2.5-8 ══╦═ Doven Wolf
                      La Vie en Rose (DNS) ═╬═ Narrative  ╠═ Veda-NAS     ╠═ La Vie en Rose (vmbr)
                                Veda (DNS) ─┘             ╠═ Veda (vmbr)  ├─ Ptolemy (vmbr)
╔═════════════════════════════════════════════════════════╩═ Ptolemy-NAS  ├─ Veda (Mgmt)
║   ┌ Closet ┐      ┌───────── Bedroom ─────────┐                         └─ Veda (IPMI)
╚═══ Flex XG ══╦╤═══ Flex XG ══╤╦═ Byarlant
       (PoE)   ║│              │╠═ Narrative 
Kitchen Jack ══╣└─ Dual PoE ┐  │╚═ Jesta Cannon*
   (Testing)   ║┌─ Injector ┘  └── Work Laptop
     Bedroom ══╝│        ┌─────── Media Center ────────────────────────────┐
     Jack #2    └──────── Switch 8 ────────────┬─ nanoHD Access Point (PoE)
Notes:                                         ├─ Sony PlayStation 4 
─── is Gigabit / ═══ is Multi-Gigabit          ├─ Pioneer VSX-S520
* = cable passed from Bedroom to Media Center  └─ Sony XR65A80K (Google TV)
Link to comment
https://linustechtips.com/topic/1415063-magic-8-ball-python3/#findComment-15283636
Share on other sites

Link to post
Share on other sites

3 hours ago, Alexsheff93 said:
name = ""
name = "Alex"
name = "Steve"

Why are you assigning this 3 times in a row? This is the same as just doing

name = "Steve"
3 hours ago, Alexsheff93 said:
elif random_name == 2:
  name == 2	# <- C
  print("Alex")	# <- A
elif random_name == 3:
  name == 3	# <- C
  print("Steve")
else:
  name == ("Please provide a name")	# <- C
question = ""
print(name,  "Asks: ",  question)	# <- B

At A you print "Alex" and at B you print whatever is in the variable name, which is "Steve" as I pointed out above. At every instance of C you're not assigning any value to name, since you're using == instead of =.

3 hours ago, Alexsheff93 said:
question = ""
print(name,  "Asks: ",  question)

You set question to "" every time you go through here so you'll always print nothing.

3 hours ago, Alexsheff93 said:
if random_question == 1:
  question = 1
  print("Is today Wednesday?")
elif random_question == 2:
  question = 2
  print("Is 28 an old age")
elif random_question == 3:
  question = 3
  print("did this work")
else:
  random_question == "Error"
#The above should print differer 3 Questions and an error, Below should answer 9 different Questions and give an error.#

you placed this after the print statement so the value you assign to question here is irrelevant.

3 hours ago, Alexsheff93 said:
random_number = random.randint(1, 9)
answer = ""
print("Magic 8-Ball's answer: ", answer)

same as above, you're just printing nothing because you set answer to "" right before the print statement.

3 hours ago, Alexsheff93 said:
if random_number == 1:
  answer = 1
  print("Yes - definitely")
elif random_number == 2:
  answer = 2
  print("It is decidedly so.")
elif random_number == 3:
  answer = 3
  print("Without a doubt.")
elif random_number == 4:
  answer = 4
  print("Reply hazy, try again.")
elif random_number == 5:
  answer = 5
  print("Ask again later.")
elif random_number == 6:
  answer = 6
  print("Better not tell you now.")
elif random_number == 7:
  answer = 7
  print("My sources say no.")
elif random_number == 8:
  answer = 8
  print("Outlook not so good.")
elif random_number == 9:
  answer = 9
  print("Very doubtful.")
else:
  answer = "Error"

...and the value of answer here is equally unused.

 

you seem to be under the impression that the order of your statements doesn't matter. it does. statements are executed in order.

 

Your code is also pretty messy, with repeated statements and variables used multiple times with different meanings. You could clean it up quite a bit:

import random
random_name = random.randint(1, 3)
random_question = random.randint(1, 3)

# Get one of 3 names
name = "Name error"	# this isn't really necessary, one of the conditions MUST be true here
if random_name == 1:
  name = " "
elif random_name == 2:
  name = "Alex"
elif random_name == 3:
  name = "Steve"

# Get one of 3 questions
question = "Question error" # this isn't really necessary, one of the conditions MUST be true here
if random_question == 1:
  question = "Is today Wednesday?"
elif random_question == 2:
  question = "Is 28 an old age"
elif random_question == 3:
  question = "did this work"

# Actually print the name and the question now that both have been picked
print(name,  "Asks: ",  question)

# Same logic as above
random_number = random.randint(1, 9)
answer = "Answer error"
if random_number == 1:
  answer = "Yes - definitely"
elif random_number == 2:
  answer = "It is decidedly so."
elif random_number == 3:
  answer = "Without a doubt."
elif random_number == 4:
  answer = "Reply hazy, try again."
elif random_number == 5:
  answer = "Ask again later."
elif random_number == 6:
  answer = "Better not tell you now."
elif random_number == 7:
  answer = "My sources say no."
elif random_number == 8:
  answer = "Outlook not so good."
elif random_number == 9:
  answer = "Very doubtful."

print("Magic 8-Ball's answer: ", answer)

better yet, you could just use a list of names, questions and answers:

import random

names = [" ", "Alex", "Steve"]
questions = ["Is today Wednesday?", "Is 28 an old age", "did this work"]
answers = ["Yes - definitely", "It is decidedly so.", "Without a doubt.",
           "Reply hazy, try again.", "Ask again later.", "Better not tell you now.",
           "My sources say no.", "Outlook not so good.", "Very doubtful."]

print(names[random.randint(0, 2)], "Asks: ", questions[random.randint(0, 2)])
print("Magic 8-Ball's answer: ", answers[random.randint(0, 8)])

to avoid mistakes with indexes you could also use the len() function to find the length of each list:

import random

names = [" ", "Alex", "Steve"]
questions = ["Is today Wednesday?", "Is 28 an old age", "did this work"]
answers = ["Yes - definitely", "It is decidedly so.", "Without a doubt.",
           "Reply hazy, try again.", "Ask again later.", "Better not tell you now.",
           "My sources say no.", "Outlook not so good.", "Very doubtful."]

print(names[random.randint(0, len(names) - 1)], "Asks: ", questions[random.randint(0, len(questions) - 1)])
print("Magic 8-Ball's answer: ", answers[random.randint(0, len(answers) - 1)])

this way you can add or remove items from the lists without changing any other code.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
https://linustechtips.com/topic/1415063-magic-8-ball-python3/#findComment-15283643
Share on other sites

Link to post
Share on other sites

18 minutes ago, Sauron said:

to avoid mistakes with indexes you could also use the len() function to find the length of each list:

len(names - 1)
len(questions - 1)
len(answers - 1)

Shouldn't it be:

len(names) - 1
len(questions) - 1
len(answers) - 1

Main System (Byarlant): Ryzen 9 5950X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 32GB G.Skill DDR4 3600MT/s CL16 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 990 EVO Plus 4TB | Corsair RM750X | StarTech 4× USB 3.0 Card | Realtek RTL8127 10G NIC | Hyte Y60 Case | Dell U3415W Monitor | Keychron K12 Blue (RGB backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB DDR4 3200MT/s (soldered) | Vega II 384SP Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi | Asus 2.5G USB NIC | Asus ProArt PA278QV | Keychron K4 Brown (white backlight)

 

Proxmox Server (Veda): Ryzen 7 3800XT | ASRock Rack X470D4U | Corsair H80i v2 | 128GB Micron DDR4 ECC 3200MT/s | 2× Samsung PM963a 960GB SSD / 4× WD 10TB / 4× Seagate 14TB Exos / 4× Micron MX500 2TB / 8× WD 12TB (custom external SAS enclosure) | Seasonic Prime Fanless 500W | Intel X550-T2 10G NIC | LSI 9300-8i HBA | Adaptec 82885T SAS Expander | Fractal Design Node 804 Case

 

Proxmox Server (La Vie en Rose)GMKtec Mini PC | Ryzen 7 5700U | 32GB Lexar DDR4 (SODIMM) | Vega II 512SP Graphics | Lexar 1TB 610 Pro SSD | 2× Realtek 8125 2.5G NICs


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / TEAMGROUP MS30 1TB | Corsair CX450M | Viewcast Osprey 260e Video Capture | TrendNet (AQC107) 10G NIC | LG WH14NS40 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Workbench (Doven Wolf): Lenovo m715q | Ryzen Pro 3 2200GE | 16GB Crucial DDR4 3200MT/s (SODIMM) | Vega 8 Graphics | SKHynix (OEM) 256GB NVMe SSD | uni 2.5G USB NIC | HDMI add-in module

 

Network:

Spoiler
                       ┌─────────────── Office/Rack ───────────────────────────────────────────────┐
Google Fiber Webpass ── Cloud Gateway Max ══╦═ Pro XG 8 ══╦═ Flex 2.5-8 ══╦═ Doven Wolf
                      La Vie en Rose (DNS) ═╬═ Narrative  ╠═ Veda-NAS     ╠═ La Vie en Rose (vmbr)
                                Veda (DNS) ─┘             ╠═ Veda (vmbr)  ├─ Ptolemy (vmbr)
╔═════════════════════════════════════════════════════════╩═ Ptolemy-NAS  ├─ Veda (Mgmt)
║   ┌ Closet ┐      ┌───────── Bedroom ─────────┐                         └─ Veda (IPMI)
╚═══ Flex XG ══╦╤═══ Flex XG ══╤╦═ Byarlant
       (PoE)   ║│              │╠═ Narrative 
Kitchen Jack ══╣└─ Dual PoE ┐  │╚═ Jesta Cannon*
   (Testing)   ║┌─ Injector ┘  └── Work Laptop
     Bedroom ══╝│        ┌─────── Media Center ────────────────────────────┐
     Jack #2    └──────── Switch 8 ────────────┬─ nanoHD Access Point (PoE)
Notes:                                         ├─ Sony PlayStation 4 
─── is Gigabit / ═══ is Multi-Gigabit          ├─ Pioneer VSX-S520
* = cable passed from Bedroom to Media Center  └─ Sony XR65A80K (Google TV)
Link to comment
https://linustechtips.com/topic/1415063-magic-8-ball-python3/#findComment-15283661
Share on other sites

Link to post
Share on other sites

3 minutes ago, AbydosOne said:

Shouldn't it be:

len(names) - 1
len(questions) - 1
len(answers) - 1

Give me a sec to catch up im reading through yours and sauron's post. the objective from code academy was to add an if/else statement to print a random question and answer with no name.

#Murica(butinternational)parrotgang

Link to comment
https://linustechtips.com/topic/1415063-magic-8-ball-python3/#findComment-15283666
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×