Trouble with user inputs - python

In my code I am trying to make an etch-a-sketch. I am in a coding class at my highschool and our project is to use lists and user inputs to make whatever we wanted to do. I chose etch-a-sketch because our class is also doing drawing with turtles. Currently I have a turtle (trtl) and a user input. Here is how I have it set up
user_inp = []
x = input(" ")
user_inp.append(x)
I am trying to have it read through the code as if you'd read a book and not just search for 1 variable at a time. currently I have a def function set as
def move():
trtl.forward(20)
for w in user_inp():
if w in user_inp:
move()
The problem with that is that is say I put in "w w" as my input. It doesn't work and instead it shows up as nothing. I need help quite badly and when I tried explaining what I needed help on to my teacher he didn't understand. If any of you do and can help me please do so.

I'm assuming user_inp.ammend(x) is a typo. Obviously user_inp.append(x) is what you want.
Your logic is going to cause the turtle to always move 20 steps for each and every input character. The following code assigns the new variable w to each successive character in the user input. It's not getting all 'w' characters from their input:
for w in user_inp():
Similarly, now that w contains some character from the input, this code will always return true:
if w in user_inp:
That's because we already got the character out of the input, so it's guaranteed to be in the input.
Instead, you just have to do something like:
for letter in user_inp():
if letter == 'w':
move()

you need to change user_inp.ammend(x) to user_inp.append(x) and when you are looping through the user_inp list you don't need the parentheses because it isn't a function it is a list so that will send an error as well

Related

python 3 input without newline

I am new to coding. And I would like to know if there's a way for input function to not print newline character after the value is entered. Something like print function's argument end. Is there any way?
Well, you can't make input() trigger by anything besides 'Enter' hit (other way may be using sys.stdin and retrieving character one-by-one until you receive some stop marker, but it's difficult both for programmer and for user, I suppose). As a workaround I can the suggest the following: if you can know the length of line written before + length of user input, then you can use some system codes to move cursor back to the end of previous line, discarding the printed newline:
print("This is first line.")
prompt = "Enter second: "
ans = input(prompt)
print(f"\033[A\033[{len(prompt)+len(ans)}C And the third.")
\033[A moves cursor one line up and \033[<N>C moves cursor N symbols right. The example code produces the following output:
This is first line.
Enter second: USER INPUT HERE And the third.
Also note that the newline character is not printed by your program, it's entered by user.
name=input('Enter your name : ')
print('hello',name,end='')
I know about the end function which is abov

How do I solve problems inside an input()? (Python) [duplicate]

This question already has answers here:
Safe way to parse user-supplied mathematical formula in Python
(3 answers)
Closed 1 year ago.
So I wanna make a code that solves simple problems (For example 3+4=? or 2/4+5=?) that are typed in by the user with input() but it treats the returned value as a string and it doesn't wanna work.
Basicly I wanna do this correctly:
print('Enter a problem:')
equals = input()
print('The answer is {}.'.format(equals))
Thanks in advance and have a nice day!
Well input() always returns a string. There is no way around that. However, you can't just "cast" it to be an equation. However, if you know the operations that will be inputted you can do some parsing. For example, this is how you might handle addition.
print('Enter a problem:')
equation = input() # user inputs 3+4=?
equalsIndex = equation.index('=')
# Reads the equation up to the equals symbol and splits the equation into the two numbers being added.
nums = equation[:equalsIndex].split('+')
nums[0] = int(nums[0])
nums[1] = int(nums[0])
print('The answer is {}.'.format(nums[0] + nums[1]))
In general, you would have to parse for the different operations.
You can't transform this from "string" to "code". I think that exist a lot of libraries that can help you (example).
Other option is that you write your own code to do that.
Main idea of that is to get numbers and operators from string to variables. You can use "if" to choosing operations.
Example.
You have a input string in format "a+b" or "a-b", where a,b - integers from 1 to 9. You can take first and last symbol of that string. Convert it into integer and save into variables. Next step is check if second symbol of the string is "+" than you can add this two variables. Otherwise you can sub this variables. That's it.
Obviously if you want some powerful application you need more work, but it only an idea.
To my experience, I have no idea on how to solve problem directly inside the input(). The only way to solve your issue (I think) is overide the input() method. You can Google 'overriding method python' and you'll find the syntax.
Hope you'll figure out this problem. Have a nice day :)
Use exec as follows.
equation = input("Input your equation")
exec("output = {}".format(equation))
print(output)
Here is an example (Note. "=" should not be included in the equation)
Input your equation: 2+4
6

Python phone number string validation

I'm having some issues that I really would like some help on. Right now I'm trying to get the user to input a phone that only accepts the first three things typed in as numbers. The rest can be letters that will get converted into numbers, but even if the first three things are numbers or letters it will keep repeating. The input has to be in this format (XXX-XXX-XXXX).
examples: (234-SDF-SDFL) this would pass, if (SDF-FSD-UEIE) then the program would ask again until the first three are number. Please and thank you.
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]
while area.isdigit() == False :
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]
Why dont you use regular expressions? (BTW: Do not use this odd naming, use pythons naming convention: snake case)
import re
phone_number=input("Number: ")
while not re.match(r'^\d{3}-[A-Z]{3}-[A-Z]{4}$', phone_number):
phone_number=input("Number: ")

Small == Equal while creating simple python code

I'm completely new to Python so all of this is a bit new for me.
I'm trying to create a script in which it by itself thinks of a number and after wards wants the user to guess a number and enter it. It seemed to work but there are wo problems here.
It understands everything however it does not understand the == part.
Because even though the both numbers are the same, it still goes on towards the else statement.
import random
while True:
Thethinker = random.randint(1,10)
Guessnumber = (input("Guess a random number "))
if Guessnumber == Thethinker:
print("Correct")
print(Thethinker)
else:
print("Not correct")
print(Thethinker)
Any help?
Assuming Python 3, input returns a string.
In Python, a string and a number can never be "equal"; you have to transform one or the other. E.g, if you use
Thethinker = str(random.randint(1,10))
then the equality-comparison with another string can succeed.
Your input returns a string instead of an integer. To get an integer do:
int(Guessnumber)
This is better than using str() because then if you ever want to change the numbers, you wouldn't be able to do that without doing the method I suggested
As far as I know, I don't do much Python

How do I read just part of a string?

For my program I ask the user to input a command. If the user writes: Input filename (filename being any possible name of a file in the computer) I want my program to only read Input so it knows what if statement to use and then open the file that the user wrote.
There is also another part where I have to do a similar task, where the user inputs: score n goals.(n is the top number of players the program has to read from a list) I want the program to differentiate this from 2 other similar tasks (score n misses and score n passes).
I am not sure if I'm approaching this the correct way, but this was my try for the first case I talked about, but it doesn't work.
user_input = input ('File name:')
input_lowered = user_input.lower()
command = input_lowered[0:4]
if command == 'input' :
fp = open ("soccer.part.txt")
else :
user_upper = input ('Input name:')
Thanks in advance for any clue of how I should aim at fixing this!!!
You can do that as follows:
your_string[0:5]
This will get the first five characters of the string as a string.
If you would like to grab a part of the string from the start then you can use:
my_string[:number]
if you would like to grab a part of the string from the end:
my_string[-number:]

Categories

Resources