Why does this beginner python program stop midway? - python

This is my first day learning python from a book called "Automate the Boring Stuff with Python".
On the "your first program" section the program is this
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?') # ask for their name
myName = input("Mizu")
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input('20')
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
but the program only runs
Hello world!
What is your name?
Mizu
but if i replace the input() functions with just values like myName = 'Mizu' , it prints the rest of the lines just fine.
What am i doing wrong here?
i used the default python editor and pycharm and both show no errors or anything.

Note, the book says
myName = input()
so that's what you put in your programme, not
myName = input("Mizu")
and then, likes others have written, when the programme gets there you type in your name.
CAUTION this is correct for python 3. Check your version. If you are using python 2, replace "input" with "raw_input()"
myName = raw_input()

input means that it's waiting for you to write something.
Type something and press"Enter"
It isn't stopped.

you need to type some thing after the third line like
$Mizu"Mizu".
The Mizu shown on the run is just a reminder message to let know which input are you giving value.

The programme is not stopped. It is waiting for your input.
In the input function you have to give some valut at the run time.
myName = input("Mizu"). In this line you have entered your question. You have to give answer at run time
myName = input("what is your name")

Related

Pre-inputting information in an input() function

I have a program that is executed. After that, the user has an option to load back their previous input() answers or to create a new one (just re-execute the program). The program is based on user input and so if I wanted to reload the user's previous inputs, is there a way to pre code an input with the user's previous answer? As a crude example of what my program does I just made this:
def program():
raw_input=input()
print("Would you like to reload previous program (press 1) or create new? (press 2)")
raw_input2=input()
if raw_input2==2:
program()
elif raw_input2==1:
#And here is where I would want to print another input with the saved 'raw_input' already loaded into the input box.
else:
print("Not valid")
For any confusion this is my original code:
while True:
textbox1=input(f" Line {line_number}: ")
line_number+=1
if textbox1:
commands.append(textbox1)
else: #if the line is empty finish inputting commands
break
print("\033[1m"+"*"*115+"\033[0m")
for cmd in commands:
execute_command(cmd)
line_numbers+=1
I tried creating a Python-like coding program using Python which generates new inputs (new lines) until you want to end your program by entering in nothing. This is only a snippet of my code of course. The problem I'm having is that after the user finished writing their basic program, whether you got an error because your code didn't make send or if it actually worked, I want there to be a 'cutscene' where it asks the user if they want to reload their previous program (because rewriting you program everytime there's an error is hard). I'm just asking whether I can do something like this: If my program was print("Hi"), and I wanted to reload it, I want to get an input; raw_input=input() but I want print("Hi") already inside the input().
This is not possible with the built-in input function. You will need a more fully-featured CLI library like readline or prompt-toolkit.
Some notes:
The input function always returns strings.
The while True keeps going until either 1 or 2 is entered
You can pass a string with the input-function call to specify what input is expexted.
If you put this in a loop you could re-ask the question, and you should then update the prev_answer variable each iteration.
prev_answer = 'abc'
while True:
raw_input2=input("Would you like to reload previous program (press 1) or create new? (press 2)")
if raw_input2=='2':
user_input = input('Please give your new input')
elif raw_input2=='1':
user_input = prev_answer
if raw_input2 in ('1','2'):
break
print(user_input)
Based on edit:
prev_answer = 'abc'
while True:
raw_input2=input("Would you like to reload previous program (press 1) or create new? (press 2)")
if raw_input2=='2':
user_input = input('Please give your new input')
elif raw_input2=='1':
print(prev_answer)
user_input = prev_answer + ' ' + input()
if raw_input2 in ('1','2'):
break

All lines of code not executing in python

why is only part of my code running in python?
I tried the same code in IDLE and SUBLIMETEXT and it only runs the first two lines and that is it.
as shown below
print("hello")
first = input("what is your firstname? ")
print("thanks")
surname = input("what is your surname? ")
Your code works fine. You may be confused with 2 things:
The input() function pauses the execution until you will finish entering something (or nothing) and pressing the Enter key.
After your last command, when you entered required info (your surname) and pressed the Enter key, there is no other command to print something.
So your program will finish silently, not using the last entered info (your surname).
It's waiting for the raw_input to run- raw_input is a function that waits for user input.
Try typing something in and pressing enter when the program asks What is your firstname?- the rest of the program will run.
I tried the code in CodeSculptor and it worked OK:
https://py3.codeskulptor.org/#user305_1ZWADnYLXt_0.py
You probably wanted a little modified version of your program:
print("hello")
first = input("what is your firstname? ")
surname = input("what is your surname? ")
print("thanks", first, surname)
The difference is in swapping the last 2 lines and adding the variables first and surname to the print() function (to display the entered info, i.e. the first name and the surname).
The output from doing it in the Python IDLE (after File→New, copy/paste the code into the new empty window, pressing F5, entering the name myprogram and pressing Enter; then — of course — entering names (John and Doe):
====== RESTART: C:/Program Files/Python36/Lib/idlelib/myprogram.py ======
hello
what is your firstname? John
what is your surname? Doe
thanks John Doe
>>>
In Sublime Text you need to install the SublimeREPL plugin.
Without it your program isn't able to accept user's input, so after your second command
first = input("what is your firstname? ")
it displays
hello
what is your firstname?
and waits for user input, but is unable to continue with the next one — there is no point in writing anything (your first name) to the prompt. (It will be displayed but your program will not accept it.)
After installing the SublimeREPL plugin, select
Tools → SublimeREPL → Python → Python-RUN current file.
Note: The “REPL” abbreviation means “Read-Evaluate-Print Loop”.
The code seems to be fine. Shouldn't be a problem in execution. It will take your first name as input, once you type that in and hit Enter, it will ask you for the surname.
TRY ADDING SEMICOLON AT THE END OF EACH LINE.
or maybe just type all of it in one line. For example:
print("Hello"); first = input("your first name"); print("HELLO 2"); second = input("your last name")

How do i use function call properly. I am gonna do 2 batch python script. The one is in input the other one is output

Lets say i have two batch python file.First one is hello.py. The next one is john.py
print('Hello world!')
print('What is your name?')
myName = input()
for Name in myName (1,10):
print('It is nice to meet you, ' + myName)
And how i want to do function call myname at john.py. Does i need to run 2 batch python at the same time. I am also bit confusing at line for Name in myName (1,10). What is meaning of that number.Please help me
To call function from the different file you need to import it.
E.g.
calculator.py
def greeting():
print('Hello world!')
print('What is your name?')
myName = input()
print('It is nice to meet you, ' + myName)
john.py
from calculator import greeting
greeting() # call imported function
As for loop statement it's invalid. Are you sure that it's correct?

Python input only accept one argument

I am writing a text game in python 3.3.4, at one point I ask for a name. Is there a a way to only accept one name, (one argument to the input) and if the user inputs more than one arg.
Here is what I currently have.
name =input('Piggy: What is your name?\n').title()
time.sleep(1)
print('Hello, {}. Piggy is what they call me.'.format(name))
time.sleep(1)
print('{}: Nice to meet you'.format(name))
time.sleep(1)
print('** Objective Two Completed **')
I am guessing I will need to use something like while, and then if and elif.
Help is greatly appreciated
while True:
name = input("What is your name? ").strip()
if len(name.split()) == 1:
name = name.title()
break
else:
print("Too long! Make it shorter!")

How to pause and wait for command input in a Python script

Is it possible to have a script like the following in Python?
...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script
Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.
What I come up with (inspired by the answer) is something like the following:
x = 1
i_cmd = 1
while True:
s = raw_input('Input [{0:d}] '.format(i_cmd))
i_cmd += 1
n = len(s)
if n > 0 and s.lower() == 'break'[0:n]:
break
exec(s)
print 'x = ', x
print 'I am out of the loop.'
if you are using Python 2.x: raw_input()
Python 3.x: input()
Example:
# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
The best way I know to do this is to use the pdb debugger. So put
import pdb
at the top of your program, and then use
pdb.set_trace()
for your "pause".
At the (Pdb) prompt you can enter commands such as
(Pdb) print 'x = ', x
and you can also step through code, though that's not your goal here. When you are done simply type
(Pdb) c
or any subset of the word 'continue', and the code will resume execution.
A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.
Waiting for user input to 'proceed':
The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:
var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')
Proceed after waiting pre-defined time:
Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.
import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds
Actual Debugger for executable Command Line:
Please see answers above on using pdb for stepping through code
Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
I think you are looking for something like this:
import re
# Get user's name
name = raw_input("Please enter name: ")
# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):
# Print out an error
print("illegal name - Please use only letters")
# Ask for the name again (if it's incorrect, while loop starts again)
name = raw_input("Please enter name: ")
Simply use the input() function as follows:
# Code to be run before pause
input() # Waits for user to type any character and
# press Enter or just press Enter twice
# Code to be run after pause

Categories

Resources