Function Is Not Running - python

Just started to code, can't figure out why the start function will not ask me for any user input.
import random
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!") #Asks me for user input... Doesn't work
if answer == "yes":
print("Rolling the dice... The number is... " + number)
else:
print("Aww :( ")

You want to give consideration to your program as a module.
Try making the following changes:
import random
_NUMBER = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print("Rolling the dice... The number is... " + _NUMBER)
else:
print("Aww :( ")
if __name__ == "__main__":
start()
The "if name"... addition allows your program to be run from the interpreter as a module. You can also import this module into other programs easily.
I've also changed the syntax on your global variable (number) to reflect best practices. It's now private -- indicated by the underscore -- and uppercase.
If this program is imported as a module, the global variable won't impact those of the same name.
Now you can do python filename.py from the command line, or from filename import start and start() from the interpreter to run your program.

You have to call the function.
start()
Working script:
import random
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print "Rolling the dice... The number is... ", number
else:
print("Aww :( ")
start()

You never actually call the function:
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print("Rolling the dice... The number is... " + number)
else:
print("Aww :( ")
start()

Just like the other two said, you haven't called the function "start()". Also you asked to type "Yes" but you check if the user gave "yes".

Related

How do I clear an "if" condition

I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.

I am creating my own guessing name but the program doesn't start

What might I be doing wrong in this program? I recently started with Python.
##number guesser generator
import random
def main():
print("welcome to the number guessing game!")
print("You will receive three guesses!")
print("Choose a number between 1 and 100")
randomnumbergenerator()
userinput()
winorlose()
def randomnumbergenerator():
random.seed(0)
randomnumber = random.randint(1,100)
return randomnumber
def userinput():
answer1 = int(input('what is your 1st guess?'))
answer2 = int(input('what is your 2nd guess?'))
answer3 = int(input('what is your 3rd guess?'))
answers = answer1, answer2, answer3
return answers
def winorlose(randomnumber, answers):
while randomnumber != answers:
print('You lose! The correct answer equals' + randomnumber)
if randomnumber == answers:
print("You picked the correct answer! The answer was " + randomnumber)
return winorlose()
The function main is just another normal function. Python has no concept of a "main" function. You need to call the main() function manually like so
# Check if file was executed as the "main" file
# This is optional, but it ensures that if you import this file as a module,
# the main function isn't invoked
if __name__ == "__main__":
main() # Call the main function
I am pretty noob as well, but it looks as though you're building the script in a class type method but haven't added the class.
At the moment the program just runs through and creates all the functions ready for instances to be called, but you've called them within the main function which itself doesn't get called. If you were to do something like this:
class randomGenerator():
def __init__(self):
self.main()
def main(self):
print("welcome to the number guessing game!")
print("You will receive three guesses!")
print("Choose a number between 1 and 100")
self.randomnumbergenerator()
self.userinput()
self.winorlose()
def randomnumbergenerator(self):
random.seed(0)
randomnumber = random.randint(1,100)
return randomnumber
def userinput(self):
answer1 = int(input('what is your 1st guess?'))
answer2 = int(input('what is your 2nd guess?'))
answer3 = int(input('what is your 3rd guess?'))
answers = answer1, answer2, answer3
return answers
def winorlose(self, randomnumber, answers):
while randomnumber != answers:
print('You lose! The correct answer equals' + randomnumber)
if randomnumber == answers:
print("You picked the correct answer! The answer was " + randomnumber)
return winorlose()
run = randomGenerator()
then at least it will start and you can troubleshoot more. I recommend you research classes as well.

invalid syntax for "from import random"

when I try to run this module
from import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart = Yes or y:
guessnum()
else:
end()
I get invalid syntax highlighting the import.
what is the issue?
I have already tried import random but it doesn't seem to want to work
Your code is full of errors. I have fixed indentation and other syntax issues.
You don't need to use from, just use import random.
Here is the code
import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart == "Yes" or "y":
guessnum()
else:
end()
Fixed your indentation, spelling, capitalization, insertion of unnecessary spaces and comparing between a string and int which would always be false.
Also added str.title to allow for all types of capitalization for restart
import random
import sys
def guessnum():
random_num = random.randint(1,6)
answer = int(input("What do you think the number is? "))
if answer == random_num:
print("Good job. you are correct!")
else:
print("Incorrect. Better luck next time. The number was %d" % random_num)
restart = input("Would you like to try again? ")
if restart.title() in ["Yes", "Y"]:
guessnum()
else:
end()
def end():
print("Goodbye!")
sys.exit(0)
guessnum()

Int is not callable

I have researched this subject, and cannot find a relevant answer, here's my code:
#Imports#
import random
from operator import add, sub, mul
import time
from random import choice
#Random Numbers#
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
#Variables + Welcoming message#
correct = 0
questions = 10
print ("Welcome to the Primary School Maths quiz!!")
print ("All you have to do is answer the questions as they come up!")
time.sleep(1)
#Name#
print("Enter your first name")
Fname = input("")
print ("Is this your name?" ,Fname)
awnser = input("")
if awnser == ("yes"):
print ("Good let's begin!")
questions()
if input == ("no"):
print("Enter your first name")
Fname = input("")
print ("Good let's begin!")
#Question Code#
def questions():
for i in range(questions):
ChoiceOp = random.randint (0,2)
if ChoiceOp == "0":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1*beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "1":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1-beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "2":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1+beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
questions()
If I'm perfectly honest I'm not quite sure what's wrong, I have had many problems with this code that this wonderful site has helped me with, but anyway this code is designed to ask 10 random addition, subtraction and multiplication questions for primary school children any help I am thankful in advance! :D
You have both a function def questions() and a variable questions = 10. This does not work in Python; each name can only refer to one thing: A variable, a function, a class, but not one of each, as it would be possible, e.g. in Java.
To fix the problem, rename either your variable to, e.g., num_questions = 10, or your function to, e.g., def ask_question()
Also note that you call your questions function before it is actually defined. Again, this works in some other languages, but not in Python. Put your def quesitons to the top and the input prompt below, or in another function, e.g. def main().

Why will this program not work in the shell, but work in my IDE?

Im having a problem with a dice roller program (text for now but eventually graphical). It will not work in anything except for the IDE I use, Wing IDE 101 4.1. The error i get flashes too fast for me to read, but i will try to take a screenshot of it. (I will edit this post if i get a screenshot.)
Here is the program:
import random
#variables
available_dice = "D20"
main_pgm_start = False
#definitions of functions
def diePick():
print("Pick a die. Your choices are: ", available_dice)
print("")
which_dice = input("")
if which_dice == "D20" or which_dice == "d20":
rollD20()
else:
print("Error: Please try again")
print("")
diePick()
def rollD20():
print("Rolling D20 .... ")
print("")
d20_result = random.randrange(1, 20)
print("You have rolled a ", d20_result)
print("")
print("Would you like to roll again?")
print("")
y = input("")
if y == "y" or y == "Y" or y == "yes" or y == "Yes":
print("")
diePick()
def MainProgram():
print("Benjamin Ward's Random D&D Dice Roller")
print("")
x = input(" Press Enter to Continue")
print("")
diePick()
MainProgram()
You can redirect the log to the text file with "logging" module if my memory serves.
I dont think input() does what you expect it to. input reads a line of text, then executes it (as python).
I think what you want is more along the lines of stdin.readline(). To use it, you will have to from sys import stdin at the top, then replace all occurences of input with sys.readline(). Note also that this will return a newline at the end, which you have to account for.

Categories