python define a variable in an if statement - python

I want to make a coin toss / dice roll in python but i cannot figure out how to define / change a variable inside an if statement.
import random
def roll(number):
if(number==1):
{print("Take a moment to think that through")}
if(number==2):
{b=random.randint(0,1)
if(b=0):
{ba=1}
else:
{bb=1}
}
the part, {b=random.randint(0,1)} the = is highlighted red and marked as a syntax error. I also tried this:
import random
b=0
def roll(number):
if(number==1):
{print("Take a moment to think that through")}
if(number==2):
{b+=random.randint(0,1)
if(b=0):
{ba=1}
else:
{bb=1}
}
that gives the same error, and the = is highlighted, not the +
and before you ask, the function roll(number) is called in the shell. the shell is my interface.

import random
def roll(number):
if number==1:
print("Take a moment to think that through")
if number==2:
b=random.randint(0,1)
if b==0:
ba=1
else:
bb=1
Python doesn't use curly braces, you should write your codes like this.Also you have to return something in your function.This is how you can use your function/variables with another methods.
import random
def roll(number):
if number==1:
my_string="Take a moment to think that through"
return my_string
if number==2:
b=random.randint(0,1)
if b==0:
ba=1
else:
bb=1
return ba,bb
Something like this, I don't know your whole code so.

You should also think about what should happen if someone enters, for example, roll(15).
import random
def roll(number):
if number==1:
print("Take a moment to think that through")
elif number==2:
b=random.randint(0,1)
if b==0:
ba=1
else:
bb=1
else:
print("What should happen in this case?")
Also, #grrr: if b==0

Related

Can I make a print statement run before a module I imported?

I am a beginner to python and coding in general and I was wondering how I can make a print statement run before a module I imported. I am making a number guessing game and in my main file where I combine all the modules, I have a general function for running all the code together. It would be best if I show my code so you guys will have a better understanding of what I am dealing with:
import random
import lvl1
import time
level1 = lvl1.Level_1_activated()
# This is the main file combining everything together to make this game playable
introduction = """
Hello and welcome to NumGuess by Sava. Here is a little bit about the game:
The game works by having 3 levels, each where you must pick a number between a range of
1-10 (level 1), 1-20 (level 2), and 1-50 (level 3).
You are given 5 attempts in the first level, 10 in the second level, and 20 in the final one.
You can also access a hint by typing ‘hint’. You win the game by picking the right number in each level.
You lose the game when you run out of tries. You can get a free bonus with 5 extra tries if you type ‘hlp’.
"""
def start_game(time, lvl1):
print(introduction)
level1
start_game(time, lvl1)
This is just the code for the main module, I have the code for lvl1 (which is the first level of my 'game'), and I have a class which has all the functions which then take part in the while loop. I will also show that file:
import random
import time
# I will fist make variables for the time breaks. S is for short, M is for medium and L is for long
S = 0.2
M = 0.7
L = 1.1
class Level_1_activated():
def get_name(self):
# This function simply asks the name of the player
name = input("Before we start, what is your name? ")
time.sleep(S)
print("You said your name was: " + name)
def try_again(self):
# This asks the player if they want to try again, and shows the progress of the level
answer = (input("Do you want to try again? "))
time.sleep(M)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(M)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
# Return statement for if the player wants to play again
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
# This is the return statement that stops the while loop
return False
def find_rand_num(self, random):
# This is the core of the level, where the player just chooses numbers between 1 and 10
time.sleep(S)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(L)
# The list of numbers for the level that the player is on at the moment
num_list = [1,10]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(S)
print("Congratulations! You got the number correct!")
# Yet another return statement for the while loop
return "Found"
elif input != number:
time.sleep(M)
print("Oops, you got the number wrong")
# This variable is fairly self-explanatory; it is what controls how many itterations there are in the while loop
tries = 1
while tries < 6:
if tries < 2:
Level_1_activated().get_name()
res = Level_1_activated().find_rand_num(random)
if res == "Found":
break
checker = Level_1_activated().try_again()
if checker is False:
break
tries += 1
If you go back to this function in the main file:
def start_game(time, lvl1):
print(introduction)
level1
I intentionally put the print statement before the module to make it run first, and I have tried different approaches to this and still can't seem to get a grasp on what I'm doing wrong here. Thank you for taking the time to read the code and I would be very grateful if any of you have a possible solution to this.
there are number of thing you can do, one is encapsulate your code into functions that only run when you ask for it
lvl1
... #all the previous code
def run_game():
tries = 1
while tries < 6:
...
tries += 1
you can also make a distinction between being executed directly vs being imported, to do that is simple, you include the following check (usually at the end of the file)
if __name__ == "__main__":
#if true it mean that you're executing this module directly, otherwise it was imported
#and you include here whatever you want that happens when you execute the module directly but not when is imported, like for example running a game
run_game()
__name__ is a special variable and python will assigned the value "__main__" if executed directly, otherwise it will be the name of the file, like "lvl1" for example
And in your main you can import it and do stuff like
import lvl1
...
def start_game():
print(introduction)
lvl1.run_game()

builtins.NameError: name 'guess' is not defined

I was working on a lab assignment and I've been struggling with an error for days. I coded return as well in my function and it keeps saying there's a NameError: and I didn't define it.
Here's the code I'm working on and it's all messed up since I'm not done. But I'd love to know what did I messed up and how can I fix the name error. Thanks!
import random
def main():
instructions = display_instructions("instructions.txt")
#display instructions
display_instructions(instructions)
list_of_words = ['apple', 'banana', 'watermelon', 'kiwi', 'pineapple',
'mango']
correct_word=random.choice(list_of_words)
answer = list(correct_word)
puzzle = []
puzzle.extend(answer)
display_puzzle_string(puzzle)
play_game(puzzle, answer)
display_result(is_win, answer)
input('Press enter to end the game.')
def display_instructions(filename):
instruction_file=open("instructions.txt","r")
file_contents=instruction_file.read()
instruction_file.close()
print(file_contents)
def display_puzzle_string(puzzle):
for i in range(len(puzzle)):
puzzle[i] = '_'
print('The answer so far is '+" ".join(puzzle))
def play_game(puzzle, answer):
num_guesses = 4
while num_guesses > 0:
get_guess(num_guesses)
update_puzzle_string(puzzle, answer, guess)
display_puzzle_string(puzzle)
is_word_found(puzzle)
def get_guess(num_guesses):
guess=input('Guess a letter '+'('+str(num_guesses)+' guesses remaining):')
return guess
def update_puzzle_string(puzzle, answer, guess):
for i in range(len(answer)):
if guess.lower() == answer[i]:
puzzle[i] = guess.lower()
num_guesses += 1
return puzzle
def is_word_found(puzzle):
if puzzle == answer:
return is_win
def display_result(is_win, answer):
if is_win:
print('Good job! You found the word '+correct_word+'!')
else:
print('Not quite, the correct word was '+correct_word+
'. Better luck next time')
main()
In the function play_game, you have the line get_guess(num_guesses) which returns the variable guess. However, you are not assigning the guess to a variable in the function. You can fix this by changing that line to guess = get_guess(num_guesses). The error tells you exactly what is wrong. You have not defined the variable guess so far.
Your code has different flaws. The main errors are related to indentation and function scopes. Keep in mind that Python uses indentation to group statements. Use 4 spaces consistently as indentation for grouping statements, e.g. to indent the function body, for-loop body etc.
Furthermore, there are many undefined name errors in your code, since you refer to names that are not defined in the current scope. Consider your function is_word_function(puzzle):
def is_word_found(puzzle):
if puzzle == answer:
return is_win
The name answer is defined in main(), whereas is_win is not defined at all (you are passing it to display_result() in main(), but have not defined it before). A better function declaration would look like this
def is_word_found(puzzle, answer):
return puzzle == answer
Note that this suggestion aims to be educational, I don't think that you necessarily need a function for this.
Generally, in order for names to be available in the current (function) scope, you have to either pass arguments to the function, or put them at module level, or - even better - consider looking into OOP (which, since this is a lab assignment, I suppose you haven't done yet).
Once you fixed these errors and your code compiles, you need to work on the logic of your game.
For example in play_game, you have the loop while num_guesses > 0 which will run infinitely, since you never decrease the num_guesses counter (in fact, you increase it in update_puzzle_string. A better loop would look like this:
def play_game(puzzle, answer, ..):
num_guesses = 4
while num_guesses and not is_word_found(puzzle, answer):
# logic
num_guesses -= 1
# or, alternatively
def play_game(puzzle, answer, ..):
num_guesses = 4
for _ in range(num_guesses):
# logic
if is_word_found(puzzle, answer):
# break or return
Consider to use flake8 in order to validate your code, detect errors and non-pythonic code constructs in the future.
>>> pip3 install flake8
>>> flake8 your_file.py

What Python3 method can I use to restrict input to only integer in my assignment?

I have a very brief familiarity with coding in general, though a majority of my experience thus far has been with Python. Which is why it's upsetting that I can't seem to figure out how to do this...
I have an assignment in my Python class where I am required to compute the area of a right triangle. I have completed the assignment successfully, but I wanted to take it a step further and restrict the user from inputting anything but an integer as input. I've tried multiple ideas from what I learned on Codecademy, though I can't seem to figure it out. Any help would be greatly appreciated!
Here is the code I've written so far; it works fine for what it is, but I would like to have it return a string that says something like "Please enter a valid number" if the user were to type anything besides a number:
from time import sleep
import math
print("Let\'s find the area of a right triangle!")
sleep(2)
triangleBase = float(input("Enter the base value for the triangle: "))
print("Great!")
triangleHeight = float(input("Enter the height value for the triangle: "))
print("Great!")
sleep(2)
print("Calculating the area of your triangle...")
sleep(2)
def triangleEquation():
areaString = str("The area of your triangle is: ")
triangleArea = float(((triangleBase * triangleHeight) / 2))
print('{}{}'.format(areaString, triangleArea))
triangleEquation()
You are close. You noticed that your code raised an exception. All you need to do is catch that exception and prompt again. In the spirit of "don't repeat yourself", that can be its own function. I cleanup up a couple of other things, like your calculation function using global variables and converting things that don't need converting (e.g. 'foo' is a str, you don't need str('foo')) and got
from time import sleep
import math
def input_as(prompt, _type):
while True:
try:
# better to ask forgiveness... we just try to return the
# right stuff
return _type(input(prompt.strip()))
except ValueError:
print("Invalid. Lets try that again...")
def triangleEquation(base, height):
area = base * height / 2
print('The area of your triangle is: {}'.format(areaString, area))
print("Let\'s find the area of a right triangle!")
sleep(2)
triangleBase = input_as("Enter the base value for the triangle: ", float)
print("Great!")
triangleHeight = input_as("Enter the height value for the triangle: ", float)
print("Great!")
sleep(2)
print("Calculating the area of your triangle...")
sleep(2)
triangleEquation(triangleBase, triangleHeight)
This should get you started. I'll leave the rest for you (if you'd like to also allow floats, hint, hint), since you said you wanted to take it a step further, that way you'll still retain the sense of accomplishment.
def triangleEquation(triangleBase, triangleHeight):
if type(triangleHeight) == int and type(triangleBase) == int:
areaString = "The area of your triangle is: "
triangleArea = float(((triangleBase * triangleHeight) / 2))
return '{}{}'.format(areaString, triangleArea)
else:
return 'Integers only.'
Note: You could also use the is idiom: if type(triangleHeight) is int...

Only the first conditions is being validated in a python function

def dice():
import random
print("******************************")
print("***** DICE GENERATOR ******")
print("******************************")
#dice choice
user_select=int(input("""Choose the type of dice to roll.
(1)1d4
(2)1d6
(3)1d10
(4)1d12
(5)1d20
:"""))
if user_select==1:
dice=random.randint(1,4)
print(dice)
return
if user_select==2:
dice=random.randint(1,6)
print(dice)
return
if user_select==3:
dice=random.randint(1,10)
print(dice)
return
if user_select==4:
dice=random.randint(1,12)
print(dice)
return
if user_select==5:
dice=random.randint(1,20)
print(dice)
return
in the example code above if i give the input as 1 then a random number is generated but or anything else there is no return.I checked in the visualiser ,it is returning a None for all values except 1
This is because you are returning straight after the first condition. I would recommend reading a book on python and understand how functions and returns work.
http://www.learnpython.org/
You have to realise that functions end if any return statement is reached. Functions are small pieces of code that work together on a certain job/goal. Once they are done with it they can return stuff or just nothing, depending on the data types you are working with and the goal of the function.
In your case you need to put only one return after the last print statement.
As stated by others, the problem is that the return is not within the if block. A common way to do what you want is to use elif:
def dice():
import random
print("******************************")
print("***** DICE GENERATOR ******")
print("******************************")
#dice choice
user_select=int(input("""Choose the type of dice to roll.
(1)1d4
(2)1d6
(3)1d10
(4)1d12
(5)1d20
:"""))
if user_select==1:
dice=random.randint(1,4)
elif user_select==2:
dice=random.randint(1,6)
elif user_select==3:
dice=random.randint(1,10)
elif user_select==4:
dice=random.randint(1,12)
elif user_select==5:
dice=random.randint(1,20)
else:
dice=None
print(dice)
(edit) notice that a return statement is not needed at the end of a function because python will automatically return None here. Its harmless and some people prefer to have them.

Creating a number of functions that need to be able to call each other in Python

So first let me say that I am a novice at Python and functions seem to be out of my comprehension for the moment but where I am having trouble is having 3 functions be able to call each other. Here is my code(yes I know it is terribly wrong but you should see where I am going):
def menu():
count=gearboxes
cost=subtotal
return subtotal
def quantity():
gearboxes=raw_input("How many gearboxes would you like to order? ")
return menu()
def subtotal(cost):
if (gearboxes<=10):
cost=gearboxes*100.0
print cost
elif (gearboxes>10 and gearboxes<20):
cost=(gearboxes-10)*80.0+1000.0
print cost
elif (gearboxes>20):
cost=(gearboxes-20)*70.0+1000.0+800.0
print cost
else:
print "wtf m8"
return menu()
def summary():
print "="*80
print "%60s %20f %20f" % ("motors",count,cost)
print "="*80
print quantity()
print subtotal(menu)
print summary(menu)
There is it and any help would be greatly appreciated if you could explain also kind of how functions call on each other.
Thanks!
fixed version(still working)
def quantity():
motors=raw_input("How many motors would you like to order? ")
gearboxes=raw_input("How many gearboxes would you like to order? ")
sensors=raw_input("How many sensor boards would you like to order? ")
return int(motors),int(gearboxes),int(sensors)
def subtotal(motors,gearboxes,sensors):
if motors<=10 and gearboxes<=15:
motorCost=motors*100
gearboxCost=gearboxes*50
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
if motors>10 and motors<=20 and gearboxes>15 and gearboxes<=30:
motorCost=(motors-10)*80+1000
gearboxCost=(gearboxes-15)*40+750
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
elif motors>20 and gearboxes>30:
motorCost=(motors-20)*70+1000+800
gearboxCost=(gearboxes-30)*30+750+600
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
def summary(motors,gearboxes,sensors,motorCost,gearboxCost,sensorCost):
print "="*80
print "%60s %20d %20d" % ("motors",motors,motorCost)
print "%60s %20d %20d" % ("gearboxes",gearboxes,gearboxCost)
print "%60s %20d %20d" % ("sensor boards",sensors,sensorCost)
print "="*80
def menu():
a,b,c=quantity()
d,e,f=subtotal(a,b,c)
summary(a,b,c,d,e,f)
return
menu()
I made some changes to your code. Treat a function like a question. When you call the function; you're asking the question. What you pass to return is the answer to the question. So when someone asks for the subtotal of some number of gearboxes; we return cost, whatever that may be.
We can then store the return values (the answers) in variables and use them later. For example, to pass to another function. Try to follow how information flows through the program.
def quantity():
count=raw_input("How many gearboxes would you like to order? ")
return int(count)
def subtotal(count):
if count<=10:
cost=count*100.0
return cost
elif count>10 and count<20:
cost=(count-10)*80.0+1000.0
return cost
elif count>20:
cost=(count-20)*70.0+1000.0+800.0
return cost
def summary(count, cost):
print "="*80
print "%60s %20f %20f" % ("motors",count,cost)
print "="*80
def menu():
items = quantity()
sub = subtotal(items)
summary(items, sub)
if __name__ == '__main__':
menu()
"subtotal" already calls menu() so I'm not sure what you are asking since you are already calling one function within the other.
Also, I can't see what your program is supposed to do - if your function names would be verbs (print_menu, get_menu, set_menu, throw_menu_on_moon, calculate_subtotal, ...) it would be better to understand for humans.
Also, the names you use (on the right hand side of =) within a function must be known there, so for example
def menu():
count=gearboxes
makes no sense (because "gearboxes" is unknown - on the other hand, "count" is fine since it defines new variable - since it is on the left hand side of =)...
Note that variables are only known within the function you defined them in, so
def f():
gearboxes = 2
def menu():
count=gearboxes
would make no sense either.
But
def f():
return 2
def menu():
gearboxes=f()
count=gearboxes
would make perfect sense.
Read the
def calculate_subtotal(gearbox_count):
as "to calculate subtotal of gearbox count do".
If you then say anywhere outside:
calculate_subtotal(5)
^^^^^^^^^^^^^^^^^^^^^
then the underlined part will be replaced by the result returned.
Otherwise, in Python the lines (in a block) are executed one after another - if you want to do multiple things in sequence, you can just write them one line each, one after another.
"return" is not "goto", "return" gives back the result - and control - to the caller of the function. Then the result is placed into the program "instead of the call".

Categories

Resources