Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
code
#1
import random
question1 = input("Question!")
answer1 = input("Answer of question1")
question2 = input("Question!")
answer2 = input("Answer of question2")
question3 = input("Question!")
answer3 = input("Answer of question1")
question4 = input("Question!")
answer4 = input("Answer of question2")
random = random.randint(1,3)
if random == 1:
    playeranswer1 = input(question1)
    if playeranswer1 == answer1:
        print("you are right")
    else:
        print("you are wrong")
elif:
    playeranswer2 = input(question2)
    if playeranswer2 == answer2:
        print("you are right")
    else:
        print("you are wrong")
how do i make this right(elif is invalid syntax)
and also how can i format the code and make it (if loop) shorter but can run four questions?
(in other programs you can just change the variable of it, but i don't know maybe it's some other way)
Reply
#2
To use the elif you need to specify a condition:

if 1 == 2:
    print('NAH')
elif 2 == (1 + 1):
    print('YEAH')
Try to store the answers in a list, like this:

import random


NUM_QUESTIONS = 4
questions = []
answers = []
for i in range(NUM_QUESTIONS):
    questions.append(input(f"Question {i}: "))
    answers.append(input(f"Answer of question {i}: "))

random = random.randint(1, 3)
if random == 1:
    playeranswer1 = input("Guess the answer: ")
    if playeranswer1 in answers:
        print("you are right")
    else:
        print("you are wrong")
else:
    playeranswer2 = input("Guess the answer: ")
    if playeranswer2 in answers:
        print("you are right")
    else:
        print("you are wrong")
Reply
#3
Please note that the use of the following syntax is a recipe for disaster:
random = random.randint(1,3)
The module 'random' is now overwritten and is a local variable of type 'int'

The following example code demonstrates:
import random

# Print information about module random
print(random)

# Overwrite 'random' - 'random' is now a local variable
random = 0
print(random)

# Overwrite 'random' again
import random
print(random)
my_random_value = random.randint(1, 5)
print(my_random_value)

# Overwrite 'random' again - 'random' is now a local variable
random = 0
print(random)

# Create a traceback error because 'random' was overwritten and is now a local variable of type 'int'
my_random_value = random.randint(1, 5)
Output:
<module 'random' from 'C:\\Python\\lib\\random.py'> 0 <module 'random' from 'C:\\Python\\lib\\random.py'> 4 0 Traceback (most recent call last): File "VariableCollision-001.py", line 21, in <module> my_random_value = random.randint(1, 5) AttributeError: 'int' object has no attribute 'randint'
Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020