Python returns None to input [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Hey so I’m writing a text-adventure game in python and made a typingprint function to make the text look like it was typed out. But when I try to use this function with inputs it will reply with None.
import random
import time
import console
import sound
import sys
def typingPrint(text):
for character in text:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
console.set_color()
typingPrint('Hello! My name is Sawyer and I will be your guide
throughout this game. Heres a helpful hint, every time you enter
room you will have to battle a enemy.')
time.sleep(3)
player_name = input(typingPrint('\nBefore we begin why don\'t
you tell me your name: '))
How can I fix this?

This is because your function doesn't return anything so there is no text in the input prompt. To solve it, you will need to first call your function, then the input -
typingPrint('Hello! My name is Sawyer and I will be your guide throughout this game. Heres a helpful hint every time you enter a room you will have to battle a enemy.')
time.sleep(3)
typingPrint('\nBefore we begin why dont you tell me your name: ')
player_name = input()

Related

Learning IDLE for Python and I am getting stuck on the message 'continue' not in loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I am working on a course via Pluralsight called Building your first Python Analytics Solution. The current module is teaching about the IDE - IDLE. The demo I am following uses a prebuilt python file called price.py that is supposed to output a list of items along with the total price. Within the example the instructor is solving for a zero entry using except and continue, as show within the picture, which works when the instructor runs it. Course Example
But when I try to mirror the code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
price_data = pd.read_csv('~/Desktop/price.csv')
print(price_data.head())
price_data = price_data.fillna(0)
print(price_data.head())
def get_price_info():
for index, row in price_data.iterrows():
total_price = row['Total_Price']
quantity = row['Quantity']
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError :
continue
get_price_info()
plt.bar(price_data.Things, height=price_data.Total_Price)
plt.title('Barplot of Things vs Total_Price')
plt.show()
I get the error 'continue' not properly in the loop.
The course is using Python IDLE 3.8.
The current version that I am running is IDLE 3.10.4.
I have repeatedly gone over the code in the screenshot and it seems to me that the code is exactly the same. I have also researched the error and still could not come up with a solution that will allow me to run the script. I am really new at this and would love to understand where the issue is.
Based on a point, that the code did not match the screen shot. I reloaded the original price.py file and mage the edits needed to make it match. If I am still missing something I would be grateful to know where the mistake is.
After doing some research on try catch blocks I was able to edit the code
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError:
print("Make sure no divisions by 0 are made.")
except NameError:
print("Make sure both numbers are defined.")
and get the code to run. Thank you
Your try-except block is indented incorrectly: it runs after your for loop completes and therefore the continue statement is outside of the loop (invalid).
# loop begins
for index, row in price_data.iterrows():
total_price = row['Total_Price']
quantity = row['Quantity']
# loop ends
# try/catch begins
try:
price_of_a_unit = (total_price/quantity)
print(price_of_a_unit)
except ZeroDivisionError:
continue # outside of a loop - invalid
# try/catch ends

Why do I get "NameError: name 'B'/'C'/'V' is not defined"? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Question = input("Welcome to the meal chooser program. The base cost is $9.99. Would you like to choose beef, chicken, or the vegetarian option?:")
if Question.casefold() == "beef":
print("Thank you. Your total cost is","$",'{:.2f}'.format(B))
elif Question.casefold() == "chicken":
print("Thank you. Your total cost is","$", '{:.2f}'.format(C))
elif Question.casefold() == "vegetarian":
print("Thank you. Your total cost is","$", '{:.2f}'.format(V))
B = 9.99*1.02
C = 9.99*1.025
V = 9.99*1.03
Whenever I run this and input chicken, beef, or vegetarian it prompts me with a message that says that the values of B, C, and V are not defined, but they are.
Code runs (barring jumps like function calls and class initializations) linearly, top down. Because you initialize your variables at the bottom, your code has not created the values when you arrive at your if-else block. If you put your variables first, the code will run fine.

Syntax error for down()? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm a beginner computer science student and using python in computer science 1. My assignment is to write a program that creates a spirograph. I think that the code is all right to do that, but when i run it, an error message pops up that says syntax error and it highlights down(), which is a common turtle command. I have no idea why. It said syntax error for main(), but then i restarted python and now it says there's an error in down(). Here's the code:
from turtle import *
from math import *
def xValue(R,r,p,t):
x=(R-r)*cos(t)-(r+p)*cos((R-r)/r*t)
def yValue(R,r,p,t):
y=(R-r)*sin(t)-(r+p)*sin((R-r)/r*t)
def initialPosistion():
t=2*pi
up()
goto(xValue(R,r,p,t),yValue(R,r,p,t)
down()
def iterating(R,r,p):
t = 2*pi
while t < 0:
t = t-0.01
goto(xValue(R,r,p,t),yValue(R,r,p,t)
up()
def main():
R = 100
r = 4
p = int(input("Enter p(10-100): "))
if p < 10 or p > 100:
input("Incorrect value for p!")
iterating(R,r,p)
input("Hit enter to close...")
main()
Missed a closing ) at the end of this line:
goto(xValue(R,r,p,t),yValue(R,r,p,t))

Python autocomplete user input [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a list of teamnames. Let's say they are
teamnames=["Blackpool","Blackburn","Arsenal"]
In the program I ask the user which team he would like to do stuff with. I want python to autocomplete the user's input if it matches a team and print it.
So if the user writes "Bla" and presses enter, the team Blackburn should automatically be printed in that space and used in the rest of the code. So for example;
Your choice: Bla (User writes "Bla" and presses enter)
What it should look like
Your Choice: Blackburn (The program finishes the rest of the word)
teamnames=["Blackpool","Blackburn","Arsenal"]
user_input = raw_input("Your choice: ")
# You have to handle the case where 2 or more teams starts with the same string.
# For example the user input is 'B'. So you have to select between "Blackpool" and
# "Blackburn"
filtered_teams = filter(lambda x: x.startswith(user_input), teamnames)
if len(filtered_teams) > 1:
# Deal with more that one team.
print('There are more than one team starting with "{0}"'.format(user_input))
print('Select the team from choices: ')
for index, name in enumerate(filtered_teams):
print("{0}: {1}".format(index, name))
index = input("Enter choice number: ")
# You might want to handle IndexError exception here.
print('Selected team: {0}'.format(filtered_teams[index]))
else:
# Only one team found, so print that team.
print filtered_teams[0]
That depends on your usecase. If your program is commandline based, you can do that at least by using the readline module and pressing TAB. This link also provides some well explained examples on that since its Doug Hellmanns PyMOTW. If you are trying that via a GUI it depends on the API you are using. In that case you need to deliver some more details please.

(Python 2.7) easygui.choicebox if else statement how to [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to make a mac address spoofer in python for my mac as i find other software to be unnecessary advance/hard to understand. First i want a choicebox asking what device you want to spoof but i can not get the if else statement to work. The point if if coice is the first then input this value elif the choice is the second one input that value. If none of the above, you did somthing wrong. and i am running python 2.7
TlDr; If Else Statement do not work as i want (python 2.7).
Here is the code:
#_._# Mac Changer #_._#
import easygui
msg = "What Device do you want to spoof you're mac addresse?"
title = "SpoofMyMac"
choices = ["en0 (Ethernet)", "en1 (WiFi)"]
choice = easygui.choicebox(msg, title, choices)
#####################################
if choice == choice[0]: #
easygui.msgbox("Ethernet") #
elif choice == choice[1]: # This is where the problem seems to be.
easygui.msgbox("Wifi") #
else: #
easygui.msgbox("chus somthin!") #
#####################################
Now this is just the begining of the code, anyone care to help me out with this if else statement?
In advance Thank you! :)
From what I can see, you just have a typo. You want to index choices, not choice:
if choice == choices[0]:
#index choices ^
easygui.msgbox("Ethernet")
elif choice == choices[1]:
#index choices ^
easygui.msgbox("Wifi")
else:
easygui.msgbox("chus somthin!")

Categories

Resources