I am new to learning python, and I only have limited programing experience, so I am sorry for asking such a basic question. I am doing an online python tutorial and wanted to take the program a bit further than the lesson requested to test out how far I could take it. The problem is that I have been hitting a roadblock. After reading a bunch of posts on here I have moved things around, changed variable names, used more functions, less functions, if else statements, and toyed around/ troubleshot, but have received all sorts of errors. I am going to paste where I currently am at below and would really appreciate if someone out there could help me finish up the program.
Here is what I would like for the program to do:
I would like the user to be prompted to enter a number.
I would like to make sure that the user entered a number, and if they don't I would like the program to give them an error and restart.
I would like that once the number is received the program squares that number and then prints the answer.
(again thanks much for all the help)
HERE IS WHERE I AM AT:
n1 = raw_input('Please enter your desired number:')
def n2():
n2 = n1.isnumeric()
return n2
def square(n2):
squared = n2**2
print "%d squared is %d." % (n2, squared)
return squared
square(n2)
n2 = raw_input("number pls\n")
while not n2.isdigit():
print("why did you do this\n")
n2 = raw_input("number pls\n")
print int(n2)**2
Problems from your code:
You need a control structure which repeatedly tries to do something until the right thing happens. This should make you think "while loop."
isnumeric isn't a method. but you had the right idea.
Naming all of your variables and functions n2 is not a good way to easily see what's going on..
If you want to add a construct for floats, you should write a function which takes a string in and returns true or false based on if it looks like a float! This is a good example for using functions to decompose the problem you're working with- you know you need to do something like
while not (n2.isdigit or isFloat(n2)):
There are some good suggestions here and elsewhere about how to do that :)
You could check if you could convert into float if so print the square else print the error .To repeat this process while you get a number you could use while loop
def number_validator( numb ):
try:
float( numb )
return True
except Exception:
print "GIven input is not a valid number"
return False
def square( n2 ):
n2=float( n2 )
squared = n2**2
print "%s squared is %s." % ( n2 , squared )
return squared
n2 = raw_input( 'Please enter your desired number:' )
while not number_validator( n2 ):
n2 = raw_input( 'Please enter your desired number:' )
square( n2 )
Output:
Please enter your desired number:wq
GIven input is not a valid number
Please enter your desired number:we
GIven input is not a valid number
Please enter your desired number:21.0
21.0 squared is 441.0.
Related
The problem with my code is that when running it to see if the first word of the question is in the query list. It won't give anything back due to being a int. Can anyone point me towards right direction ?
import random
response = [ 'Yes, of course!',"Without a doubt,yes.",
'For sure!','Ask me later.',
'I am not sure.',
'I will tell you after my nap.',
'No Way!','I do not think so.',
'The answer is clearly NO.']
query = ['Will','Are','Is','Am','Do','Can','May']
# Global lists ^^^
def main(response,query,ran):
# The program that
print('Ask a question that can only be answered in yes or no.')
question = input()
if question(0) in query():
ran(response,query)
res = ran(response,query)
print(res)
again = input('Enter Y or y to play again. Enter N or n to exit.')
if again in ['y','Y']:
main(lists)
else:
print('This program will now close.')
def ran(response,query):
res = random.choice(response)
return res
main(response,query,ran)
The problem lies here question.index(0) in lists. You are comparing apples with pears. index will yield a number and you are comparing it with the actual definition of the lists function. You might want to rethink what you want to compare.
Secondly, you will have extra errors, you are using random.sample in a bad way, you should be doing random.sample(response, 1)[0], I'm presuming you want to pick a random response from that collection.
Thirdly, what is the lists() function supposed to do?
I want to make this code much more elegant, using loop for getting user input into a list and also making the list as a list of floats withot having to define each argument on the list as a float by itself when coming to use them or print them...
I am very new to python 3.x or python in general, this is the first code i have ever written so far so 'mercy me pardon!'
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n
if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
calc =list(range(2))
calc[0] = (input("number 1:"))
calc[1] = (input("number 2:"))
print (float(calc[0])/float(calc[1]))
Since you are saying you are new to Python, I'm going to suggest you experiment with a few methods yourself. This will be a nice learning experience. I'm not going to give you answers directly here, since that would defeat the purpose. I'm instead going to offer suggestions on where to get started.
Side note: it's great that you are using Python3. Python3.6 supports f-strings. This means you can replace the line with your print function as follows.
print(f"Hello {Name} What's up? "
"\nare you coming to the party tonight in {Place}"
"\n if not at least try to make simple calculator:")
Okay, you should look into the following in order:
for loops
List comprehension
Named Tuples
functions
ZeroDivisionError
Are you looking for something like this :
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
output:
1 2
0.5
By using a function that does the input for you inside a list comprehension that constructs your 2 numbers:
def inputFloat(text):
inp = input(text) # input as text
try: # exception hadling for convert text to float
f = float(inp) # if someone inputs "Hallo" instead of a number float("Hallo") will
# throw an exception - this try: ... except: handles the exception
# by wrinting a message and calling inputFloat(text) again until a
# valid input was inputted which is then returned to the list comp
return f # we got a float, return it
except:
print("not a number!") # doofus maximus user ;) let him try again
return inputFloat(text) # recurse to get it again
The rest is from your code, changed is the list comp to handle the message and input-creation:
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n"+
" if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
# this list comprehension constructs a float list with a single message for ech input
calc = [inputFloat("number " + str(x+1)+":") for x in range(2)]
if (calc[1]): # 0 and empty list/sets/dicts/etc are considered False by default
print (float(calc[0])/float(calc[1]))
else:
print ("Unable to divide through 0")
Output:
"
Hello john What's up?
are you coming to the party tonight in Colorado
if not at least try to make simple calculator:
you will input 2 numbers now and i will devide them for you:
number 1:23456dsfg
not a number!
number 1:hrfgb
not a number!
number 1:3245
number 2:sfdhgsrth
not a number!
number 2:dfg
not a number!
number 2:5
649.0
"
Links:
try: ... except:
Lists & comprehensions
Please mind I am very new to the Python world.
I've been looking for an answer to this online and can't seem to find the right solution, based on my understanding I feel the logic is correct. In the end, though my results are just not there.
I am compiling with Idle.
Point of the solution: Is to take a string value of Kilometers from the console. Then convert it to Miles, then output the string.
Seems simple but debugging the below code over and over again I cannot seem to figure out why after I enter my kilometer number the print with the conversion value never displays.
def main(distanceMile=None):
# Declare and initialize variables
# string called distancekilo
distanceKilo = ""
# distancemile = ""
# conversion = 0.6214
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
I would simply like to know where I am going wrong here?
Your code has three main bugs. One is the indentation at the end of calcConvert (return should be indented). Another is that the main definition at the top doesn't seem to do anything. Another is that you want to save calcConvert(distanceKilo) to a variable. This code works:
# Introduction
print("Welcome to the distance converter \n")
# Prompt for distance in Kilometers
distanceKilo = input("Enter distance in Kilometers: ")
# Default Argument
def calcConvert(value):
conversion = 0.6214
distanceMile = int(value) * conversion
return distanceMile
distanceMile = calcConvert(distanceKilo)
print("That distance in miles is ", distanceMile)
If you're new to Python, I would suggest also reading some posts and articles about the way people normally style code (like calc_convert vs calcConvert) in Python :) It's not entirely necessary, but it makes it easier for other Python users to read your code.
I am quite new to the PseudoCode concept... I would like to get an idea of how functions and operands like modulus, floor division and the likes would be written in PseudoCode. Writing the PseudoCode for this code might actually help me understand better...
user_response=input("Input a number: ")
our_input=float(user_response)
def string (our_input):
if (our_input % 15) == 0 :
return ("fizzbuzz")
elif (our_input % 3) == 0 :
return ("fizz")
elif (our_input % 5) == 0 :
return ("buzz")
else :
return ("null")
print(string(our_input))
Your code really isn't that hard to understand assuming the knowledge of % as the modulus operation. Floor division can really just be written as a regular division. Floor the result, if really necessary.
If you don't know how to express them, then explicitly write modulus(x, y) or floor(z).
Pseudocode is meant to be readable, not complicated.
Pseudocode could even be just words, and not "code". The pseudo part of it comes from the logical expression of operations
The basic idea of PseudoCode is either to
a) Make complicated code understandable, or
b) Express an idea that you are going to code/haven't yet figured out how to code.
For example, if I am going to make a tool that needs to read information in from a database, parse it into fields, get just the info that the user requests, then format the information and print it to the screen, my first draft of the code would be simple PseudoCode as so:
# Header information
# Get user input
# Connect to Database
# Read in values from database
# Gather useful information
# Format information
# Print information
This gives me a basic structure for my program, that way I don't get lost as I'm making it. Also, if someone else is working with me, we can divvy up the work (He works on the code to connect to the database, and I work on the code to get the user input.)
As the program progresses, I would be replacing PseudoCode with real, working code.
# Header information
user_input_row = int(input("Which row (1-10)? "))
user_input_column = input("Which column (A, B, C)? "))
dbase = dbconn("My_Database")
row_of_interest = dbase.getrow(user_input_row)
# Gather useful information
# Format information
# Print information
At any point I might realize there are other things to do in the code, and if I don't want to stop what I'm working on, I add them in to remind myself to come back and code them later.
# Header information #Don't forget to import the database dbconn class
user_input_row = int(input("Which row (1-10)? "))
#Protect against non-integer inputs so that the program doesn't fail
user_input_column = input("Which column (A, B, C)? "))
#Make sure the user gives a valid column before connecting to the database
dbase = dbconn("My_Database")
#Verify that we have a connection to the database and that the database is populated
row_of_interest = dbase.getrow(user_input_row)
# Separate the row by columns -- use .split()
# >> User only wants user_input_column
# Gather useful information
# Format information
# >> Make the table look like this:
# C C1 C2 < User's choice
# _________|________|_______
# Title | Field | Group
# Print information
After you're done coding, the old PseudoCode can even serve to be good comments to your program so that another person will know right away what the different parts of your program are doing.
PseudoCode also works really well when asking a question when you don't know how to code something but you know what you want, for example if you had a question about how to make a certain kind of loop in your program:
my_list = [0,1,2,3,4,5]
for i in range(len(my_list)) but just when i is even:
print (my_list[i]) #How do I get it to print out when i is even?
The PseudoCode helps the reader know what you're trying to do and they can help you easier.
In your case, useful PseudoCode for things like explaining your way through code might look like:
user_response=input("Input a number: ") # Get a number from user as a string
our_input=float(user_response) # Change that string into a float
def string (our_input):
if (our_input % 15) == 0 : # If our input is divisible by 15
return ("fizzbuzz")
elif (our_input % 3) == 0 : # If our input is divisible by 3 but not 15
return ("fizz")
elif (our_input % 5) == 0 : # If our input is divisible by 5 but not 15
return ("buzz")
else : # If our input is not divisible by 3, 5 or 15
return ("null")
print(string(our_input)) # Print out response
THANKS GUYS FOR ALL OF YOUR INPUT, FROM ALL I READ, I CAME UP WITH THIS, IF THERE ARE ANY AREAS U THINK NEEDS TO BE ADJUSTED PLEASE LET ME KNOW.
THANKS AGAIN
THE FUNCTION USING PYTHON
user_response=input("Input a number: ")
our_input=float(user_response)
def string (our_input):
if (our_input % 15) == 0 :
return ("fizzbuzz")
elif (our_input % 3) == 0 :
return ("fizz")
elif (our_input % 5) == 0 :
return ("buzz")
print(string(our_input))
<<------------------------------->>
IT'S PSEUDOCODE
Request an input from the user
Ensure that the input is a number
If the input is divisible by 15
send "fizzbuzz" to the main
program
But if the input is divisible by 3 and not 15
send "fizz" to the main program
But if the input is divisible by 5 and not 15 or 3
send "buzz" to the main program
Display the result.
I am completely new to any coding at all.
As one of my first little tasks I tried to design a program comparing numbers. I wanted to add a function that distinguishes "pi" and "e" entries and converts them into respective floats. This function, however, doesnt work fine.
# the user is prompted to insert a value. This will be stored `enter code here`as "input1"
input1=input("insert a number:")
# decide whether the input is a number or a word. Convert words `enter code here`into numbers:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", (number))
elif pismeno == "e":
number= float(2.71)
print ("word e converted to number:", (number))
else:
number = float(pismeno)
print (number, "is already a number. No need to convert.")
# call the convert function onto the input:
convert(input1)
print ("The number you chose is:",input1)*
I guess that it has something to do with the output being stored inside the function and not "leaking" outside to the general code. Please keep in mind that I have literally NO experience so stick to a child language rather than the usual professional speech.
If you are writing a function, you need a return statement. A simplified example of your code:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", number)
return number
else:
....
....
input1=input("insert a number:")
print(convert(input1))
I really suggest you to study basic concepts of programming. You may start here: https://www.learnpython.org/. More about functions: https://www.learnpython.org/en/Functions
The number you chose is: pi" instead of "The number you chose is: 3.14"
Your current final print just prints the input you originally gave it (input1)
You need to provide a way to return a value from the function and then set that to a variable where you call it
def convert(pismeno):
... Code ...
return number
# call the convert function onto the input:
output_num = convert(input1)
print ("The number you chose is:",output_num )